模板匹配應(yīng)用的場(chǎng)景非常多峻贮,OCR(字符識(shí)別),目標(biāo)檢測(cè)澎粟、定位等等蛀序。OpenCV中,你可以使用cv2.matchTemplate()來(lái)完成活烙。對(duì)于其中的計(jì)算原理徐裸,可參考如下博客:
CV學(xué)習(xí)筆記(十一):模板匹配 http://www.reibang.com/p/79aa4cd67200
cv2.matchTemplate(img, templ, method)
tmepl:模板圖像
method:官方提供了三種方法cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF_NORMED,其中第三種方法值越小啸盏,表示匹配概率越大重贺,其余的為值越大匹配概率越大,這里列出的三種是會(huì)進(jìn)行歸一化回懦,這方便你設(shè)定閾值來(lái)進(jìn)行卡控气笙;
注意:該函數(shù)返回的是由匹配程度填充的灰度圖像
官方文檔:https://docs.opencv.org/3.0-beta/modules/imgproc/doc/object_detection.html?highlight=cv2.matchtemplate#void%20matchTemplate(InputArray%20image,%20InputArray%20templ,%20OutputArray%20result,%20int%20method)
import cv2
import numpy as np
# 剔除數(shù)據(jù)集中相鄰太近的點(diǎn),模板匹配設(shè)定的閾值會(huì)在目標(biāo)附近產(chǎn)生大量的重復(fù)結(jié)果
# 需要設(shè)計(jì)方法進(jìn)行剔除
def split_min_dist_dots(dot, dot_set, min_dist = 20):
if dot_set:
append_flag = True
for dt in dot_set:
dist = abs(dot[0] - dt[0]) + abs(dot[1] - dt[1])
if dist < min_dist:
append_flag = False
if append_flag:
dot_set.append(dot)
else:
dot_set.append(dot)
return dot_set
img = cv2.imread('steels.png', -1)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gaussian_img = cv2.GaussianBlur(gray_img,(3, 3),0)
template_img = cv2.imread('steel_temp.png', 0)
height, width = template_img.shape[:2]
res = cv2.matchTemplate(gaussian_img, template_img, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
threshold_template = 0.6
locs = np.where(res >= threshold_template)
# 最終的匹配結(jié)果
dots_set = []
# zip(*)操作怯晕,參考https://www.cnblogs.com/quietwalk/p/7997705.html
# locs[::-1]則是將序列順序顛倒潜圃,由于[row, col]對(duì)繪制矩形需要區(qū)分
for loc in (zip(*locs[::-1])):
dots_set = split_min_dist_dots(loc, dots_set)
for dot in dots_set:
cv2.rectangle(img, dot, (dot[0] + width, dot[1] + height), (255, 25, 25), 1)
cv2.putText(img, 'pipe', dot, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (25, 25, 255), 2)
cv2.putText(img, 'Pipe Count:%s'%len(dots_set), (0, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 25, 255), 2)
cv2.imshow('template_steel', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
這是一個(gè)關(guān)于模板匹配很簡(jiǎn)單的示例,如果你想利用這種方法應(yīng)用到你的項(xiàng)目舟茶,需要關(guān)注以下幾點(diǎn):
- 增加模板庫(kù)谭期,單單一張模板圖往往在應(yīng)用中捉襟見(jiàn)肘堵第;
- 模板匹配在目標(biāo)附近會(huì)產(chǎn)生大量高于設(shè)定閾值的結(jié)果,你需要設(shè)計(jì)更好的剔除鄰近干擾方案隧出;
- 對(duì)不同亮度踏志、角度進(jìn)行適配和測(cè)試
當(dāng)然,你完全也可以采用深度學(xué)習(xí)中的目標(biāo)檢測(cè)方案鸳劳,后面會(huì)涉及到狰贯,加個(gè)關(guān)注????
對(duì)于opencv-python的模板匹配部分有問(wèn)題歡迎留言也搓, Have Fun With OpenCV-Python, 下期見(jiàn)赏廓。