Search code examples
pythonopencvmatchtemplate

matchTemplate with resized image does not work:(-215:Assertion failed) _img.size().height <= _templ.size().height


I resize my image before the matchTemplate call to make sure that both images have the same size.

# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
import time

img_rgb = cv.imread('t2.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('template1.png', 0)

# Make sure that we use the exact same size in the comparison
if img_gray.shape != template.shape:
    img_gray = cv.resize(img_gray, template.shape, interpolation=cv.INTER_AREA)


res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
print res

But I got this error:

res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1112: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'cv::matchTemplate'

Solution

  • when ypu resize your image you are using template.shape but you need to use

    template.shape[::-1]