Python文档阅读笔记-OpenCV中Template Matching
生活随笔
收集整理的这篇文章主要介绍了
Python文档阅读笔记-OpenCV中Template Matching
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
目标
通过模板匹配在一张图中找相似图。
原理
模板匹配这个方法是在一个大图中找小图的功能,OpenCV中使用cv.matchTemplate()这个函数实现。在OpenCV中可以填写几种参数。这个函数的返回值是灰度图,其中,每个像素表示该像素的邻域与模板匹配的程度。
如果输入图像的大小为W * H模板图像的大小为w * h,则输出图像的大小为(W - w + 1) * (H - h + 1)。得到结果后,可以使用cv.minMaxLoc()函数去找里面的最大值和最小值,将其作为矩形的左上角,并将(w, h)作为矩形的宽度和高度。该矩形是模板的区域。
注意:如果使用的cv.TM_SQDIFF为表示方法,最小值给出的将是最佳匹配。
OpenCV中的模板匹配
在图片中找Messi的脸,模板图片如下:
使用不同的表达方式查看结果,代码如下:
import cv2 as cv import numpy as np from matplotlib import pyplot as plt img = cv.imread('messi5.jpg',0) img2 = img.copy() template = cv.imread('template.jpg',0) w, h = template.shape[::-1] # All the 6 methods for comparison in a list 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:img = img2.copy()method = eval(meth)# Apply template Matchingres = cv.matchTemplate(img,template,method)min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimumif method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:top_left = min_locelse:top_left = max_locbottom_right = (top_left[0] + w, top_left[1] + h)cv.rectangle(img,top_left, bottom_right, 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.suptitle(meth)plt.show()结果如下:
cv.TM_CCOEFF
cv.TM_CCOEFF_NORMED
cv.TM_CCORR
cv.TM_CCORR_NORMED
cv.TM_SQDIFF
cv.TM_SQDIFF_NORMED
上图中可得知TM_CCORR未在大图中找到模板图。
模板匹配多个对象
如果大图中有含义多个模板图,cv.minMaxLoc()不能找出所有,那么设置一个阈值,去寻找,代码如下:
import cv2 as cv import numpy as np from matplotlib import pyplot as plt img_rgb = cv.imread('mario.png') img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY) template = cv.imread('mario_coin.png',0) w, h = template.shape[::-1] res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where( res >= threshold) for pt in zip(*loc[::-1]):cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) cv.imwrite('res.png',img_rgb截图:
总结
以上是生活随笔为你收集整理的Python文档阅读笔记-OpenCV中Template Matching的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Web前端笔记-element ui中t
- 下一篇: Python笔记-XPath定位