Obtener salida solo de la primera página TIFF al extracto hocr

Obtener salida solo de la primera página TIFF al extracto hocr

[Imagen de muestra]

Busco su orientación en el código que figura a continuación. Estoy ejecutando este código para extraer texto de TIFF de varias páginas al formato hocr. Obtengo un resultado de la primera página de TIFF, pero el resto de las páginas se omiten.

# Python program to extract text from all the images in a folder
# storing the text in corresponding files in a different folder
# This is for hocr output, but there is error of getting only 1 page
    
from PIL import Image
import pytesseract as pt
import os
pt.pytesseract.tesseract_cmd = r'C:\Users\admin\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
     
def main():
    # path for the folder for getting the raw images
    path ="D:\\input"
    # path for the folder for getting the output
    tempPath ="D:\\output"
 
    # iterating the images inside the folder
    for imageName in os.listdir(path):
             
        inputPath = os.path.join(path, imageName)
        img = Image.open(inputPath)
 
        # applying ocr using pytesseract for python
           
        text = pt.image_to_pdf_or_hocr(img, extension = 'hocr', config = (r'--oem 3 --psm 6'), lang ="eng")
         
        fullTempPath = os.path.join(tempPath, 'time_'+imageName+".hocr")
        print(text)
  
        # saving the text for every image in a separate .hocr file
        file1 = open(fullTempPath, "wb")
        file1.write(text)
        file1.close()
  
 
if __name__ == '__main__':
    main()

Respuesta1

EDITAR:

Revisé que puede obtenerse filenameen lugar dePILLOW.Image

text = pt.image_to_pdf_or_hocr('D:\\input\\Best time to visit.tiff', extension='hocr', config=(r'--oem 3 --psm 6'), lang="eng")

Por lo tanto, puede ejecutarse tesseractcon el original tiffy convertir todas las páginas en un solo texto hocr.


RESPUESTA ORIGINAL:

Tomé tu tiffcódigo y el enlace de mi comentario y creé un código que guarda cada página en un archivo separado. Se utiliza img.seek(page)para seleccionar la página. Y me funciona con tu archivo.

from PIL import Image
import os

folder = '/home/furas/Desktop'
filename = 'Best time to visit.tiff'

img = Image.open(os.path.join(folder, filename))

page = 0

while True:
    try:
        img.seek(page)

        filename = f'page-{page+1}.png'
        print('saving...', filename)

        img.save(os.path.join(folder, filename))

        page += 1
    except EOFError:
        # Not enough frames in img
        break

Algo similar me funciona en tu código.

from PIL import Image
import pytesseract as pt
import os

pt.pytesseract.tesseract_cmd = r'C:\Users\admin\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
     
# path for the folder for getting the raw images
path = "D:\\input"

# path for the folder for getting the output
tempPath = "D:\\output"

# iterating the images inside the folder
for imageName in os.listdir(path):
 
    # only images   
    if imageName.lower().endswith(('.tiff', '.jpg', '.png')):
        print(imageName)
        
        inputPath = os.path.join(path, imageName)
        img = Image.open(inputPath)
    
        page = 0
        while True:
            try:
        
                img.seek(page)
                text = pt.image_to_pdf_or_hocr(img, extension='hocr', config=(r'--oem 3 --psm 6'), lang="eng")
        
                print('page...', page)
                page += 1
         
                fullTempPath = os.path.join(tempPath, f"time_{imageName}_{page}.hocr")
                #print(text)
        
                # saving the text for every image in a separate .hocr file
                file1 = open(fullTempPath, "wb")
                file1.write(text)
                file1.close()
            except EOFError:
                # Not enough frames in img
                break            

Tiene que escribir cada página por separado .hocrporque si intenta escribir muchas .hocren un archivo, se crean archivos rotos..hocr

Para escribir todas las páginas en un archivo, necesitará utilizar texto sin formato.

información relacionada