【发布时间】:2016-03-05 21:30:17
【问题描述】:
我正在尝试使用模板匹配在从 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}
我编译并稍后使用pdfcrop 或使用PythonMagick 中的.image() 方法修剪方程周围的空白。在原始页面上使用此修剪输出生成的模板匹配不会给出合理的结果。这是使用 pdfcrop/Mac 的 Preview.app 修剪/转换的输出:
从上面的页面直接裁剪方程效果很好。我会很感激一些解释和帮助。
编辑: 我还发现以下内容通过暴力破解不同的可能比例来使用模板匹配: http://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/
但是,由于我愿意处理多达 1000 个文档,因此这似乎是一种非常缓慢的方法。另外,我想应该有一种更合乎逻辑的方式来处理它,通过某种方式找到相关的尺度。
【问题讨论】:
标签: python opencv pdf image-processing resolution