[英]Simple template matching with python-openCv
我正在嘗試檢測圖像中一些簡單的“紅色圖案”。 這是我遵循的算法:1)濾除所有其他顏色,而不是“紅色”,並創建黑色和白色圖像。 我使用了帶有適當遮罩的“ cvtColor”,然后應用了“ GaussianBlur”以減少噪聲。 到目前為止,一切都很好。
2)我使用如下的功能“ matchTemplate”來檢測圖像中的“箭頭”模板。
問題 :照片中有“箭頭”模板時,可以正確檢測到它。 但是當它不在照片中時,算法會檢測到其他形狀,這是錯誤的。 有人可以修改代碼,以便當箭頭模板不在圖片中時什么也沒檢測到。 這是我的代碼:
template = cv2.imread(address,0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(self.image['blured'], template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(self.image['blured'],top_left, bottom_right, 255, 2)
cv2.rectangle(self.image['normal'], top_left, bottom_right, 255,2)
我的模板圖片是我從主照片中精確裁剪出來的:
有人可以發現我的錯誤嗎? 我是圖像處理的新手。 提前致謝。
您必須查看您的max_val
並為其設置一個閾值。
假設max_val
在圖像中包含箭頭時為x1
,在圖像中不包含箭頭時為x2
,應該為x1 > x2
。 作為第一個暫定值,您可以選擇threshold=(x1+x2)/2
,然后如果max_val > threshold
則在圖像中找到圖案,否則找不到圖案。
滑過
image
,使用指定的方法將大小w
\\ timesh
的重疊塊與templ
比較,並將比較結果存儲在result
。
因此, res
圖像中是否存在箭頭,您的圖像res
將始終具有最大值。
非常感謝Alessandro Jacopson。 我修改了代碼並以這種方式解決了問題。 幾乎是您提出的建議:
template = cv2.imread(address,0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(self.image['blured'], template,cv2.TM_CCOEFF_NORMED)
threshold = 0.9
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(self.image['blured'], pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.rectangle(self.image['normal'], pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
通過這種方式,可以非常准確地檢測出圖案。 新問題:對方向和旋轉敏感。 旋轉時不會檢測到圖案,例如大約45度。 盡管可以旋轉或縮放比例,但是我可以設置任何參數,並使算法找到模式嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.