Using PDF file in Keras OCR or PyTesseract - Python, is it possible?

Viewed 42

I am using Keras OCR and PyTesseract and was wondering if it is possible to use PDF files as the image input.

If not, does anyone have a suggestion as to how to convert a very massive PDF file into PNG or another acceptable format?

Thank you!

2 Answers

No, as far as I know PyTesseract works only with images. You'll need to convert your pdf to images first.

By "very massive PDF" I'm assuming you mean a pdf with lots of pages. This is not an issue. You can use pdf2image library (see the docs here). The method convert_from_path has an output_folder argument that lets you specify the folder where all your generated images will be saved:

Output directory for the generated files, should be seen more as a “working directory” than an output folder. The converted images will be written there to save system memory.

You can later use them one by one instead of your pdf to work with PyTesseract. If you don't assign the returned list of images from convert_from_path you don't risk filling up your memory.

Otherwise, if you are willing to keep everything in memory you can use the returned pages directly, like so:

pages = convert_from_path(pdf_path)

for example, my code : Python : 3.9 Macos: BigSur

from PIL import Image from fonctions_images import * from pdf2image import convert_from_path

path='/Users/yves/documents_1/'
fichier =path+'TOUTOU.pdf'
images = convert_from_path(fichier,500, transparent=True,grayscale=True,poppler_path='/usr/local/Cellar/poppler/21.12.0/bin')

for v in range(0,len(images)):
    image=images[v]
    image.save(path+"image.png", format="png")
    test=path+"image.png"
    img = cv2.imread(test) # to store image in memory
    img = del_lines(path,img) # to supprime the lines
    img = cv2.imread(path+"img_final_bin_1.png")
    pytesseract.pytesseract.tesseract_cmd = "/usr/local/bin/tesseract"

    d=pytesseract.image_to_data(img[3820:4050,2340:4000], lang='fra',config=custom_config,output_type='data.frame')
Related