opencv for python 之 模板匹配

来源:互联网 发布:python 3pdf 编辑:程序博客网 时间:2024/05/24 02:38

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()

模板匹配结果


原创粉丝点击