While using the matchTemplate function in OpenCV, I get the error that the template image is larger than the original image. How to overcome that?

The code is as follows:

def imagecheck(name1):
  os.chdir('/content/drive/My Drive/Mad Street Den/Images')
  main_image = cv2.imread('image_name_100.jpg')
  gray_image = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY)

  #open the template as gray scale image
  os.chdir('/content/drive/My Drive/Mad Street Den/Crops')
  template = cv2.imread(name1, 0)
  width, height = template.shape[::-1] #get the width and height

  #match the template using cv2.matchTemplate
  match = cv2.matchTemplate(gray_image, template, cv2.TM_CCOEFF_NORMED)
  threshold = 0.9
  position = np.where(match >= threshold) #get the location of template in the image

  for point in zip(*position[::-1]): #draw the rectangle around the matched template
     cv2.rectangle(main_image, point, (point[0] + width, point[1] + height), (0, 204, 153), 2)

  if (all (position)):
  return (result)
for i in range(0,273):
  print(name1, ' : ',result)

The Error is

error: OpenCV(3.4.3) /io/opencv/modules/imgproc/src/templmatch.cpp:1107: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'matchTemplate' site:stackoverflow.com

1 Answers

Dave W. Smith On

You can avoid the issue by not attempting to match a template against an image if the template is larger. Compare the template dimensions to the image dimensions and, in this case, return [] if they template is larger in any dimension.