Python OpenCV 正月十五轻松点,复习一下模板匹配吧
Python OpenCV 365 天學習計劃,與橡皮擦一起進入圖像領域吧。本篇博客是這個系列的第 49 篇。
該系列文章導航參考:https://blog.csdn.net/hihell/category_10688961.html
Python OpenCV
- 學在前面
- 通過案例簡單復盤
- 匹配到多個圖像區域
- 橡皮擦的小節
學在前面
關于 OpenCV 中的模板匹配,在之前的博客 圖像的模板匹配,Python OpenCV 取經之旅第 29 天。
模板匹配就是在一個目標圖像(大圖)中檢索模板圖像(小圖),進行該操作的核心是兩個函數,一個是 cv2.matchTemplate 另一個是 cv2.minMaxLoc 。
模板匹配是將模板圖像在目標圖像上進行滑動,從左到右,從上到下,一個一個區域進行,類似卷積操作。
由上文提及的博客,我們也知道,如果模板圖像的大小是 w*h,目標圖像的大小是 W*H,那匹配到的圖像大小是 W-w+1,H-h+1,這步驟的操作是由 cv2.matchTemplate 實現的,接下來在由 cv2.minMaxLoc 函數查找最大值和最小值的像素點位置,拿到這個位置會后就可以在目標圖像上進行繪制了。
通過案例簡單復盤
編寫測試代碼如下,代碼中對于 method 參數進行了基本的羅列:
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()先展示的結果是沒有進行歸一化操作的,后展示的為歸一化操作的結果。
cv.TM_CCOEFF 運行結果
cv.TM_CCORR
cv.TM_SQDIFF
使用 cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED, cv.TM_SQDIFF_NORMED 等參數值的結果不在展示,問題出現在模板圖片的選擇上,因為左上角出現相同的像素點,所以導致有的結果出現 2 個匹配結果,最神奇的是,我對 result 進行輸出,發現使用 cv.minMaxLoc 函數之后,并未返回多個結果,以下是參考數據,都是單個坐標。
為了驗證出現的原因,我將矩形繪制的地方增加了顏色變動代碼。
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]# 每次繪制的時候,都展示不同的顏色代碼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()經過實驗確定繪制的圖像是上次繪制的殘留,因為出現了如下內容,兩次繪制的矩形邊框顏色不一致問題。
知道原因了修改就比較容易了,只需要在循環的時候重新加載一下原圖即可。
在實際應用的時候,盡量使用帶有歸一化的參數,但是對于每個圖像不同的參數都會導致不同的結果,需要給予實際情況進行判斷,沒有標準解。其它內容還可以去官網繼續學習 地址
匹配到多個圖像區域
在上述的案例中一直都是匹配到一個目標圖像區域,如果希望在一幅圖像中匹配到多個目標圖像,使用下述代碼即可。
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()
上述代碼函數使用的是原函數 cv.matchTemplate 沒有難度,重點在下面的代碼部分出現的差異:
其中 threshold=0.8 相當于臨界值的概念,用于篩選匹配到的結果大于 0.8 的坐標,相當于拿模板圖像與目標圖像去匹配,匹配度告訴 80%,表示匹配上了,否則沒有匹配上,所以降低這個值會導致匹配的結果變多,你可以自行嘗試一下。
其中 np.where(condition) 函數表示輸出滿足 condition 的坐標,注意不是值,是坐標。
接下來的操作其實是對圖像坐標的一些細節處理了,如果你對代碼不清楚,可以按照下述輸出進行比對
輸出結果如下:
(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 的坐標點,但是這些點都是橫縱坐標分開順序排列,并且是孤立的,而且圖像在繪制的時候,橫縱坐標順序是反著的,先高即縱,后寬即橫,搗鼓清楚了,其他的都是 Python 基本操作。
對坐標理解清楚之后,完全可以修改代碼如下,不需要這些變換,得到的結果是一致的。
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()橡皮擦的小節
希望今天的 1 個小時你有所收獲,我們下篇博客見~
相關閱讀
技術專欄
今天是持續寫作的第 92 / 100 天。
如果你想跟博主建立親密關系,可以關注同名公眾號 夢想橡皮擦,近距離接觸一個逗趣的互聯網高級網蟲。
博主 ID:夢想橡皮擦,希望大家點贊、評論、收藏。
總結
以上是生活随笔為你收集整理的Python OpenCV 正月十五轻松点,复习一下模板匹配吧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作业二:wireshark抓包与ping
- 下一篇: 使用python包scanpy读取单细胞