以下のコードについてご指導をお願いします。このコードを実行して、複数ページの TIFF から hocr 形式にテキストを抽出しています。TIFF の最初のページから出力を取得していますが、残りのページは省略されています。
# 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()
答え1
編集:
filename
代わりに取得できることを確認しましたPILLOW.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")
tesseract
したがって、オリジナルで実行できtiff
、すべてのページを 1 つのテキストに変換できますhocr
。
元の回答:
私はtiff
コメントのリンクからあなたのコードを取得し、各ページを別々のファイルに保存するコードを作成しました。これはimg.seek(page)
ページを選択するために使用します。そして、それはあなたのファイルで私にとってはうまく機能します。
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
あなたのコードでも同様のことが起こります
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
各ページを別々に書き込む必要があります。1つのファイルに.hocr
多くのページを書き込もうとすると、壊れたファイルが作成されます。.hocr
.hocr
すべてのページを 1 つのファイルに書き込むには、プレーン テキストを使用する必要があります。