pythonopencv模板匹配多⽬标_opencvpython模板匹配
理论
模板匹配是⼀种在较⼤的图像中搜索和查模板图像位置的⽅法。OpenCV带有⼀个函数cv2.matchTemplate()⽤于此⽬的.它只是简单地将模板图像放在输⼊图像上(就像在2D卷积中那样),并在模板图像下对输⼊图像的模板和补丁进⾏⽐较,在OpenCV中实现了⼏种⽐较⽅法,它返回⼀个灰度图像,每个像素表⽰该像素区域与模板的匹配程度.
rectangle函数opencv如果输⼊图像的⼤⼩(W x H)且模板图像的⼤⼩(w x h),则输出图像的⼤⼩为(W-w + 1,H-h + 1).获得结果后,可以使⽤
cv.minMaxLoc()函数查最⼤/最⼩值的位置。将其作为矩形的左上⾓,并将(w,h)作为矩形的宽度和⾼度.
OpenCV中的模板匹配
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('img.jpg',0)
img2 = py()
template = cv2.imread('img_roi.png',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = py()
method = eval(meth)
# Apply template Matching
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), icks([]), icks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), icks([]), icks([])
plt.suptitle(meth)
plt.show()
与多个对象匹配的模板
cv.minMaxLoc()将不会提供所有的位置.在这种情况下,我们将使⽤阈值.
import cv2
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv2.imread('img5.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('img_roi1.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.imshow('res',img_rgb)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论