gpt4 book ai didi

python - 如何用opencv自动调整模板匹配的阈值?

转载 作者:行者123 更新时间:2023-12-04 22:47:21 24 4
gpt4 key购买 nike

所以我使用 opencv 进行模板匹配,如下所示。我经常需要摆弄视觉相似性 #THRESHOLD ,因为它有时无法发现匹配项或返回太多匹配项。这是一个反复试验,直到它与文档中某个位置的 1 个元素完全匹配。我想知道是否有任何方法可以以某种方式自动执行此操作。

image.png 文件是 pdf 文档的图片。 template.png 文件是段落的图片。我的目标是发现 pdf 文档中的所有段落,我想知道什么神经网络在这里有用。

import cv2
import numpy as np


img = cv2.imread("image.png");
gimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE);
w, h = template.shape[::-1]


result = cv2.matchTemplate(gimg, template, cv2.TM_CCOEFF_NORMED)

loc = np.where(result >= 0.36) #THRESHOLD
print(loc)

for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,255,0), 3)

cv2.imwrite("output.png", img)

例如,它将搜索每个 #THRESHOLD值来自 01.0并返回一个阈值,该阈值返回图像中的单个矩形匹配(在上方绘制绿色框)。

但是,我不禁觉得这是非常详尽的,或者有没有更聪明的方法来找出阈值是多少?

最佳答案

由于评论很多,几乎没有任何回应,我将总结答案以供将来的读者使用。

首先,您的问题几乎与 How to detect paragraphs in a text document image for a non-consistent text structure in Python 相同。此外,该线程似乎解决了您正在解决的问题:Easy ways to detect and crop blocks (paragraphs) of text out of image?

其次,不应使用模板匹配 来检测 PDF 中的段落,而应使用以下方法之一:

  • 使用 canny edge detector in combination with dilation and F1 Score optimization. 这通常用于 fmw42 建议的 OCR。
  • 或者,您可以使用 Stroke Width Transform (SWT) 来识别文本,然后将其分组为行并最终分组,即段落。对于 OCR,这些块然后可以传递给 Tesseract(按照 fmw42 的建议)

  • 任何 OCR 任务的关键是通过根据需要更改图像来消除图像的破坏性特征,从而尽可能地简化文本检测问题。事先处理的图像信息越多越好: change colors, binarize, threshold, dilate, apply filters, etc.

    要回答关于在模板匹配中找到最佳匹配的问题 :
    结帐 nathancy's answer on template matching 。本质上,它归结为使用 minMaxLoc 找到最大相关值。请参阅 Nathancy 的回答的摘录:

        # Threshold resized image and apply template matching
    thresh = cv2.threshold(resized, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    detected = cv2.matchTemplate(thresh, template, cv2.TM_CCOEFF)
    (_, max_val, _, max_loc) = cv2.minMaxLoc(detected) ```


    此外,在 nathancy's answer in this thread 中可以找到从图像中提取文本块(不使用模板匹配)的综合指南。

    关于python - 如何用opencv自动调整模板匹配的阈值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923076/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com