【问题标题】:How do you use pytesseract in a flask app你如何在烧瓶应用程序中使用 pytesseract
【发布时间】:2020-12-29 14:17:01
【问题描述】:

我想构建一个烧瓶应用程序,允许用户上传带有文本的图像。然后我想让 pytesseract 提取文本并返回它。

我做了一些研究,发现了这篇文章: https://stackabuse.com/pytesseract-simple-python-optical-character-recognition/#disqus_thread

它几乎解释了我想要做什么。我唯一不明白的是我应该在哪里保存定义 ocr_core 函数的 OCR 脚本。因为在文章中他以后可以导入函数。

【问题讨论】:

    标签: python flask web-applications tesseract python-tesseract


    【解决方案1】:

    该文件应命名为ocr_core.py,并保存在与app.py 相同的目录中。

    考虑ocr_core.py

    try:
        from PIL import Image
    except ImportError:
        import Image
    import pytesseract
    
    def ocr_core(filename):
        """
        This function will handle the core OCR processing of images.
        """
        text = pytesseract.image_to_string(Image.open(filename))  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
        return text
    
    

    app.py 中,from ocr_core import ocr_core 行从模块ocr_core 导入函数ocr_core

    换句话说:from some_module import some_func 会从文件some_module.py 中的some_module 模块导入some_func 函数。

    教程也有,在ocr_core.py结尾处:

    print(ocr_core('images/ocr_example_1.png'))
    

    从技术上讲,该行将在 app.py 中运行导入的位置执行。它看起来像是用于测试功能的一条线。通常这应该在一个块中:

    if __name__ == '__main__':
        print(ocr_core('images/ocr_example_1.png'))
    

    这意味着它只会在您使用 python 解释器python ocr_core.py 运行时执行 - 而不是在某个地方导入该模块时。根据教程,当您启动 Flask 服务器时会运行打印行,这可能是不可取的。

    【讨论】:

    • 但是我需要在哪里安装 tesseract?在同一个目录下?
    • 这取决于操作系统。您需要将代码指向 tesseract 二进制文件,本教程似乎没有提及。 see this answer for *nix。您可能应该在import pytesseract 之后直接设置它。这一点在官方USAGE instructions中也有说明。
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多