Template Matching - Template image is not there [closed]
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!
lol, python users NEVER seem to understand, that loading an image CAN go wrong, e.g because of a wrong path.
you never check, IF your VideoCapture opened, or if your image was loaded.
being too arrogant to check something simple, your code fails on the NEXT line.
@LBerger -- make sure you have a xxx remark about this in your upcoming book, please !
@berak Path is fine, thanks. Video shows on the frame, gray video shows on the frame (I've traced it), template shows on another frame for the duration of the video (checked it too). Don't go too fast on your assumptions mate.
yet your `
cv2.cvtColor()
failed, because it's input was invalid.(sorry to say so, but you are found GUILTY of ignoring the
ret
value from the VideoCapture. samp problem as in the 1st comment. you HAVE TO CHECK ANY IO, manually)@LBerger -- if we could put that into the heads of silly python noobs -- questions here, or on SO reduced by half !
may be something like that in python tutorial :
hehehe, that'll do ;)