图像与cvMatchTemplate图像 - 但如何?

时间:2013-01-23 18:04:08

标签: python image-processing opencv python-2.7 computer-vision

我想知道某个子图像出现在源图像的哪个位置(例如源图像:http://i.pictr.com/6xg895m69q.png,子图像:http://i.pictr.com/jdaz9zwzej.png)。据我所知,有必要转换数组以使它们对OpenCV“可读”,这是我尝试过的,但由于某些原因,它不起作用。这是我目前的代码:

 from PIL import Image
 import numpy
 from pylab import *
 import cv2
 import cv

 image = cv2.imread('source_img.jpg')
 template = cv2.imread('template_img.jpg')

 im = cv.fromarray(image)
 templ = cv.fromarray(template)
 result = numpy.zeros(shape=(1,10)) ##create a matrix with 0s
 a = cv.fromarray(result)
 cv.MatchTemplate(im, templ, a, cv.CV_TM_CCORR)
 print result
 print image

我的目标是在结果数组中写出子图像的坐标(数组的其余部分应该保持值0(我知道我的代码到目前为止还没有这个)。这个错误信息,我执行代码时得到:

  

OpenCV错误:断言失败(result.size()== cv :: Size(std :: abs(img.cols - templ.cols)+ 1,std :: abs(img.rows - templ.rows) cvMatchTemplate中的+ 1)&& result.type()== CV_32F),文件/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/OpenCV-2.4.3/modules/imgproc /src/templmatch.cpp,第376行   Traceback(最近一次调用最后一次):     文件“/Users/strongbow/imagerecognition.py”,第27行,in       cv.MatchTemplate(im,templ,a,cv.CV_TM_CCORR)   cv2.error:result.size()== cv :: Size(std :: abs(img.cols - templ.cols)+ 1,std :: abs(img.rows - templ.rows)+ 1)& &安培; result.type()== CV_32F

我是OpenCV的新手,并且真的不知道如何处理此错误消息。任何想法/指针做什么?

2 个答案:

答案 0 :(得分:8)

import sys
import cv2
import numpy

img = cv2.imread(sys.argv[1])
template = cv2.imread(sys.argv[2])
th, tw = template.shape[:2]

result = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED)
threshold = 0.99
loc = numpy.where(result >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img, pt, (pt[0] + tw, pt[1] + th), 0, 2)

cv2.imwrite(sys.argv[3], img)

enter image description here

答案 1 :(得分:5)

import cv2
from cv2 import cv

image = cv2.imread('1_tree.jpg')
template = cv2.imread('1_tree_detail.jpg')

values = cv2.matchTemplate(image, template, method=cv.CV_TM_SQDIFF)
best_fit_point = cv2.minMaxLoc(values)[2]
bottom_right = best_fit_point[0]+template.shape[0], best_fit_point[1]+template.shape[1]
cv2.rectangle(image, best_fit_point, bottom_right, (255,255,255))
cv2.imshow('tree',image)
cv2.imwrite('tree_match.jpg', image)
cv2.waitKey()

enter image description here enter image description here enter image description here