pythonopencvcascade-classifier

in <module> gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)?


I am trying to make an car detector/classifier with cv2 i have a .xml file i downloaded from github: https://gist.github.com/199995/37e1e0af2bf8965e8058a9dfa3285bc6 and when ever i run my code i get

Traceback (most recent call last):

  File "C:\Users\user1\Downloads\Stuff\Python\cascades\Car_classification.py", line 13, in <module>
    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

and my code is:

import cv2
import numpy as np

cap = cv2.VideoCapture('car.jpg')

font = cv2.FONT_HERSHEY_TRIPLEX

harcascade = cv2.CascadeClassifier("cars.xml")

while True:
    ret,frames = cap.read()

    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
    
    cars = harcascade.detectMultiScale(gray, 1.1 , 2)
    
    for (x,y,w,h) in cars:
        cv2.rectangle(frames,(x,y),(x+w,y+h),(255,0,0),2)
        cv2.putText(frames,str("Car"),(x,y+h),font,1,255)
     
    
    cv2.imshow('img',frames)   

     
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    
    
cap.release()
cv2.destroyAllWindows()

My input image:

enter image description here

My output image:

It is a car but i don't think a tire is a car! so what am i doing wrong?


Solution

  • Can't say why your classification isn't picking up on the car with any certainty, since I have no info on where https://gist.github.com/199995/37e1e0af2bf8965e8058a9dfa3285bc6 came from. Without knowing that, I can't say what kind of images it's expected to be able to detect. It's possible that it was trained to recognize cars from images more like this parking lot, or even more zoomed out. In which case your example image is completely unlike what it has been trained to detect. Without knowing more it's impossible to say.

    As for that error message you're getting, that one I can at least explain.

    cap = cv2.VideoCapture('car.jpg')
    

    You're opening an image as a video. On the first pass through the loop, it's (surprisingly) able to read image data, but after that on the next pass there's no more "frames" to read, so your frames object is None, there's no image data in it. This means when you try to convert it to grayscale, the operation is failing.