使用Opencv Python从相机检测面部

时间:2016-03-18 16:27:09

标签: python opencv face-detection

我目前正试图从我的笔记本电脑相机中检测脸部,但由于某种原因,我找到的代码没有给出结果。代码正在启动网络摄像头并且没有给出任何错误但是没有为面部绘制矩形。没有检测到面孔,因此for循环永远不会运行,我尝试更改比例因子,但这没有帮助。两个xml文件都与代码位于同一文件夹中。代码如下:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.VideoCapture(0)

while(1):
    _,f=img.read()
    gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(f,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = f[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',f)
    if cv2.waitKey(25) == 27:
        break

cv2.destroyAllWindows()
img.release()

1 个答案:

答案 0 :(得分:1)

你好你的程序工作正常,你有2个小问题你需要将这个代码放在里面:

cv2.imshow('img',f)
if cv2.waitKey(25) == 27:
  break

确保您的xml文件已成立,这是我的代码:

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv3/3.0.0/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv3/3.0.0/share/OpenCV/haarcascades/haarcascade_eye.xml')

img = cv2.VideoCapture(0)

while(1):
    _,f=img.read()
    gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(f,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = f[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('Test',f)
    if cv2.waitKey(25) == 27:
        break

cv2.destroyAllWindows()
img.release()