我正在尝试使用
mss
和 pytesseract
在 python 中创建实时 OCR。
到目前为止,我已经能够捕获整个屏幕,其 FPS 稳定为 30。如果我想捕获大约 500x500 的较小区域,我已经能够获得 100+ FPS。
但是,一旦我添加这行代码,
text = pytesseract.image_to_string(img)
,猛增 0.8 FPS。有什么方法可以优化我的代码以获得更好的 FPS?该代码还能够检测文本,只是速度非常慢。
from mss import mss
import cv2
import numpy as np
from time import time
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\\Users\\Vamsi\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'
with mss() as sct:
# Part of the screen to capture
monitor = {"top": 200, "left": 200, "width": 500, "height": 500}
while "Screen capturing":
begin_time = time()
# Get raw pixels from the screen, save it to a Numpy array
img = np.array(sct.grab(monitor))
# Finds text from the images
text = pytesseract.image_to_string(img)
# Display the picture
cv2.imshow("Screen Capture", img)
# Display FPS
print('FPS {}'.format(1 / (time() - begin_time)))
# Press "q" to quit
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
查看 pytesseract 代码后,我发现它会转换图像格式并保存在本地,然后再将其输入 tesseract。 通过从 PNG 更改为 JPG,我获得了 3 倍的加速(9.5 秒/图像 3 秒)。我想Python代码部分还可以做更多的优化。
您可以使用“easyocr”,这是一个轻量级的Python包,可用于OCR应用程序。它非常快速、可靠,可以访问 70 多种语言,包括英语、中文、日语、韩语、印地语,还有更多语言正在添加中。
“pip 安装 easyocr”
pytesseract “默认情况下”效率不高,因为它包装了 tesseract 可执行文件,它将临时文件保存到磁盘等...... 如果您认真对待性能,则需要直接使用 tesseract API(例如通过 tesserocr 或通过 创建自定义 API 包装器)
我也遇到了同样的问题。在本机桌面环境中对文档进行 OCR 需要 5 秒,而在同一台计算机上的 docker 中运行相同的文档则需要 200 多秒。
解决方案原来是添加:
ENV OMP_THREAD_LIMIT=1
到我的 dockerfile。
这会禁用超立方体中的多线程。为什么它在 docker 中运行得更快,我无法告诉你,但它对我来说使其接近本机性能。