首页 > 解决方案 > 使用 Tesseract 进行 OCR 匹配模板感兴趣区域 (ROI)

问题描述

这是我第一次尝试使用 Python。我通常使用 .NET,但为了识别文档中的形状,我转向 Python 和 OpenCV 进行图像处理。

我正在使用 OpenCV TemplateMatching (cv2.matchTemplate) 在我的文档中发现感兴趣的区域 (ROI)。

这很好用。模板匹配 ROI 并放置矩形,识别匹配。

我图像中的 ROI 包含我还需要 OCR 和提取的文本。我正在尝试使用 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)

标签: ocrpython-tesseractmatchtemplate

解决方案


您的代码中有两个问题: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 甚至正确过滤的图像才能进行任何有意义的识别。希望这可以帮助。


推荐阅读