前面我們使用模板匹配,得到的結果都是一個圖,那么如果我們圖片中有許多我們的目標,那么該如何找出來呢?
如上我們圖片中有許多箭頭和我們的模板一致,只不過方向不對,那么該如何匹配呢?
圖片和模板處理
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)