import cv2 import numpy as np img=cv2.imread("AAA.jpg") gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #取图像中的某个区域作为特征模板,将模板放入match中 template=gray[50:100,50:100] #将模板与图像进行匹配,得出的匹配系数放入match中 match=cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED) #找出匹配系数大于0.9的匹配点放入locations中 locations=np.where(match>=0.9) #求出模板图案的长和宽,shape函数就是读取矩阵的行列数, #shape[0]图片高 #shape[1]图片长 #shape[2]图片通道数 w,h=template.shape[0:2] #为每个特征匹配的图像画方框 for p in zip(*locations[::-1]): x1,y1=p[0],p[1] x2,y2=x1+w,y1+h cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2) cv2.imshow("img",img) cv2.waitKey()