【问题标题】:Error setting psm for pytesseract为 pytesseract 设置 psm 时出错
【发布时间】:2017-09-01 17:54:32
【问题描述】:

我正在尝试对 pytesseract 使用 0 的 psm,但出现错误。我的代码是:

import pytesseract
from PIL import Image
img = Image.open('pathToImage')
pytesseract.image_to_string(img, config='-psm 0')

出现的错误是

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/pytesseract/pytesseract.py", line 126, in image_to_string
f = open(output_file_name, 'rb')
IOError: [Errno 2] No such file or directory: 
'/var/folders/m8/pkg0ppx11m19hwn71cft06jw0000gp/T/tess_uIaw2D.txt'

当我进入“/var/folders/m8/pkg0ppx11m19hwn71cft06jw0000gp/T”时,有一个名为 tess_uIaw2D.osd 的文件似乎包含我正在寻找的输出信息。似乎 tesseract 正在将文件保存为 .osd,然后查找该文件但扩展名为 .txt。当我使用 --psm 0 通过命令行运行 tesseract 时,它将输出文件保存为 .osd 而不是 .txt。

pytesseract 的 image_to_string() 通过将输出文件保存在某处然后自动读取该输出文件来工作是否正确?有什么方法可以设置 tesseract 将文件保存为 .txt,或者将其设置为查找 .osd 文件?当我不设置 psm 时,我只运行 image_to_string() 函数没有问题。

【问题讨论】:

    标签: python tesseract file-extension python-tesseract


    【解决方案1】:

    您有几个问题:

    1. PSM 错误

      • 在您的问题中,您提到您在命令行中运行"--psm 0"。但是,在您的代码片段中,您有 "-psm 0"
      • 使用双破折号config= "--psm 0" 将解决该问题。
    2. 如果您阅读了 tesseract 命令行文档,您可以指定从图像中读取的文本的输出位置。我建议你从那里开始。

    3. pytesseract 的 image_to_string() 通过将输出文件保存在某处然后自动读取该输出文件来工作是否正确?

      • 从我对 tesseract 的使用来看,这不是它的工作原理
      • pytesseract.image_to_string() 默认返回图片上的字符串。当您查看函数 image_to_string 时,这是由参数 output_type=Output.STRING 定义的。
      • 其他返回选项包括 (1) Output.BYTES 和 (2) Output.DICT
      • 我通常有text = pytesseract.image_to_string(img)之类的东西
      • 然后我将该文本写入日志文件
      • 这是一个例子:
    import datetime
    import io
    import pytesseract
    import cv2
    
    img = cv2.imread("pathToImage")
    text = pytesseract.image_to_string(img, config="--psm 0")
    ocr_log = "C:/foo/bar/output.txt"
    timestamp_fmt = "%Y-%m-%d_%H-%M-%S-%f"
    
    # ...
    # DO SOME OTHER STUFF BEFORE WRITING TO LOG FILE
    # ...
    
    with io.open(ocr_log, "a") as ocr_file:
        timestamp = datetime.datetime.now().strftime(timestamp_fmt)
        ocr_file.write(f"{timestamp}:\n====OCR-START===\n")
        ocr_file.write(text)
        ocr_file.write("\n====OCR-END====\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 2017-09-28
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多