Ask Your Question

Error at template matching in Python

asked 2016-10-27 14:04:15 -0500

Nandika gravatar image

updated 2016-10-28 09:20:31 -0500

I'm trying to template matching using my web cam.I used web cam feed as source and used a template as small image that taken from web cam. Both template and source have same bit depth.(uint8). same data type of source(left) and template(right)

I'm using OpenCV3.0 with python 2.7 in VS 2013 IDE I got this error:

C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\imgproc\src\templmatch.cpp:1062: error: (-215) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate


import cv2
import numpy as np

template = cv2.imread("C:/Users/Nandika/Desktop/ttt.jpg",0)
w, h = template.shape[::-1]


    while 1:
        res = cv2.matchTemplate(img,template,method)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)

        cv2.rectangle(img,top_left, bottom_right, 255, 2)


        if cv2.waitKey(1) & 0xFF == ord('q'):

Give me a solution

Thank in advance

edit retag flag offensive close merge delete


squint hard at your imag member there.

berak gravatar imageberak ( 2016-10-27 22:23:52 -0500 )edit

please show your code !

current assumption is: your template is grayscale, your query image is bgr.

berak gravatar imageberak ( 2016-10-28 09:03:04 -0500 )edit

code is added This question also in Stackoverflow

Nandika gravatar imageNandika ( 2016-10-28 09:22:14 -0500 )edit

1 answer

Sort by » oldest newest most voted

answered 2016-10-28 09:29:27 -0500

berak gravatar image

please convert your img from the webcam to grayscale, so both have the same type:

while 1:
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # !!
    res = cv2.matchTemplate(gray, template,method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
edit flag offensive delete link more


I converted both source and template to gray before.But, got same Error.. Now Its working...But, My template is not a gray.

So,This template and source is not same.

OpenCV docs said,

''image – Image where the search is running. It must be 8-bit or 32-bit floating-point.

templ – Searched template. It must be not greater than the source image and have the same data type.''

What type of data type mentioned in that docs?

Nandika gravatar imageNandika ( 2016-10-28 13:36:35 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2016-10-27 14:04:15 -0500

Seen: 3,585 times

Last updated: Oct 28 '16