模板匹配
作者:互联网
模板单个匹配
def all_operate(file1="lena.jpg",file2="face.jpg"):
img = cv.imread(file1,0)
template = cv.imread(file2,0)
h,w = template.shape[:2]
print (h,w)
methods =[cv.TM_CCOEFF,cv.TM_CCOEFF_NORMED,cv.TM_CCORR,cv.TM_CCORR_NORMED,cv.TM_SQDIFF,cv.TM_SQDIFF_NORMED]
method =["cv.TM_CCOEFF","cv.TM_CCOEFF_NORMED","cv.TM_CCORR","cv.TM_CCORR_NORMED","cv.TM_SQDIFF","cv.TM_SQDIFF_NORMED"]
num=1
fig = plt.figure(figsize=(10,25))#创建多个子图
for meth in methods:
img_ = img.copy()
res = cv.matchTemplate(img_,template,meth)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(res)
if meth in [cv.TM_SQDIFF,cv.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0]+w,top_left[1]+h)
cv.rectangle(img_,top_left,bottom_right,255,2)
fig.add_subplot(3,4,num)
plt.imshow(res,cmap="gray")
plt.xticks([]),plt.yticks([])
num+=1
fig.add_subplot(3,4,num)
plt.imshow(img_,cmap="gray")
plt.xticks([]),plt.yticks([])
plt.title(method[int(num/2-1)])
num+=1
plt.show()
模板多个匹配
def all_tem_match(file1="mario.jpg",file2="mario_coin.jpg"):
img = cv.imread(file1,1)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
template = cv.imread(file2,0)
h,w = template.shape[:2]
res = cv.matchTemplate(gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res>=threshold)
for pt in zip(*loc[::-1]):
bottom_right = (pt[0]+w,pt[1]+h)
cv.rectangle(img,pt,bottom_right,(0,0,255),2)
cv.imshow("img",img)
cv.waitKey(0)
cv.destroyAllWindows()
标签:plt,匹配,img,SQDIFF,TM,NORMED,cv,模板 来源: https://blog.csdn.net/qq_38641985/article/details/115216761