Home > Software engineering >  CascadeClassifier Bad Argument error OpenCV
CascadeClassifier Bad Argument error OpenCV

Time:09-01

I am running Python 3.9 creating a project in OpenCV and getting an error on my car_tracker variable the code works when I comment that line out but not sure what is causing it.

Traceback (most recent call last): File "C:\Users\XXXX\Desktop\Car_Automation\Car_Automation.py", line 18, in car_tracker = cv2.CascadeClassifier(trained_car_data) cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'CascadeClassifier'

Overload resolution failed:

  • Can't convert object to 'str' for 'filename'
import cv2
    
#Our pre-trained car classifier
pedestrian_tracker = cv2.CascadeClassifier('haarcascade_fullbody.xml')
trained_car_data = cv2.CascadeClassifier('car_detector.xml')

# create opencv image
img = cv2.imread('car.jpg')

#convert to grayscale
black_n_white = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#Create car classifier
car_tracker = cv2.CascadeClassifier(trained_car_data)    #Error happens on this line

#detect cars
cars = trained_car_data.detectMultiScale(black_n_white)

print(cars)

#Display the image with the faces spotted
cv2.imshow('Car Detector', black_n_white)

#Don't autoclose Wait here in the code and listen for a key press)
cv2.waitKey()

print("Code Completed")

CodePudding user response:

You don't need line 13.

Change this:

cars = trained_car_data.detectMultiScale(black_n_white)

to:

cars = trained_car_data.detectMultiScale(img, 
                                 scaleFactor=1.3, 
                                 minNeighbors=4, 
                                 minSize=(30, 30),
                                 flags=cv.CASCADE_SCALE_IMAGE)

CodePudding user response:

(as already said in the comments, yesterday)

Your code is equivalent to literally passing a cascade classifier instance into the constructor of a cascade classifier:

car_tracker = cv2.CascadeClassifier(cv2.CascadeClassifier('car_detector.xml'))

So that is the mistake that causes the exception you're asking about.

Simply drop this line:

car_tracker = cv2.CascadeClassifier(trained_car_data)

because you aren't using the result anyway (if that hadn't thrown an exception).

If you happen to have trouble with the multiscale detection, I would suggest that you try parameters other than the defaults. Detections can be sensitive to the scale factor. Pick something close to 1.0, something less than 1.3 for sure, because that scale step is significant and may cause you to lose detections on instances that are too big in one scale and too small in the other.

  • Related