2

Hi I'am trying to use matchTamplate func but its giving thar eror

OpenCV Error: Assertion failed ((depth == 0 || depth == 5) && type == _templ.type() && _img.dims() <= 2) in cv::matchTemplate, file C:\projects\opencv-python\opencv\modules\imgproc\src\templmatch.cpp, line 1102 Traceback (most recent call last): File "templatematch.py", line 10, in res = cv2.matchTemplate(img2gray, template, cv2.TM_CCOEFF_NORMED) cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1102: error: (-215) (depth == 0 || depth == 5) && type == _templ.type() && _img.dims() <= 2 in function cv::matchTemplate

Here is tho code

import cv2
import numpy as np 

img = cv2.imread("tempmatch1.jpg")
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

template = cv2.imread("tempmatch2.jpg")
w, h,_ = template.shape[::-1]

res = cv2.matchTemplate(img2gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
loc = np.where(res >= threshold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img, pt, (pt[0]+w, pt[1]+h), (0,0,255), 2)
cv2.imshow("detected", img)

k= cv2.waitKey(5) & 0xFF
if k==27:
    cv2.destroyAllWindows()

1 Answer 1

8

I suspect that the error is telling you that the template isn't compatible with the image it's being applied to. In this case, a color template and a grayscale image.

Instead of

res = cv2.matchTemplate(img2gray, template, cv2.TM_CCOEFF_NORMED)

try

res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, its perfectly worked and i just want to say it work when i did template grayscale to but its give better results when I do like you say
If color isn't important for matching, a grayscale template is probably a tiny bit faster, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.