def template_match(img_master, img_slave, method = 'cv2.TM_CCOEFF_NORMED', mlx = 1, mly = 1, show=True):
# Apply image oversampling
img_master = cv2.resize(img_master,None,fx=mlx, fy=mly, interpolation = cv2.INTER_CUBIC)
img_slave = cv2.resize(img_slave,None,fx=mlx, fy=mly, interpolation = cv2.INTER_CUBIC)
res = cv2.matchTemplate(img_slave,img_master,eval(method))
w, h = img_master.shape[::-1]
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# Control if the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum value
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)
# Retrieve center coordinates
px = (top_left[0]+bottom_right[0])/(2.0*mlx)
py = (top_left[1]+bottom_right[1])/(2.0*mly)
# Scale images for visualization
img_master_scaled = cv2.convertScaleAbs(img_master, alpha=(255.0/500))
img_slave_scaled = cv2.convertScaleAbs(img_slave, alpha=(255.0/500))
cv2.rectangle(img_slave_scaled,top_left, bottom_right, 255, 2*mlx)
if show == True:
plt.figure(figsize=(20,10))
plt.subplot(131),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(img_master_scaled,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.subplot(133),plt.imshow(img_slave_scaled, cmap = 'gray')
plt.suptitle(method)
plt.show()
return px, py, max_val
评论列表
文章目录