Ask Your Question

Revision history [back]

Template Matching - Template image is not there

Hi.

I'm trying to make a simple Template Matching code to detect a TV channel logo in a video from that same channel.

Code is this:

import cv2
import numpy as np

cap = cv2.VideoCapture('C:/Users/Eduardo/Desktop/VA/videoplayback.mp4')
template = cv2.imread('C:/Users/Eduardo/Desktop/VA/tve1.png')
gray_template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
cv2.imshow("Template", gray_template)

w, h = gray_template.shape[::-1]

while True:
    _, frame = cap.read()
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    res = cv2.matchTemplate(gray_frame, gray_template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.8)

    for pt in zip(*loc[::-1]):
        cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 3)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1)

    if key == 27:
        break;

cap.release()
cv2.destroyAllWindows()

But I'm getting this error:

Traceback (most recent call last):
  File "otradetec.py", line 14, in <module>
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(3.4.5) d:\build\opencv\opencv-3.4.5\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

As far as my understanding goes, this error means that there is no gray_frame image, but I don't know why. The grey_template image (the one I'm matching with the .mp4 video) is not opened for the full duration of the video, when I suppose it should.

Any ideas? Been five hours stuck with this...

Thanks!