前言
在本節(jié)我們要學(xué)習(xí):
-
使用模板匹配在一幅圖像中查找目標(biāo)
-
函數(shù):cv2.matchTemplate(),cv2.minMaxLoc()
一、原理
模板匹配是用來在一副大圖中搜尋查找模版圖像位置的方法。OpenCV 為我們提供了函數(shù):cv2.matchTemplate()。和 2D 卷積一樣,它也是用模板圖像在輸入圖像(大圖)上滑動(dòng),并在每一個(gè)位置對(duì)模板圖像和與其對(duì)應(yīng)的輸入圖像的子區(qū)域進(jìn)行比較。OpenCV 提供了幾種不同的比較方法(細(xì)節(jié)請(qǐng)看文檔)。返回的結(jié)果是一個(gè)灰度圖像,每一個(gè)像素值表示了此區(qū)域與模板的匹配程度。
如果輸入圖像的大小是(WxH),模板的大小是(wxh),輸出的結(jié)果的大小就是(W-w+1,H-h+1)。當(dāng)你得到這幅圖之后,就可以使用函數(shù)cv2.minMaxLoc() 來找到其中的最小值和最大值的位置了。第一個(gè)值為矩形左上角的點(diǎn)(位置),(w,h)為 模板矩形的寬和高。這個(gè)矩形就是找到的模板區(qū)域了。
二、OpenCV 中的模板匹配
我們這里有一個(gè)例子:我們?cè)诿肺鞯恼掌兴阉髅肺鞯拿娌?。所以我們要制作下面這樣一個(gè)模板:
我們會(huì)嘗試使用不同的比較方法,這樣我們就可以比較一下它們的效果了。
# -*- coding: utf-8 -*-
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('ball.png', 0)
img2 = img.copy()
template = cv2.imread('ball_face.png', 0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
# exec 語句用來執(zhí)行儲(chǔ)存在字符串或文件中的 Python 語句。
# 例如,我們可以在運(yùn)行時(shí)生成一個(gè)包含 Python 代碼的字符串,然后使用 exec 語句執(zhí)行這些語句。
# eval 語句用來計(jì)算存儲(chǔ)在字符串中的有效 Python 表達(dá)式
method = eval(meth)
# Apply template Matching
res = cv2.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 使用不同的比較方法,對(duì)結(jié)果的解釋不同
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.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.tight_layout()
plt.show()
我們看到 cv2.TM_CCORR 和 cv2.TM_SQDIFF 的效果不想我們想的那么好。
三、多對(duì)象的模板匹配
在前面的部分,我們?cè)趫D片中搜素梅西的臉,而且梅西只在圖片中出現(xiàn)了一次。假如你的目標(biāo)對(duì)象只在圖像中出現(xiàn)了很多次怎么辦呢?函數(shù)cv.imMaxLoc() 只會(huì)給出最大值和最小值。此時(shí),我們就要使用閾值了。在下面的例子中我們要經(jīng)典游戲 Mario 的一張截屏圖片中找到其中的硬幣。文章來源:http://www.zghlxwxcb.cn/news/detail-785107.html
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv2.imread('mario.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
#umpy.where(condition[, x, y])
#Return elements, either from x or y, depending on condition.
#If only condition is given, return condition.nonzero().
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite('res.png',img_rgb)
結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-785107.html
到了這里,關(guān)于OpenCV官方教程中文版 —— 模板匹配的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!