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 cv2import numpy as npimg_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 cv2import timeimport 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算出来会是负数,用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]#大于模板阈值的目标置信度    #将模板数据坐标进行处理成左上角、右下角的格式    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)#打印数据处理到nms运行时间    dets = data_hstack[keep_dets]#最终的nms获得的矩形框    return detsif __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 = 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)

检测效果如下所示:

参考资料:

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模板匹配内容请搜索 以前的文章或继续浏览下面的相关文章希望大家以后多多支持 !

相关文章

发表新评论