Reputation: 29
I am trying this python code snippet:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 3)
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 I get this error:
Traceback (most recent call last):
File "test.py", line 14, in <module>
roi_color = img[y:y+h, x:x+w]
TypeError: 'NoneType' object has no attribute '__getitem__'
I found this program here.
Upvotes: 1
Views: 1891
Reputation: 31
If you are sure that your image path is right and still the problem persist try doing this:
From this line
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
remove img =
, let it be just
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
This worked for me.
Upvotes: 3
Reputation: 323
I had the same problem and it appears that there is a bug in the code with the img variable. It looks like there is confusion with the second setting of the img variable within the first 'for' loop. Just make sure you also have the path to your image set correctly as well.
I changed the code to the following and it worked for me.
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('/path/to/your/image/img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 3)
for (x,y,w,h) in faces:
img2 = 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()
Upvotes: 1