import cv2 def template_match(img_master, img_slave, method='cv2.TM_CCOEFF_NORMED', mlx=1, mly=1, show=True): # Apply image oversampling img_master = cv2.cvtColor(img_master, cv2.COLOR_BGR2GRAY) img_slave = cv2.cvtColor(img_slave, cv2.COLOR_BGR2GRAY) 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 # import numpy as np # example = np.arange(2000).reshape((100, 20)) # a_kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) # def sliding_window(data, win_shape, **kwargs): # assert data.ndim == len(win_shape) # shape = tuple(dn - wn + 1 for dn, wn in zip(data.shape, win_shape)) + win_shape # strides = data.strides * 2 # return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides, **kwargs) # def arrays_from_kernel(a, a_kernel): # windows = sliding_window(a, a_kernel.shape) # return np.where(a_kernel, windows, 0) # sub_arrays = arrays_from_kernel(example, a_kernel)