0

I have the following code:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 
                                     'haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 
                                    'opencv_haarcascade_eye.xml')

img = cv2.imread('lena.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
faces = face_cascade.detectMultiScale(gray)

for (x,y,w,h) in faces:

            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_gray)

    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)

k = cv2.waitKey(0)

if k == 27:     
    
    cv2.destroyAllWindows()

elif k == ord('s'):

    cv2.imwrite('frame',img)

    cv2.destroyAllWindows()

Running it produces the following error:

eyes = eye_cascade.detectMultiScale(roi_gray) cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale' [ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

When I removed eyes = eye_cascade.detectMultiScale(roi_gray) part, the code works fine with fave detection but with eyes = eye_cascade.detectMultiScale(roi_gray) parth its showing error.

How to solve this issue?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
shubham k
  • 9
  • 1

2 Answers2

0

The error is just in the process of loading of the classifier. It should be

eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 
                                    'haarcascade_eye.xml')

Instead of

eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 
                                    'opencv_haarcascade_eye.xml')

At least, this solution is shown here, and I tested it with OpenCV(4.5.1)

MefAldemisov
  • 867
  • 10
  • 21
-1

According to this topic about roi_gray explanation

for (x,y,w,h) in faces:
    roi_gray=gray[y:y+h,x:x+w]    #This particular code will return the cropped face from the image.
    roi_color = img[y:y+h, x:x+w] #This particular code will return the details of the image that u will recive after getting the co-ordinates of the image.

Are you sure there is a face in the image? roy_gray returns cropped face from the image but if there isn't any maybe you will get an error I think.

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28