opencv for python 之 模板匹配

import cv2.cv as cv

#load image
filename = "../Video/cat.jpg"
image = cv.LoadImage(filename)


#create one window
win_name = "test"
cv.NamedWindow(win_name)
win2_name = "test2"
cv.NamedWindow(win2_name)


#take off one template
rect = (170,80,50,50)
cv.SetImageROI(image, rect)
template = cv.CloneImage(image)
cv.ShowImage(win_name, template)

 

cv.ResetImageROI(image)
W,H=cv.GetSize(image)
w,h=cv.GetSize(template)
width=W-w+1
height=H-h+1
result=cv.CreateImage((width,height),32,1)

result 是一个矩阵,存储了模板与源图像每一帧相比较后的相似值,
cv.MatchTemplate(image,template, result,cv.CV_TM_SQDIFF)

下面的操作将从矩阵中找到相似值最小的点,从而定位出模板位置
(min_x,max_y,minloc,maxloc)=cv.MinMaxLoc(result)
(x,y)=minloc
cv.Rectangle(image,(int(x),int(y)),(int(x)+w,int(y)+h),(255,255,255),1,0)
cv.ShowImage(win2_name, image)

cv.WaitKey()

模板匹配结果

opencv for python 之 模板匹配_第1张图片

你可能感兴趣的:(python,python)