-4

I am trying to detect a car from a car video using haarcascades and I had an output. But the error splits out there:

File "D:\Documents\KY7\Oracle\baocao\car_detector_haarcascades\car.py", line 10, in gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Here is the code:

import numpy as np
import cv2

car_cascade = cv2.CascadeClassifier('haarcascade_car.xml')

cap = cv2.VideoCapture(r"D:\Documents\KY7\Oracle\baocao\car_detector_haarcascades\cars.mp4")

while cap.isOpened():
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cars = car_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in cars:
        cv2.rectangle(img,(x,y),(x+w+5,y+h+5),(0,0,255),3)

    cv2.imshow('Car Detector',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

I have no idea to fix this error

Oga
  • 1
  • 1
  • 1
  • 1

1 Answers1

1

Your error is img is empty

Probably you need to check if capture is successful or not, something like this

if not ret:
    break
doudev
  • 143
  • 1
  • 11