首页 > 解决方案 > 如何使用 python tesseract 将所有类型的图像转换为文本

问题描述

我正在尝试使用 python tesseract 将文件夹中的所有类型的图像转换为文本。下面是我正在使用的,只有 .png 文件被转换为 .txt,其他类型没有被转换为文本。

import os
import pytesseract
import cv2
import re
import glob
import concurrent.futures
import time


def ocr(img_path):
    out_dir = "Output//"
    img = cv2.imread(img_path)
    text = pytesseract.image_to_string(img,lang='eng',config='--psm 6')
    out_file = re.sub(".png",".txt",img_path.split("\\")[-1])
    out_path = out_dir + out_file
    fd = open(out_path,"w")
    fd.write("%s" %text)
    return out_file

os.environ['OMP_THREAD_LIMIT'] = '1'
def main():
    path = input("Enter the path : ")
    if os.path.isdir(path) == 1:
        out_dir = "ocr_results//"
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)

        with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
            image_list = glob.glob(path+"\\*.*")
            for img_path,out_file in zip(image_list,executor.map(ocr,image_list)):
                print(img_path.split("\\")[-1],',',out_file,', processed')

if __name__ == '__main__':
    start = time.time()
    main()
    end = time.time()
    print(end-start)

如何将所有类型的图像文件转换为文本。请帮我处理上面的代码。

标签: python-tesseract

解决方案


函数中存在错误ocr

首先,以下确实将所有类型的图像文件转换为文本。

text = pytesseract.image_to_string(img,lang='eng',config='--psm 6'))

然而,下一段代码的作用是

  1. 使用正则表达式选择具有.png扩展名的文件
  2. 创建具有相同文件名和.txt扩展名的新路径
  3. 将 OCR 输出写入新创建的文本文件。

    out_file = re.sub(".png",".txt",img_path.split("\\")[-1])
    out_path = out_dir + out_file
    fd = open(out_path,"w")
    fd.write("%s" %text)
    

换句话说,所有类型的图像文件都已转换,但并非所有类型都正确写回。正则表达式匹配逻辑仅替换.png.txt并分配给out_path. 当没有.png(其他图像类型)时,变量获得与原始文件名相同的值(例如sampe.jpg)。接下来的代码行打开原始图像并用 OCR 结果覆盖。

一种解决方法是将要覆盖的所有图像格式添加到正则表达式中。

例如,

out_file = re.sub(".png|.jpg|.bmp|.tiff",".txt",img_path.split("\\")[-1])

推荐阅读