Python OpenCV 正月十五轻松点,复习一下模板匹配吧
Python OpenCV 365 天學(xué)習(xí)計(jì)劃,與橡皮擦一起進(jìn)入圖像領(lǐng)域吧。本篇博客是這個(gè)系列的第 49 篇。
該系列文章導(dǎo)航參考:https://blog.csdn.net/hihell/category_10688961.html
Python OpenCV
- 學(xué)在前面
- 通過(guò)案例簡(jiǎn)單復(fù)盤
- 匹配到多個(gè)圖像區(qū)域
- 橡皮擦的小節(jié)
學(xué)在前面
關(guān)于 OpenCV 中的模板匹配,在之前的博客 圖像的模板匹配,Python OpenCV 取經(jīng)之旅第 29 天。
模板匹配就是在一個(gè)目標(biāo)圖像(大圖)中檢索模板圖像(小圖),進(jìn)行該操作的核心是兩個(gè)函數(shù),一個(gè)是 cv2.matchTemplate 另一個(gè)是 cv2.minMaxLoc 。
模板匹配是將模板圖像在目標(biāo)圖像上進(jìn)行滑動(dòng),從左到右,從上到下,一個(gè)一個(gè)區(qū)域進(jìn)行,類似卷積操作。
由上文提及的博客,我們也知道,如果模板圖像的大小是 w*h,目標(biāo)圖像的大小是 W*H,那匹配到的圖像大小是 W-w+1,H-h+1,這步驟的操作是由 cv2.matchTemplate 實(shí)現(xiàn)的,接下來(lái)在由 cv2.minMaxLoc 函數(shù)查找最大值和最小值的像素點(diǎn)位置,拿到這個(gè)位置會(huì)后就可以在目標(biāo)圖像上進(jìn)行繪制了。
通過(guò)案例簡(jiǎn)單復(fù)盤
編寫測(cè)試代碼如下,代碼中對(duì)于 method 參數(shù)進(jìn)行了基本的羅列:
import cv2 as cv import numpy as np from matplotlib import pyplot as pltdef template_demo():tpl = cv.imread("./tpl.jpg")target = cv.imread("./t9.jpg")methods = [cv.TM_CCOEFF, cv.TM_CCORR, cv.TM_SQDIFF,cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED, cv.TM_SQDIFF_NORMED]th, tw = tpl.shape[:2]for md in methods:result = cv.matchTemplate(target, tpl, md)min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)# 如果方法是 TM_SQDIFF 或 TM_SQDIFF_NORMED,則取最小值if md == cv.TM_SQDIFF_NORMED or md == cv.TM_SQDIFF:tl = min_locelse:tl = max_locbr = (tl[0] + tw, tl[1] + th)cv.rectangle(target, tl, br, (0, 0, 255), 2)# cv.imshow("match-" + np.str(md), target)plt.subplot(121), plt.imshow(result, cmap='gray')plt.title('result'), plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(cv.cvtColor(target, cv.COLOR_BGR2RGB), cmap='gray')plt.title('target'), plt.xticks([]), plt.yticks([])plt.show()if __name__ == "__main__":template_demo()cv.waitKey(0)cv.destroyAllWindows()先展示的結(jié)果是沒(méi)有進(jìn)行歸一化操作的,后展示的為歸一化操作的結(jié)果。
cv.TM_CCOEFF 運(yùn)行結(jié)果
cv.TM_CCORR
cv.TM_SQDIFF
使用 cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED, cv.TM_SQDIFF_NORMED 等參數(shù)值的結(jié)果不在展示,問(wèn)題出現(xiàn)在模板圖片的選擇上,因?yàn)樽笊辖浅霈F(xiàn)相同的像素點(diǎn),所以導(dǎo)致有的結(jié)果出現(xiàn) 2 個(gè)匹配結(jié)果,最神奇的是,我對(duì) result 進(jìn)行輸出,發(fā)現(xiàn)使用 cv.minMaxLoc 函數(shù)之后,并未返回多個(gè)結(jié)果,以下是參考數(shù)據(jù),都是單個(gè)坐標(biāo)。
為了驗(yàn)證出現(xiàn)的原因,我將矩形繪制的地方增加了顏色變動(dòng)代碼。
import cv2 as cv import numpy as np from matplotlib import pyplot as pltdef template_demo():tpl = cv.imread("./tpl.jpg")target = cv.imread("./t9.jpg")tpl = cv.cvtColor(tpl,cv.COLOR_BGR2RGB)target = cv.cvtColor(target,cv.COLOR_BGR2RGB)# methods = [cv.TM_CCOEFF, cv.TM_CCORR, cv.TM_SQDIFF,# cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED, cv.TM_SQDIFF_NORMED]# 每次繪制的時(shí)候,都展示不同的顏色代碼colors = [(0, 0, 255),(255, 0, 255),(0, 255, 255),(0, 0, 0),(255, 0, 0),(0,255, 0)]methods = [cv.TM_CCOEFF, cv.TM_CCORR, cv.TM_SQDIFF,cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED, cv.TM_SQDIFF_NORMED]th, tw = tpl.shape[:2]color_num = 0for md in methods:result = cv.matchTemplate(target, tpl, md)# print(result.shape)# cv.normalize(result, result, 0, 1, cv.NORM_MINMAX, -1)min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)print(min_val, max_val, min_loc, max_loc)# 如果方法是 TM_SQDIFF 或 TM_SQDIFF_NORMED,則取最小值if md == cv.TM_SQDIFF_NORMED or md == cv.TM_SQDIFF:tl = min_locelse:tl = max_locbr = (tl[0] + tw, tl[1] + th)print(colors[color_num])cv.rectangle(target, tl, br, colors[color_num], 5)color_num+=1# cv.imshow("match-" + np.str(md), target)plt.cla()plt.subplot(121), plt.imshow(result, cmap='gray')plt.title('result'), plt.xticks([]), plt.yticks([])plt.subplot(122), plt.imshow(target, cmap='gray')plt.title('target'), plt.xticks([]), plt.yticks([])plt.show()if __name__ == "__main__":template_demo()cv.waitKey(0)cv.destroyAllWindows()經(jīng)過(guò)實(shí)驗(yàn)確定繪制的圖像是上次繪制的殘留,因?yàn)槌霈F(xiàn)了如下內(nèi)容,兩次繪制的矩形邊框顏色不一致問(wèn)題。
知道原因了修改就比較容易了,只需要在循環(huán)的時(shí)候重新加載一下原圖即可。
在實(shí)際應(yīng)用的時(shí)候,盡量使用帶有歸一化的參數(shù),但是對(duì)于每個(gè)圖像不同的參數(shù)都會(huì)導(dǎo)致不同的結(jié)果,需要給予實(shí)際情況進(jìn)行判斷,沒(méi)有標(biāo)準(zhǔn)解。其它內(nèi)容還可以去官網(wǎng)繼續(xù)學(xué)習(xí) 地址
匹配到多個(gè)圖像區(qū)域
在上述的案例中一直都是匹配到一個(gè)目標(biāo)圖像區(qū)域,如果希望在一幅圖像中匹配到多個(gè)目標(biāo)圖像,使用下述代碼即可。
import cv2 as cv import numpy as np import matplotlib.pyplot as pltdef main():tpl = cv.imread("./big_tpl.jpg")target = cv.imread("./big.jpg")th, tw = tpl.shape[:2]result = cv.matchTemplate(target, tpl, cv.TM_CCOEFF_NORMED)threshold = 0.8loc = np.where(result >= threshold)for pt in zip(*loc[::-1]):cv.rectangle(target, pt, (pt[0] + tw,pt[1] + th), (0, 0, 255), 1)cv.imshow("img", target)cv.waitKey()cv.destroyAllWindows()if __name__ == '__main__':main()
上述代碼函數(shù)使用的是原函數(shù) cv.matchTemplate 沒(méi)有難度,重點(diǎn)在下面的代碼部分出現(xiàn)的差異:
其中 threshold=0.8 相當(dāng)于臨界值的概念,用于篩選匹配到的結(jié)果大于 0.8 的坐標(biāo),相當(dāng)于拿模板圖像與目標(biāo)圖像去匹配,匹配度告訴 80%,表示匹配上了,否則沒(méi)有匹配上,所以降低這個(gè)值會(huì)導(dǎo)致匹配的結(jié)果變多,你可以自行嘗試一下。
其中 np.where(condition) 函數(shù)表示輸出滿足 condition 的坐標(biāo),注意不是值,是坐標(biāo)。
接下來(lái)的操作其實(shí)是對(duì)圖像坐標(biāo)的一些細(xì)節(jié)處理了,如果你對(duì)代碼不清楚,可以按照下述輸出進(jìn)行比對(duì)
輸出結(jié)果如下:
(array([146, 146, 147, 147, 147, 147, 147, 147, 148, 148, 148, 148, 148,148, 148, 148, 148, 148, 149, 149, 149, 149, 149, 149, 149, 149,149, 149, 150, 150, 150, 150], dtype=int64), array([692, 979, 118, 405, 691, 692, 978, 979, 117, 118, 404, 405, 691,692, 693, 978, 979, 980, 117, 118, 119, 404, 405, 406, 692, 693,979, 980, 118, 119, 405, 406], dtype=int64)) (array([692, 979, 118, 405, 691, 692, 978, 979, 117, 118, 404, 405, 691,692, 693, 978, 979, 980, 117, 118, 119, 404, 405, 406, 692, 693,979, 980, 118, 119, 405, 406], dtype=int64), array([146, 146, 147, 147, 147, 147, 147, 147, 148, 148, 148, 148, 148,148, 148, 148, 148, 148, 149, 149, 149, 149, 149, 149, 149, 149,149, 149, 150, 150, 150, 150], dtype=int64)) [(692, 146), (979, 146), (118, 147), (405, 147), (691, 147), (692, 147), (978, 147), (979, 147), (117, 148), (118, 148), (404, 148), (405, 148), (691, 148), (692, 148), (693, 148), (978, 148), (979, 148), (980, 148), (117, 149), (118, 149), (119, 149), (404, 149), (405, 149), (406, 149), (692, 149), (693, 149), (979, 149), (980, 149), (118, 150), (119, 150), (405, 150), (406, 150)]使用 loc = np.where(result >= threshold) 之后,得到了所有大于 0.8 的坐標(biāo)點(diǎn),但是這些點(diǎn)都是橫縱坐標(biāo)分開(kāi)順序排列,并且是孤立的,而且圖像在繪制的時(shí)候,橫縱坐標(biāo)順序是反著的,先高即縱,后寬即橫,搗鼓清楚了,其他的都是 Python 基本操作。
對(duì)坐標(biāo)理解清楚之后,完全可以修改代碼如下,不需要這些變換,得到的結(jié)果是一致的。
for pt in zip(*loc):cv.rectangle(target, (pt[1],pt[0]), (pt[1] + th,pt[0] + tw), 255, 1)為了提高效率,可以匹配灰度圖,然后在彩色圖像繪制即可。
import cv2 as cv import numpy as np import matplotlib.pyplot as plt def main():tpl = cv.imread("./big_tpl.jpg")target = cv.imread("./big.jpg")tpl_gray = cv.cvtColor(tpl, cv.COLOR_BGR2GRAY)target_gray = cv.cvtColor(target, cv.COLOR_BGR2GRAY)th, tw = tpl_gray.shape[:]result = cv.matchTemplate(target_gray, tpl_gray, cv.TM_CCOEFF_NORMED)print(result)threshold = 0.8loc = np.where(result >= threshold)for pt in zip(*loc[::-1]):cv.rectangle(target, pt, (pt[0] + tw,pt[1] + th), 255, 1)cv.imshow("target", target)cv.waitKey()cv.destroyAllWindows()if __name__ == '__main__':main()橡皮擦的小節(jié)
希望今天的 1 個(gè)小時(shí)你有所收獲,我們下篇博客見(jiàn)~
相關(guān)閱讀
技術(shù)專欄
今天是持續(xù)寫作的第 92 / 100 天。
如果你想跟博主建立親密關(guān)系,可以關(guān)注同名公眾號(hào) 夢(mèng)想橡皮擦,近距離接觸一個(gè)逗趣的互聯(lián)網(wǎng)高級(jí)網(wǎng)蟲(chóng)。
博主 ID:夢(mèng)想橡皮擦,希望大家點(diǎn)贊、評(píng)論、收藏。
總結(jié)
以上是生活随笔為你收集整理的Python OpenCV 正月十五轻松点,复习一下模板匹配吧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 作业二:wireshark抓包与ping
- 下一篇: 双指针扫描