简体   繁体   English

使用Haar进行人脸检测-OpenCV Python

[英]Face Detection using Haar - OpenCV python

I am trying this python code snippet: 我正在尝试以下python代码段:

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 . 我在这里找到了这个程序。

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 删除img = ,让它只是

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

This worked for me. 这对我有用。

I had the same problem and it appears that there is a bug in the code with the img variable. 我遇到了同样的问题,并且似乎在带有img变量的代码中存在错误。 It looks like there is confusion with the second setting of the img variable within the first 'for' loop. 第一个“ for”循环中的img变量的第二个设置似乎有些混乱。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM