pythonopencvnumpyface-detectioneye-detection

Python - Unable to detect face and eye?


I am trying to create a face and eye detection using OpenCV library. This is the code I been working with. It's running smoothly with no errors but the only problem is not showing any results no faces and eyes are found with this code

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)

Solution

  • For me it works in my jupyter notebook on Ubuntu 15.10 using OpenCV 3.1.0-dev with python 3.4

    Could it be, that you have a simple typo?

    haarcascad_frontalface_default.xml => haarcascade_frontalface_default.xml

    and here:

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

    That's my working code:

    %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()  
    

    enter image description here