[英]How to reduce the search area of the image for template matching?
I'm using openCV template matching algorithm, but it takes a long time to search for a template image inside the base image.我正在使用openCV模板匹配算法,但是在基础图像中搜索模板图像需要很长时间。 Is there any way to tell the algorithm to search only a specific area(like- Top, Bottom, Left, Right) of the given base image for the template image?
有什么方法可以告诉算法只搜索给定基本图像的特定区域(如顶部、底部、左侧、右侧)以获取模板图像? My goal is to reduce the search time any other approach would be appreciated.
我的目标是减少搜索时间,任何其他方法将不胜感激。
Here is my code -这是我的代码 -
template = cv2.imread(temp_img)
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
sigma=0.33
v = np.median(template)
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
template = cv2.Canny(template, lower, upper)
(tH, tW) = template.shape[:2]
baseImage = cv2.imread(base_img)
gray = cv2.cvtColor(baseImage, cv2.COLOR_BGR2GRAY)
found = None
threshold = 0.8
for scale in np.linspace(0.1, 0.5, 30)[::-1]:
resized = imutils.resize(gray, width=int(gray.shape[1] * scale))
r = gray.shape[1] / float(resized.shape[1])
if resized.shape[0] < tH or resized.shape[1] < tW:
break
v = np.median(resized)
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
canny = cv2.Canny(resized, lower, upper)
res = cv2.matchTemplate(canny, template, cv2.TM_CCOEFF_NORMED)
(min_val, max_val, _, max_loc) = cv2.minMaxLoc(res)
if found is None or max_val > found[0]:
found = (max_val, max_loc, r)
(max_val, max_loc, r) = found
if max_val > threshold:
(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))
cv2.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)
The reason it takes a long time is that you are searching for each scale of the template image in the given image.需要很长时间的原因是您正在给定图像中搜索模板图像的每个比例。
for scale in np.linspace(0.1, 0.5, 30)[::-1]:
resized = imutils.resize(gray, width=int(gray.shape[1] * scale))
You can remove the for
loop which reduce the search time.您可以删除减少搜索时间的
for
循环。 The trade-off might be the missing template images.权衡可能是缺少模板图像。 For instance: if you have 5 template image in the given image, you might find 2 of them.
例如:如果给定图像中有 5 个模板图像,您可能会找到其中的 2 个。
The second option is changing the linspace
parameters:第二个选项是更改
linspace
参数:
start: 0.1开始: 0.1
stop: 0.5停止: 0.5
num: 30数量: 30
If we interpret the current params:如果我们解释当前的参数:
From the range of 0.1
to 0.5
ratios:从
0.1
到0.5
比率范围:
Possible Solutions:可能的解决方案:
You can do shorten range, ie from 0.4-0.5 np.linspace(0.4, 0.5, 30)
您可以缩短范围,即从 0.4-0.5
np.linspace(0.4, 0.5, 30)
Or you can reduce the generated sample size, ie 20, np.linspace(0.1, 0.5, 20)
或者你可以减少生成的样本大小,即 20,
np.linspace(0.1, 0.5, 20)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.