-1

I'm using template matching for object detection in python. Given two images, one source image and one template image, i intend to find the position of the template image matching in the background image.

Function code:

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

Inputs: bg.png is of 76 kb and template.png of 12 kb

Community
  • 1
  • 1
  • 1
    What are your background and template dimensions? Is the template smaller than the background. If not, then that might be your issue. Do you actually have both files? Might one not be read properly, so empty? Always a good idea to check the dimensions of the bumpy arrays for the background and template before doing the template matching. – fmw42 Jul 02 '21 at 16:17
  • general tip: the crucial part of the error comes *after* `(Assertion failed)`. – Christoph Rackwitz Jul 03 '21 at 03:19
  • @fmw42 Thanks for suggestion.. I've checked the dimensions. Template size is smaller than background.Since, both files are input, it is not empty. Giving the absolute path solved the problem ! – Seema Shaikh Jul 06 '21 at 12:22

1 Answers1

1

Make sure your file path (absolute / relative) used at each place follows the OS convention.

For Linux:

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

For Windows:

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