使用模板匹配在圖像中尋找物體
模板匹配
模板匹配就是用來在大圖中找小圖,也就是說在一副圖像中尋找另外一張模板圖像的位置:
opencv中用 cv.matchTemplate() 實現模板匹配。
模板匹配的原理其實很簡單,就是不斷地在原圖中移動模板圖像去比較,有6種不同的比較方法,詳情可參考:TemplateMatchModes
1. 平方差匹配CV_TM_SQDIFF:用兩者的平方差來匹配,最好的匹配值為0
2. 歸一化平方差匹配CV_TM_SQDIFF_NORMED
3. 相關匹配CV_TM_CCORR:用兩者的乘積匹配,數值越大表明匹配程度越好
4. 歸一化相關匹配CV_TM_CCORR_NORMED
5. 相關系數匹配CV_TM_CCOEFF:用兩者的相關系數匹配,1表示完美的匹配,-1表示最差的匹配
6. 歸一化相關系數匹配CV_TM_CCOEFF_NORMED
歸一化的意思就是將值統一到0~1,這些方法的對比代碼可到源碼處查看。模板匹配也是應用卷積來實現的:假設原圖大小為W×H,模板圖大小為w×h,那么生成圖大小是(W-w+1)×(H-h+1),生成圖中的每個像素值表示原圖與模板的匹配程度。
實驗:源圖像中匹配模板圖像
源圖像:
模板圖像:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 1.模板匹配
img = cv.imread('lena.jpg', 0)
template = cv.imread('face.jpg', 0)
h, w = template.shape[:2] # rows->h, cols->w
# 6種匹配方法
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
for meth in methods:
img2 = img.copy()
# 匹配方法的真值
method = eval(meth)
res = cv.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
# 如果是平方差匹配TM_SQDIFF或歸一化平方差匹配TM_SQDIFF_NORMED,取最小值
if method 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(img2, top_left, bottom_right, 255, 2)
plt.subplot(121), plt.imshow(res, cmap='gray')
plt.xticks([]), plt.yticks([]) # 隱藏坐標軸
plt.subplot(122), plt.imshow(img2, cmap='gray')
plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
實驗結果
匹配多個物體
前面我們是找最大匹配的點,所以只能匹配一次。我們可以設定一個匹配閾值來匹配多次:
實驗:匹配圖像中的硬幣
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 2.匹配多個物體
img_rgb = cv.imread('mario.jpg')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('mario_coin.jpg', 0)
h, w = template.shape[:2]
res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
threshold = 0.8
# 取匹配程度大於%80的坐標
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]): # *號表示可選參數
bottom_right = (pt[0] + w, pt[1] + h)
cv.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2)
cv.imshow('img_rgb', img_rgb)
cv.waitKey(0)
cv.destroyAllWindows()
代碼難點講解
第3步有幾個Python/Numpy的重要知識:
x = np.arange(9.).reshape(3, 3)
print(np.where(x > 5))
# 結果:(array([2, 2, 2]), array([0, 1, 2]))
zip()函數,功能強大到難以解釋,舉個簡單例子就知道了:
x = [1, 2, 3]
y = [4, 5, 6]
print(list(zip(x, y))) # [(1, 4), (2, 5), (3, 6)]