[英]How to reduce the search area of the image for template matching?
我正在使用openCV模板匹配算法,但是在基礎圖像中搜索模板圖像需要很長時間。 有什么方法可以告訴算法只搜索給定基本圖像的特定區域(如頂部、底部、左側、右側)以獲取模板圖像? 我的目標是減少搜索時間,任何其他方法將不勝感激。
這是我的代碼 -
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)
需要很長時間的原因是您正在給定圖像中搜索模板圖像的每個比例。
for scale in np.linspace(0.1, 0.5, 30)[::-1]:
resized = imutils.resize(gray, width=int(gray.shape[1] * scale))
您可以刪除減少搜索時間的for
循環。 權衡可能是缺少模板圖像。 例如:如果給定圖像中有 5 個模板圖像,您可能會找到其中的 2 個。
第二個選項是更改linspace
參數:
開始: 0.1
停止: 0.5
數量: 30
如果我們解釋當前的參數:
您可以縮短范圍,即從 0.4-0.5 np.linspace(0.4, 0.5, 30)
或者你可以減少生成的樣本大小,即 20, np.linspace(0.1, 0.5, 20)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.