view raw
Imran Ibrahimi Imran Ibrahimi - 8 months ago 166
Python Question

Raspberry Pi 3 Python and Opencv for facial recognition

I am receiving this message when trying to execute script whether in virtual environment or a normal Python shell.

File "/home/pi/", line 10, in <module>
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
error: /home/pi/opencv-3.1.0/modules/imgproc/src/color.cpp:8000: error: (-215) scn == 3 || scn == 4 in function cvtColor

Here is my code:

import cv2

#Load an image from file
image = cv2.imread("fronthead.jpg", 1)

#Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml')

#Convert to grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

#Look for faces in the image using the loaded cascade file
faces = face_cascade.detectMultiScale(gray, 1.1, 5)

print "Found "+str(len(faces))+" face(s)"

#Draw a rectangle around every found face
for (x,y,w,h) in faces:

#Save the result image

Why am I getting this error?


Your image variable is apparently not a 3 or 4 channel image. Thus, cvtColor() is unable to transform it to grayscale.

Check image.shape and see that it returns something with the right dimensions (i.e. a 3D array with last dimension 3 or 4).

It is also quite possible that image is None, which usually means that the path to the file is wrong.