问题描述
我在 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 是 76 kb 并且 12 kb 的模板.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,0)