Python - 无法检测面部和眼睛?

Python - Unable to detect face and eye?

我正在尝试使用 OpenCV 库创建面部和眼睛检测。这是我一直在使用的代码。 运行 顺利,没有错误,但唯一的问题是没有显示任何结果,此代码没有找到面部和眼睛

import cv2
import sys
import numpy as np
import os

# Get user supplied values
imagePath = sys.argv[1]


# Create the haar cascade
faceCascade = cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascad_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascade_eye.xml')

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.2,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)

print "Found {0} faces!".format(len(faces))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = image[y:y+h, x:x+w]

    eyes = eyeCascade.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("Faces found", image)
print image.shape
cv2.waitKey(0)

对我来说,它可以在 Ubuntu 15.10 上使用 OpenCV 3.1.0-dev 和 python 3.4

在我的 jupyter notebook 中运行

难不成是你打错字了?

haarcascad_frontalface_default.xml => haarcascade_frontalface_default.xml

这里:

eyes = eyeCascade.detectMultiscale(roi_gray) => eyeCascade.detectMultiScale(roi_gray)

这是我的工作代码:

%matplotlib inline

import matplotlib
import matplotlib.pyplot as plt

import cv2
import sys
import numpy as np
import os

# Create the haar cascade
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')

# Read the image
image = cv2.imread('lena.png', 0)

if image is None:
    raise ValueError('Image not found')

# Detect faces in the image
faces = faceCascade.detectMultiScale(image)

print('Found {} faces!'.format(len(faces)))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), 255, 2)
    roi = image[y:y+h, x:x+w]

    eyes = eyeCascade.detectMultiScale(roi)
    for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)


plt.figure()
plt.imshow(image, cmap='gray')
plt.show()