Why is python throwing Assertation error for object detection in opencv?

Viewed 93

I am trying to run this code. But python is throwing an error for the line 'cv2.detectmultiscale'

I trained a a custom object detector using opencv_createsamples and opencv_traincascade. The error I am getting is :

cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-j8nxabm_\opencv\modules\objdetect\src\cascadedetect.cpp:1389: error: (-215:Assertion failed) scaleFactor > 1 && _image.depth() == CV_8U in function 'cv::CascadeClassifierImpl::detectMultiScale'

My code is:

    color = np.random.uniform(0, 255, 3)
    fc = cv2.CascadeClassifier(r"D:\data\cascade.xml")
    img = cv2.imread('3450.jpg')
    img = cv2.resize(img, (100, 100))
    gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    grey = np.array(gr, dtype='uint8')
    features = fc.detectMultiScale(grey, scaleFactor = 0.6, minNeighbors= 1)
    for  (x,y,w,h) in features :
        cv2.rectangle(img, (x,y), (x+w,y+h), color,3)
    cv2.imshow(img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
1 Answers

As @Yuri Hinsburg mentioned on the comments, documentation says:

scaleFactor Parameter specifying how much the image size is reduced at each image scale.

Also the answer is in your error snippent, it clearly saying scaleFactor>1 && .., You can simply change it with a proper value or you don't choose any value and it uses default value(which I did in the example below) which is 1.1:

import numpy as np
import cv2

color = np.random.uniform(0, 255, 3)
fc = cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")
img = cv2.imread('face.jpg')
img = cv2.resize(img, (100, 100))
gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grey = np.array(gr, dtype='uint8')
faces = fc.detectMultiScale(grey)

for  (x,y,w,h) in faces :
    cv2.rectangle(img, (x,y), (x+w,y+h), color,3)
cv2.imshow("Test",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

enter image description here

Related