opencv模板匹配相同位置去除重复的框
使用opencv自帶的模板匹配
1、目標匹配函數:cv2.matchTemplate()
res=cv2.matchTemplate(image, templ, method, result=None, mask=None)
image:待搜索圖像
templ:模板圖像
result:匹配結果
method:計算匹配程度的方法,主要有以下幾種:
CV_TM_SQDIFF?? ?平方差匹配法:該方法采用平方差來進行匹配;最好的匹配值為0;匹配越差,匹配值越大。
CV_TM_CCORR?? ?相關匹配法:該方法采用乘法操作;數值越大表明匹配程度越好。
CV_TM_CCOEFF?? ?相關系數匹配法:1表示完美的匹配;-1表示最差的匹配。
CV_TM_SQDIFF_NORMED?? ?計算歸一化平方差,計算出來的值越接近0,越相關
CV_TM_CCORR_NORMED?? ?計算歸一化相關性,計算出來的值越接近1,越相關
CV_TM_CCOEFF_NORMED?? ?計算歸一化相關系數,計算出來的值越接近1,越相關
待檢測的圖片如下,需要檢測里面金幣的位置
需要檢測金幣的模板如下:
2、基本的多對象模板匹配效果代碼如下:
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("001.jpg",img_rgb) cv2.imshow('img_rgb', img_rgb) cv2.waitKey(0)檢測效果如下:
通過上圖可以看到對同一個圖有多個框標定,需要去重,只需要保留一個
解決方案:對于使用同一個待檢區域使用NMS進行去掉重復的矩形框
3、使用NMS對模板匹配出來的矩形框進行去掉臨近重復的,代碼如下:
import cv2 import time import numpy as npdef 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算出來會是負數,用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 keepdef 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]#大于模板閾值的目標置信度#將模板數據坐標進行處理成左上角、右下角的格式xmin = np.array(loc[1])ymin = np.array(loc[0])xmax = xmin+wymax = ymin+hxmin = 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)#打印數據處理到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)#轉化成灰色template_img = cv2.imread('mario_coin.jpg', 0)#模板小圖template_threshold = 0.8#模板置信度dets = template(img_gray,template_img,template_threshold)count = 0for 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)檢測效果如下所示:
參考資料:
- https://blog.csdn.net/qq_39507748/article/details/104598222
- https://docs.opencv.org/3.4/d4/dc6/tutorial_py_template_matching.html
- https://blog.csdn.net/mdjxy63/article/details/81037860
- https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py
- https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/
總結
以上是生活随笔為你收集整理的opencv模板匹配相同位置去除重复的框的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: opencv--检测图片中的圆形
- 下一篇: 会爬行的小乌龟