-1

I am entering this code for face detection:

import cv2
face_cascade = cv2.CascadeClassifier('venv/Lib/site- 
packages/cv2/data/haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier('venv/Lib/site-packages/cv2/data/haarcascade_eye.xml')

img = cv2.imread('Documents\Face detection\face1.jpg')

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

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

for (x, y, w, h) in faces:
img = 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)
cv2.waitKey(0)
cv2.destroyAllWindows()

But when I run this code it gave this error:

Traceback (most recent call last): File "C:/Users/Nisha/Documents/Face detection/Face detection.py", line 9, in gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Please tell in detail how I get rid of this error or tell any changes or tell any alternative code which doesn't produce error and I can also complete my work. Actually, I am new in IT so I produce many error in small codes so please guide me so I can keep moving.

  • 2
    The `Mat` you are passing to `cvtColor` - `img`, is either empty or malformed. Check the path, it does not appear to be valid. – stateMachine Mar 27 '20 at 04:00

2 Answers2

1

The file you're trying to read is missing:

img = cv2.imread('Documents\Face detection\face1.jpg')

put print( img.shape ) right after this line to make sure your image is read properly.

If you're working in Windows, I'd recommend you to print('Documents\Face detection\face1.jpg') as well and see what file you're trying to read. I bet you lose all path separators.

lenik
  • 23,228
  • 4
  • 34
  • 43
0

try using this code to read image file:

import os
path = os.getcwd()

img = cv2.imread(path+'Documents\Face detection\face1.jpg')
Ishwar Ramdasi
  • 166
  • 1
  • 4