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定位