Error in template matching

617 views Asked by At

I am trying to make a iris scanner using Python and open CV. While using the template matching function I get the following error:

import cv2
import numpy as np

img1 = cv2.imread('canny.jpg');
img2 = cv2.imread('frame1.jpg');
edges=cv2.Canny(img2,100,100)
w,h=edges.shape[::-1]

res = cv2.matchTemplate(img1 , edges, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
print loc

Following is the error:

Traceback (most recent call last):
  File "E:/OpenCV Programs/threshold2img1.py", line 9, in <module>
    res = cv2.matchTemplate(img1 , edges, cv2.TM_CCOEFF_NORMED)
error: OpenCV(3.4.1) C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\templmatch.cpp:1102: error: (-215) (depth == 0 || depth == 5) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate
1

There are 1 answers

0
Piglet On

imread reads image files as BGR colour images by default. So img1 is BGR colour image while edge is grayscale.

You cannot do template matching between a BRG colour image and a grayscale template. Mathematically that doesn't make sense.

Think of the colour pixels as points in 3d space. Now how similar is scalar 5 to the point (3,4,1)?

The OpenCV manual is actually pretty clear about that. They even give the formulas used to calculate the results...

https://docs.opencv.org/2.4/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#matchtemplate

In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image.