Python OpenCV 輕松點,復習一下模板匹配吧

      網友投稿 841 2022-05-29

      Python OpenCV 365 天學習計劃,與橡皮擦一起進入圖像領域吧。本篇博客是這個系列的第 49 篇。

      學在前面

      關于 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 plt def 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_loc else: tl = max_loc br = (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 函數之后,并未返回多個結果,以下是參考數據,都是單個坐標。

      -20675626.0 56209900.0 (355, 415) (201, 259) 58169844.0 325979360.0 (346, 4) (201, 259) 38019264.0 216403984.0 (201, 259) (313, 3) 0.559607207775116 0.9503162503242493 (307, 1) (201, 259) -0.4676389992237091 0.7111679315567017 (356, 415) (201, 259) 0.1108362227678299 1.0 (201, 259) (282, 0)

      為了驗證出現的原因,我將矩形繪制的地方增加了顏色變動代碼。

      import cv2 as cv import numpy as np from matplotlib import pyplot as plt def 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 = 0 for 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_loc else: tl = max_loc br = (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()

      經過實驗確定繪制的圖像是上次繪制的殘留,因為出現了如下內容,兩次繪制的矩形邊框顏色不一致問題。

      知道原因了修改就比較容易了,只需要在循環的時候重新加載一下原圖即可。

      for md in methods: target = cv.imread("./t9.jpg") result = cv.matchTemplate(target, tpl, md)

      在實際應用的時候,盡量使用帶有歸一化的參數,但是對于每個圖像不同的參數都會導致不同的結果,需要給予實際情況進行判斷,沒有標準解。其它內容還可以去官網繼續學習 地址

      匹配到多個圖像區域

      在上述的案例中一直都是匹配到一個目標圖像區域,如果希望在一幅圖像中匹配到多個目標圖像,使用下述代碼即可。

      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") th, tw = tpl.shape[:2] result = cv.matchTemplate(target, tpl, cv.TM_CCOEFF_NORMED) threshold = 0.8 loc = 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 loc = np.where(result >= threshold) for pt in zip(*loc[::-1]): cv.rectangle(target, pt, (pt[0] + tw, pt[1] + th), (0, 0, 255), 1)

      其中 threshold=0.8 相當于臨界值的概念,用于篩選匹配到的結果大于 0.8 的坐標,相當于拿模板圖像與目標圖像去匹配,匹配度告訴 80%,表示匹配上了,否則沒有匹配上,所以降低這個值會導致匹配的結果變多,你可以自行嘗試一下。

      其中 np.where(condition) 函數表示輸出滿足 condition 的坐標,注意不是值,是坐標。

      接下來的操作其實是對圖像坐標的一些細節處理了,如果你對代碼不清楚,可以按照下述輸出進行比對

      threshold = 0.8 loc = np.where(result >= threshold) print(loc) print(loc[::-1]) print(list(zip(*loc[::-1]))) for pt in zip(*loc[::-1]): cv.rectangle(target, pt, (pt[0] + tw, pt[1] + th), 255, 1)

      輸出結果如下:

      (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.8 loc = 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 個小時你有所收獲,我們下篇博客見~

      相關閱讀

      技術專欄

      Python OpenCV 輕松點,復習一下模板匹配吧

      Python 爬蟲 100 例教程,超棒的爬蟲教程,立即訂閱吧

      Python 爬蟲小課,精彩 9 講

      今天是持續寫作的第

      92

      / 100 天。

      如果你想跟博主建立親密關系,可以關注同名公眾號

      夢想橡皮擦

      ,近距離接觸一個逗趣的互聯網高級網蟲。

      博主 ID:夢想橡皮擦,希望大家

      評論

      IDE OpenCV Python

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:深度學習入門,keras實現回歸模型
      下一篇:【網絡通訊與網絡安全】網絡通訊中的隨機數如果不隨機會怎么樣?(下)
      相關文章
      亚洲狠狠色丁香婷婷综合| 日本亚洲精品色婷婷在线影院| 亚洲精品无码成人片久久不卡| 亚洲视频免费观看| 久久亚洲日韩看片无码| 亚洲资源在线视频| 亚洲美女中文字幕| 亚洲激情视频网站| 亚洲一区免费视频| 亚洲中文字幕久久久一区| 亚洲国产视频久久| 亚洲欧美日韩自偷自拍| 亚洲经典千人经典日产| 久久精品国产亚洲AV未满十八| 亚洲av中文无码字幕色不卡| 亚洲av无码专区在线观看亚| 国产成人精品日本亚洲语音| www亚洲精品少妇裸乳一区二区| 亚洲成av人片不卡无码久久| 亚洲国产日韩成人综合天堂| 久久久久亚洲精品天堂久久久久久| 久久影视国产亚洲| 亚洲精品乱码久久久久66| 久久精品亚洲中文字幕无码网站| 久久精品国产亚洲av麻豆小说| 久久久久亚洲av无码专区喷水| 亚洲成A∨人片在线观看无码| 亚洲乱人伦精品图片| 天堂亚洲国产中文在线| 亚洲Av永久无码精品黑人| 一区二区三区亚洲视频| 久久综合亚洲色HEZYO国产| 久久久久久a亚洲欧洲aⅴ| 久久久无码精品亚洲日韩蜜臀浪潮 | 亚洲高清国产AV拍精品青青草原| 亚洲男人天堂av| 亚洲av无码不卡久久| 亚洲日韩一中文字暮| 亚洲精品高清在线| 亚洲成av人影院| 亚洲性一级理论片在线观看|