1
import cv2
import numpy as np
from matplotlib import pyplot as plt

template = cv2.imread('templateGray.PNG', 0)
height, width = template.shape[::]
vidcap = cv2.VideoCapture('Vid.mp4')
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('output.avi', fourcc, 30.0, (320,  240))


while vidcap.isOpened():
    ret, frame = vidcap.read()
    img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    res = cv2.matchTemplate(img_gray, template, cv2.TM_SQDIFF)
    plt.imshow(res, cmap='gray')
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = min_loc
    bottom_right = (top_left[0] + width, top_left[1] + height)
    cv2.rectangle(frame, top_left, bottom_right, (255, 0, 0), 2)
    out.write(frame)

cv2.waitKey(0)
vidcap.release()
out.release()
cv2.destroyAllWindows()

Traceback (most recent call last): File "(program name path here)", line 16, in res = cv2.matchTemplate(img_gray, template, cv2.TM_SQDIFF) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1175: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'cv::matchTemplate'

Process finished with exit code 1

thats my code and error message. i first started with a screenshot of the video saved to a variable called img_rgb with imread, then img_gray was the grayscale version of that image. when i did it like that it worked, but it broke when i switched to a frame from a video. does anyone know what im doing wrong?

  • 1
    Is your template larger than the video frame? If so, that is the issue. The template must be smaller than the frame. If that is not it, then are you sure you actually have a good video frame. Have you done any checks to be sure? – fmw42 Mar 08 '22 at 00:15
  • @fmw42 the template used to be 166 by 318, i resized it to 78 by 150 and I think it fixed one problem. now its throwing an error on line 14 instead. here's the error message: Traceback (most recent call last): File "(insert file name here)", line 14, in img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' Process finished with exit code 1 – DemonPotato4411 Mar 08 '22 at 02:30
  • @fmw42 nevermind i fixed that by putting everything in the while loop except the first line inside an `if ret:` block with an `else: break` at the end. now it runs without error, i just need to make it draw the rectangle correctly beyond the first frame. – DemonPotato4411 Mar 08 '22 at 02:48

0 Answers0