Python+Opencv實現(xiàn)圖像匹配功能(模板匹配)
本文實例為大家分享了Python+Opencv實現(xiàn)圖像匹配功能的具體代碼,供大家參考,具體內(nèi)容如下
1、原理
簡單來說,模板匹配就是拿一個模板(圖片)在目標圖片上依次滑動,每次計算模板與模板下方的子圖的相似度,最后就計算出了非常多的相似度;
如果只是單個目標的匹配,那只需要取相似度最大值所在的位置就可以得出匹配位置;
如果要匹配多個目標,那就設(shè)定一個閾值,就是說,只要相似度大于比如0.8,就認為是要匹配的目標。

1.1 相似度度量指標
- 差值平方和匹配 CV_TM_SQDIFF
- 標準化差值平方和匹配 CV_TM_SQDIFF_NORMED
- 相關(guān)匹配 CV_TM_CCORR
- 標準相關(guān)匹配 CV_TM_CCORR_NORMED
- 相關(guān)匹配 CV_TM_CCOEFF
- 標準相關(guān)匹配 CV_TM_CCOEFF_NORMED
1.2 計算步驟
有一張模板圖像Templa和一張較大的待搜索圖像Image,模板匹配是一種用于在較大圖像中搜索和查找模板圖像位置的方法。
具體就是將模板圖像滑動到輸入圖像上(就像在卷積操作一樣),然后在模板圖像下比較模板和輸入圖像的子圖的相似度。
它返回一個灰度圖像,其中每個像素表示該像素的鄰域與模板匹配的相似度。如果輸入圖像的大小(WxH)和模板圖像的大小(wxh),則輸出圖像的大小將為(W-w+ 1,H-h + 1)。 獲得相似度圖像之后,在其上查找最大相似度所在的像素。將其作為匹配區(qū)域矩形的左上角,并以(w,h)作為矩形的寬度和高度。該矩形是與模板匹配的區(qū)域。
2、代碼實現(xiàn)
2.1 單模板匹配單個目標
代碼如下:
# 相關(guān)系數(shù)匹配方法: cv2.TM_CCOEFF
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
left_top = max_loc# 左上角
right_bottom = (left_top[0] + w, left_top[1] + h)# 右下角
cv2.rectangle(img, left_top, right_bottom, 255, 2) # 畫出矩形位置
plt.subplot(121), plt.imshow(res, cmap='gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img, cmap='gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.show()
2.2 單模板匹配多個目標
目標照片:mario.jpg

模板照片:mario_coin.jpg

代碼如下:
import cv2
import numpy as np
img_rgb = cv2.imread('mario.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.jpg', 0)
h, w = template.shape[:2]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
# 取匹配程度大于%80的坐標
loc = np.where(res >= threshold)
#np.where返回的坐標值(x,y)是(h,w),注意h,w的順序
for pt in zip(*loc[::-1]):
bottom_right = (pt[0] + w, pt[1] + h)
cv2.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2)
cv2.imwrite("img.jpg",img_rgb)
cv2.imshow('img', img_rgb)
cv2.waitKey(0)
檢測結(jié)果如下:

3、算法精度優(yōu)化
- 多尺度模板匹配
- 旋轉(zhuǎn)目標模板匹配
- 非極大值抑制
通過上圖可以看到對同一個圖有多個框標定,需要去重,只需要保留一個
解決方案:對于使用同一個待檢區(qū)域使用NMS(非極大值抑制)進行去掉重復(fù)的矩形框
NMS 原理
對于Bounding Box的列表B及其對應(yīng)的置信度S,采用下面的計算方式。選擇具有最大score的檢測框M,將其從B集合中移除并加入到最終的檢測結(jié)果D中。通常將B中剩余檢測框中與M的IoU大于閾值Nt的框從B中移除,重復(fù)這個過程,直到B為空。
ps. 重疊率(重疊區(qū)域面積比例IOU)常用的閾值是 0.3 ~ 0.5.
代碼如下:
import cv2
import time
import numpy as np
def py_nms(dets, thresh):
"""Pure Python NMS baseline."""
#x1、y1、x2、y2、以及score賦值
# (x1、y1)(x2、y2)為box的左上和右下角標
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
#每一個候選框的面積
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
#order是按照score降序排序的
order = scores.argsort()[::-1]
# print("order:",order)
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
#計算當前概率最大矩形框與其他矩形框的相交框的坐標,會用到numpy的broadcast機制,得到的是向量
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
#計算相交框的面積,注意矩形框不相交時w或h算出來會是負數(shù),用0代替
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
#計算重疊度IOU:重疊面積/(面積1+面積2-重疊面積)
ovr = inter / (areas[i] + areas[order[1:]] - inter)
#找到重疊度不高于閾值的矩形框索引
inds = np.where(ovr <= thresh)[0]
# print("inds:",inds)
#將order序列更新,由于前面得到的矩形框索引要比矩形框在原order序列中的索引小1,所以要把這個1加回來
order = order[inds + 1]
return keep
def template(img_gray,template_img,template_threshold):
'''
img_gray:待檢測的灰度圖片格式
template_img:模板小圖,也是灰度化了
template_threshold:模板匹配的置信度
'''
h, w = template_img.shape[:2]
res = cv2.matchTemplate(img_gray, template_img, cv2.TM_CCOEFF_NORMED)
start_time = time.time()
loc = np.where(res >= template_threshold)#大于模板閾值的目標坐標
score = res[res >= template_threshold]#大于模板閾值的目標置信度
#將模板數(shù)據(jù)坐標進行處理成左上角、右下角的格式
xmin = np.array(loc[1])
ymin = np.array(loc[0])
xmax = xmin+w
ymax = ymin+h
xmin = xmin.reshape(-1,1)#變成n行1列維度
xmax = xmax.reshape(-1,1)#變成n行1列維度
ymax = ymax.reshape(-1,1)#變成n行1列維度
ymin = ymin.reshape(-1,1)#變成n行1列維度
score = score.reshape(-1,1)#變成n行1列維度
data_hlist = []
data_hlist.append(xmin)
data_hlist.append(ymin)
data_hlist.append(xmax)
data_hlist.append(ymax)
data_hlist.append(score)
data_hstack = np.hstack(data_hlist)#將xmin、ymin、xmax、yamx、scores按照列進行拼接
thresh = 0.3#NMS里面的IOU交互比閾值
keep_dets = py_nms(data_hstack, thresh)
print("nms time:",time.time() - start_time)#打印數(shù)據(jù)處理到nms運行時間
dets = data_hstack[keep_dets]#最終的nms獲得的矩形框
return dets
if __name__ == "__main__":
img_rgb = cv2.imread('mario.jpg')#需要檢測的圖片
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)#轉(zhuǎn)化成灰色
template_img = cv2.imread('mario_coin.jpg', 0)#模板小圖
template_threshold = 0.8#模板置信度
dets = template(img_gray,template_img,template_threshold)
count = 0
for coord in dets:
cv2.rectangle(img_rgb, (int(coord[0]),int(coord[1])), (int(coord[2]),int(coord[3])), (0, 0, 255), 2)
cv2.imwrite("result.jpg",img_rgb)
檢測結(jié)果如下:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信