前面我们使用模板匹配,得到的结果都是一个图,那么如果我们图片中有许多我们的目标,那么该如何找出来呢?
如上我们图片中有许多箭头和我们的模板一致,只不过方向不对,那么该如何匹配呢?
图片和模板处理
ref=cv2.imread('jiantou.jpg')
cv2.imshow('jiantou', jt)
cv2.waitKey(0)
h,w= ref.shape[:2]
yuan=cv2.imread('yuan.jpg')
yuan1=yuan.copy()
cv2.imshow("yuan", yuan)
cv2.waitKey(0)
阈值选择
result = cv2.matchTemplate(ref, yuan1, cv2.TM_CCOEFF_NORMED)
threshold =0.9
loc = np.where(result >= threshold)
我们得到的results是一个包含许多匹配度的,如何我们这里使用一个阈值来选择,之前我们选择的都是那个最大的。现在我们选匹配度较好的几个。(where具体看我主页单文章解释)
这里result是一个矩阵,表示以哪一个点做左上角时的匹配度。如何where可以返回这个点的位置。
画出
for pt in zip(*loc[::-1]):
cv2.rectangle(yuan,pt,(pt[0]+w,pt[1]+h),(0,0,255),1)

现在我们值画出了同方向的,那么我们该如何检测不同方向的呢?
旋转
rotated_image1 =np.rot90(ref, k=-1)
rotated_image1 =np.rot90(ref, k=1)
这里k=-1顺时针,k=1为逆时针
这是我们可以把箭头旋转一下,如何再进行模板匹配。(关于zip我另一篇文章专门写)
rotated_image1 =np.rot90(ref, k=-1)
result1 = cv2.matchTemplate(rotated_image1, yuan1, cv2.TM_CCOEFF_NORMED)
loc1 = np.where(result1 >= threshold)
for pt in zip(*loc1[::-1]):
cv2.rectangle(yuan,pt,(pt[0]+w,pt[1]+h),(0,0,255),1)
cv2.imshow('yuan', yuan)
cv2.waitKey(0)
rotated_image2 =np.rot90(ref, k=1)
cv2.imshow("yuan1", rotated_image2)
cv2.waitKey(0)
result2 = cv2.matchTemplate(rotated_image2, yuan1, cv2.TM_CCOEFF_NORMED)
loc2 = np.where(result2 >= threshold)
for pt in zip(*loc2[::-1]):
cv2.rectangle(yuan,pt,(pt[0]+w,pt[1]+h),(0,0,255),1)
cv2.imshow("yuan", yuan)
cv2.waitKey(0)
