【问题标题】:matchTemplate (-215:Assertion failed) corr.rows <= img.rows + templ.rows - 1 && corr.cols <= img.cols + templ.cols - 1 in function 'cv::crossCorr'matchTemplate (-215:Assertion failed) corr.rows <= img.rows + templ.rows - 1 && corr.cols <= img.cols + templ.cols - 1 in function 'cv::crossCorr'
【发布时间】:2021-09-14 10:14:59
【问题描述】:

我在 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

【问题讨论】:

  • 您的背景和模板尺寸是多少?模板是否小于背景。如果没有,那么这可能是你的问题。你真的有这两个文件吗?可能没有正确阅读,所以空吗?在进行模板匹配之前检查背景和模板的凹凸数组的尺寸总是一个好主意。
  • 一般提示:错误的关键部分出现在之后 (Assertion failed).
  • @fmw42 感谢您的建议。我检查了尺寸。模板大小小于背景。由于两个文件都是输入的,所以它不是空的。给出绝对路径解决了问题!

标签: python-3.x numpy opencv opencv-python template-matching


【解决方案1】:

确保您在每个位置使用的文件路径(绝对/相对)遵循操作系统约定。

对于 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2020-09-17
    • 2020-10-13
    • 2021-04-14
    相关资源
    最近更新 更多