ocr - 使用 Tesseract 进行 OCR 匹配模板感兴趣区域 (ROI)
问题描述
这是我第一次尝试使用 Python。我通常使用 .NET,但为了识别文档中的形状,我转向 Python 和 OpenCV 进行图像处理。
我正在使用 OpenCV TemplateMatching (cv2.matchTemplate) 在我的文档中发现感兴趣的区域 (ROI)。
这很好用。模板匹配 ROI 并放置矩形,识别匹配。
我图像中的 ROI 包含我还需要 OCR 和提取的文本。我正在尝试使用 Tesseract 来做到这一点,但根据我的结果,我认为我的做法是错误的。
我的流程是这样的:
- 运行 cv2.matchTemplate
- 循环匹配的 ROI
- 添加矩形信息。印象
- 传递矩形信息。到正方体
- 将从 tesseract 返回的文本添加到图像
- 写出最终图像
在下图中,您可以看到匹配的区域(很好),但您可以看到 ROI 中的文本与 tesseract 中的文本(ROI 的右下角)不匹配。
请有人看一下并建议我哪里出错了?
import cv2
import numpy as np
import pytesseract
import imutils
img_rgb = cv2.imread('images/pd2.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('images/matchMe.png', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.45
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
roi = img_rgb[pt, (pt[0] + w, pt[1] + h)]
config = "-l eng --oem 1 --psm 7"
text = pytesseract.image_to_string(roi, config=config)
print(text)
cv2.putText(img_rgb, text, (pt[0] + w, pt[1] + h),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)
cv2.imwrite('images/results.png', img_rgb)
解决方案
您的代码中有两个问题:1.您在 OCR 之前修改图像(绘制矩形)。2. roi 构造不正确。
img_rgb = cv2.imread('tess.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('matchMe.png', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.45
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
roi = img_rgb[pt[1]:pt[1] + h, pt[0]: pt[0] + w]
config = "-l eng --oem 1 --psm 7"
text = pytesseract.image_to_string(roi, config=config)
print(text)
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.putText(img_rgb, text, (pt[0] + w, pt[1] + h),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)
cv2.imwrite('results.png', img_rgb)
您可能仍然需要提供 tesseract 甚至正确过滤的图像才能进行任何有意义的识别。希望这可以帮助。
推荐阅读
- postgresql - pg_upgrade 期间的 postgres 超级用户问题
- java - 我可以在我的 Java 应用程序中安装嵌入 Neo4j 的图形数据科学 (GDS) 库吗?
- r - If else 语句的值是 R 中连续字符的一部分
- xml - 将“固定”键添加到引用的属性不起作用
- scp - 不再支持 SSH 协议 v.1
- python - 为什么我的 while 循环不会结束我的石头、纸、剪刀游戏?
- python - Python 请求包含有值的参数和没有值的参数
- sql - SQL 查询结果到已创建的表中
- python - 如何在 for 循环中移动多个海龟?
- c - CS50,预设 1,马里奥更舒适 - 错误:预期表达