matchTemplate (-215:断言失败) corr.rows <= img.rows + templ.rows - 1 && corr.cols <= img.cols + te



我在python中使用模板匹配进行对象检测。给定两个图像,一个源图像和一个模板图像,我打算找到匹配的模板图像在背景图像中的位置。

功能代码:

def __init__(self, piece_path, background_path):
self.piece_path = piece_path
self.background_path = background_path
def __img_to_grayscale(self, img):
tmp_path = "/tmp/sobel.png"
cv2.imwrite(tmp_path, img)
return cv2.imread(tmp_path, 0)
def get_position(self):
# some code for template and background processing
background = self.__img_to_grayscale(self.background_path)
template = self.__img_to_grayscale(self.piece_path)
res = cv2.matchTemplate(background, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
origin = x_inf
end = top_left[0] + PIXELS_EXTENSION

return end - origin

输入:bg.png为76kb12 kb 的template.png

确保每个地方使用的文件路径(绝对/相对(都遵循操作系统约定。

对于Linux:

def __img_to_grayscale(self, img):
tmp_path = "/tmp/sobel.png"
cv2.imwrite(tmp_path, img)
return cv2.imread(tmp_path, 0)

对于Windows:

def __img_to_grayscale(self, img):
tmp_path = "../sobel.png"
cv2.imwrite(tmp_path, img)
return cv2.imread(tmp_path, 0)

最新更新