大图里面找小图
#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
#模板匹配方法1,SQDIFF
def match_sqdiff(tpl,target):
th,tw,_ = tpl.shape
dst = cv.matchTemplate(target,tpl,cv.TM_SQDIFF_NORMED)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
tl = min_loc
#print(tl)
br = (tl[0]+tw,tl[1]+th)
cv.rectangle(target,tl,br,(0,0,255),2)
return target
#模板匹配方法2,CCORR
def match_ccorr(tpl,target):
th,tw,_ = tpl.shape
dst = cv.matchTemplate(target,tpl,cv.TM_CCORR_NORMED)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
tl = max_loc
#print(tl)
br = (tl[0]+tw,tl[1]+th)
cv.rectangle(target,tl,br,(0,0,255),2)
return target
#模板匹配方法3,CCOEFF
def match_ccoeff(tpl,target):
th,tw,_ = tpl.shape
dst = cv.matchTemplate(target,tpl,cv.TM_CCOEFF_NORMED)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(dst)
tl = max_loc
#print(tl)
br = (tl[0]+tw,tl[1]+th)
cv.rectangle(target,tl,br,(0,0,255),2)
return target
def img_test():
imgtpl = cv.imread('E:/chenopencvblogimg/zhuqiutpl.jpg')
imgtarget = cv.imread('E:/chenopencvblogimg/zhuqiu.jpg')
#判断是否读取成功
if imgtpl is None or imgtarget is None:
print("Could not read the image,may be path error")
return
cv.namedWindow("origin imgtpl",cv.WINDOW_NORMAL)
cv.imshow("origin imgtpl",imgtpl)
cv.namedWindow("origin imgtarget",cv.WINDOW_NORMAL)
cv.imshow("origin imgtarget",imgtarget)
img_show = match_sqdiff(imgtpl,imgtarget)
cv.namedWindow("match_sqdiff",cv.WINDOW_NORMAL)
cv.imshow("match_sqdiff",img_show)
img_show = match_ccorr(imgtpl,imgtarget)
cv.namedWindow("match_ccorr",cv.WINDOW_NORMAL)
cv.imshow("match_ccorr",img_show)
img_show = match_ccoeff(imgtpl,imgtarget)
cv.namedWindow("match_ccoeff",cv.WINDOW_NORMAL)
cv.imshow("match_ccoeff",img_show)
#让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
cv.waitKey(0)
#销毁窗口
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(img_test() or 0)