OpenCV 中模板匹配的分辨率操作

Resolution Manipulation for Template Matching in OpenCV

我正在尝试使用模板匹配在从 LaTeX 生成的给定 pdf 文档中查找方程式。当我在 here 上使用代码时,当我从原始页面裁剪图片(转换为 jpeg 或 png)时,我只得到一个很好的匹配,但是当我单独编译等式代码并生成 jpg/png 它的输出匹配出现了巨大的错误。

我认为原因与分辨率有关,但由于我是该领域的业余爱好者,我无法合理地使独立方程生成的jpg在整个页面上具有与jpg相同的像素结构。这是从上述 OpenCV 网站复制(或多或少)的代码,它是 python:

的实现
import cv2
from PIL import Image

img = cv2.imread('location of the original image', 0)
img2 = img.copy()
template = cv2.imread('location of the patch I look for',0)
w, h = template.shape[::-1]

# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']

method = eval(methods[0])

# Apply template Matching
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
    top_left = min_loc
else:
    top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
print top_left, bottom_right

img = Image.open('location of the original image')

#cropping the original image with the found coordinates to make a qualitative comparison
cropped = img.crop((top_left[0], top_left[1], bottom_right[0], bottom_right[1]))
cropped.save('location to save the cropped image using the coordinates found by template matching')

这是我寻找第一个等式的示例页面:

生成具体独立方程的代码如下:

\documentclass[preview]{standalone}
\usepackage{amsmath}
\begin{document}\begin{align*}
(\mu_1+\mu_2)(\emptyset) = \mu_1(\emptyset) + \mu_2(\emptyset) = 0 + 0 =0
\label{eq_0}
\end{align*}
\end{document}

我编译然后 trim 方程周围的白色 space 使用 pdfcrop or using .image() method in PythonMagick。在原始页面上使用此 trimmed 输出生成的模板匹配未给出合理的结果。这是使用 pdfcrop/Mac 的 Preview.app:

的 trimmed/converted 输出

.

直接裁剪上述页面中的公式效果很好。我将不胜感激一些解释和帮助。

编辑: 我还发现以下内容通过暴力破解不同的可能比例来使用模板匹配: http://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/

然而,由于我愿意处理多达 1000 个文档,所以这似乎是一个非常缓慢的方法。另外,我想应该有一种更合乎逻辑的处理方式,通过某种方式找到相关的尺度。

模板匹配的问题在于它只适用于非常受控的环境。这意味着如果您从实际图像中获取模板,它会完美地工作,但如果分辨率不同或者即使图像有点转动,它也不会工作。

我建议你寻找另一种更适合这个问题的算法。在 OpenCV docs 中,您可以找到一些针对您的问题的特定算法。

您可以使用 features,即带有描述符的关键点,而不是模板匹配。它们是缩放不变的,因此您无需迭代图像的不同缩放版本。

python例子find_obj.py 对于您给定的示例,OpenCV 提供了 ORB 功能。

python find_obj.py --feature=brisk rB4Yy_big.jpg ZjBAA.jpg

请注意,我没有使用裁剪版的公式进行搜索,而是使用周围有一些白色像素的版本进行搜索,因此关键点检测可以正常工作。它周围需要一些 space,因为关键点必须完全在图像内部。否则无法计算描述符。

大图是您post的原图。

补充说明:您总是会得到 一些 匹配项。如果您要搜索的公式图像不存在于大图像中,则匹配将是无意义的。如果您需要理清这些误报,您有以下选择:


编辑:既然你要求了,这里是一个在找到的公式而不是匹配项周围绘制边界框的版本:

#!/usr/bin/env python

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2

def init_feature():
    detector = cv2.BRISK_create()
    norm = cv2.NORM_HAMMING
    matcher = cv2.BFMatcher(norm)
    return detector, matcher

def filter_matches(kp1, kp2, matches, ratio = 0.75):
    mkp1, mkp2 = [], []
    for m in matches:
        if len(m) == 2 and m[0].distance < m[1].distance * ratio:
            m = m[0]
            mkp1.append( kp1[m.queryIdx] )
            mkp2.append( kp2[m.trainIdx] )
    p1 = np.float32([kp.pt for kp in mkp1])
    p2 = np.float32([kp.pt for kp in mkp2])
    kp_pairs = zip(mkp1, mkp2)
    return p1, p2, kp_pairs

def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
    h1, w1 = img1.shape[:2]
    h2, w2 = img2.shape[:2]
    vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
    vis[:h1, :w1] = img1
    vis[:h2, w1:w1+w2] = img2
    vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

    if H is not None:
        corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]])
        corners = np.int32( cv2.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) )
        cv2.polylines(vis, [corners], True, (0, 0, 255))

    cv2.imshow(win, vis)
    return vis

if __name__ == '__main__':

    img1 = cv2.imread('rB4Yy_big.jpg' , 0)
    img2 = cv2.imread('ZjBAA.jpg', 0)
    detector, matcher = init_feature()

    kp1, desc1 = detector.detectAndCompute(img1, None)
    kp2, desc2 = detector.detectAndCompute(img2, None)

    raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
    p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
    if len(p1) >= 4:
        H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
        print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
        vis = explore_match('find_obj', img1, img2, kp_pairs, status, H)
        cv2.waitKey()
        cv2.destroyAllWindows()
    else:
        print('%d matches found, not enough for homography estimation' % len(p1))