除了使用之外
cv2.HoughLines(),另一种方法是使用模板匹配。这个想法是在更大的图像中搜索并找到模板图像的位置。为了执行此方法,模板在输入图像上滑动(类似于2D卷积),在此执行比较方法以确定像素相似度。这是模板匹配的基本思想。不幸的是,这种基本方法有缺陷,因为它
仅在模板图像大小 与输入图像中 所需的项目相同时才起作用 。因此,如果模板图像小于在输入图像中找到的所需区域,则此方法将不起作用。
为了解决这个限制,我们可以使用来动态重新缩放图像,以实现更好的模板匹配
np.linspace()。每次迭代时,我们都会调整输入图像的大小并跟踪比率。我们继续调整大小,直到模板图像的大小大于调整大小的图像,同时跟踪最高的相关值。相关值越高,匹配越好。一旦我们遍历各种比例,我们就会找到匹配度最大的比率,然后计算边界框的坐标来确定ROI。
使用此屏幕截图模板图像
这是结果
import cv2import numpy as np# Resizes a image and maintains aspect ratiodef maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA): # Grab the image size and initialize dimensions dim = None (h, w) = image.shape[:2] # Return original image if no need to resize if width is None and height is None: return image # We are resizing height if width is none if width is None: # Calculate the ratio of the height and construct the dimensions r = height / float(h) dim = (int(w * r), height) # We are resizing width if height is none else: # Calculate the ratio of the 0idth and construct the dimensions r = width / float(w) dim = (width, int(h * r)) # Return the resized image return cv2.resize(image, dim, interpolation=inter)# Load template, convert to grayscale, perform canny edge detectiontemplate = cv2.imread('template.png')template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)template = cv2.Canny(template, 50, 200)(tH, tW) = template.shape[:2]cv2.imshow("template", template)# Load original image, convert to grayscaleoriginal_image = cv2.imread('1.png')gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)found = None# Dynamically rescale image for better template matchingfor scale in np.linspace(0.1, 3.0, 20)[::-1]: # Resize image to scale and keep track of ratio resized = maintain_aspect_ratio_resize(gray, width=int(gray.shape[1] * scale)) r = gray.shape[1] / float(resized.shape[1]) # Stop if template image size is larger than resized image if resized.shape[0] < tH or resized.shape[1] < tW: break # Detect edges in resized image and apply template matching canny = cv2.Canny(resized, 50, 200) detected = cv2.matchTemplate(canny, template, cv2.TM_CCOEFF) (_, max_val, _, max_loc) = cv2.minMaxLoc(detected) # Uncomment this section for visualization ''' clone = np.dstack([canny, canny, canny]) cv2.rectangle(clone, (max_loc[0], max_loc[1]), (max_loc[0] + tW, max_loc[1] + tH), (0,255,0), 2) cv2.imshow('visualize', clone) cv2.waitKey(0) ''' # Keep track of correlation value # Higher correlation means better match if found is None or max_val > found[0]: found = (max_val, max_loc, r)# Compute coordinates of bounding box(_, max_loc, r) = found(start_x, start_y) = (int(max_loc[0] * r), int(max_loc[1] * r))(end_x, end_y) = (int((max_loc[0] + tW) * r), int((max_loc[1] + tH) * r))# Draw bounding box on ROIcv2.rectangle(original_image, (start_x, start_y), (end_x, end_y), (0,255,0), 2)cv2.imshow('detected', original_image)cv2.imwrite('detected.png', original_image)cv2.waitKey(0)


