Face Detection: My First Attempt¶

Import Libraries¶

In [1]:
import cv2 as cv
from matplotlib import pyplot as plt

Function To Detect The Number of Faces (Using the Haar Cascade Classifier)¶

In [2]:
def detectFaces(img):
    
    img = cv.imread(img)
    img = cv.resize(img, (400, 300))
    img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    
    plt.imshow(img_rgb)
    plt.text(10, 30, f'Original Image', color='white', fontsize=12, bbox=dict(facecolor='black', alpha=0.5))
    plt.axis('off')
    plt.show()
    
    face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')

    faces = face_cascade.detectMultiScale(img_rgb, scaleFactor=1.05, minNeighbors=7, minSize=(20, 20))

    num_faces = 0
    for (x, y, w, h) in faces:
        cv.rectangle(img_rgb, (x, y), (x+w, y+h), (0, 255, 0), 2)
        num_faces += 1
 
    plt.imshow(img_rgb)
    plt.text(10, 30, f'Faces Detected: {num_faces}', color='white', fontsize=12, bbox=dict(facecolor='black', alpha=0.5))
    plt.axis('off')
    plt.show()

Function Called On Example Photos¶

In [3]:
detectFaces('Photo1.jpg')
No description has been provided for this image
No description has been provided for this image
In [4]:
detectFaces('Photo2.jpg')
No description has been provided for this image
No description has been provided for this image
In [5]:
detectFaces('Photo3.jpg')
No description has been provided for this image
No description has been provided for this image

Detecting Face Parts (Eyes)¶

In [6]:
img = cv.imread('JimPicture.jpg')
img = cv.resize(img, (300, 300))
img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)

face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')

faces = face_cascade.detectMultiScale(img_rgb, scaleFactor=1.05, minNeighbors=7, minSize=(20, 20))


(x, y, w, h) = faces[0]

face_center = (x + w // 2, y + h // 2)
face_axes = (w // 2, h // 2)
cv.ellipse(img_rgb, face_center, face_axes, 0, 0, 360, (0, 255, 0), 2)

  
roi_gray = img[y:y+h, x:x+w]

eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
    eye_center = (x + ex + ew // 2, y + ey + eh // 2)
    eye_axes = (ew // 2, eh // 2)
    cv.ellipse(img_rgb, eye_center, eye_axes, 0, 0, 360, (0, 0, 255), 2)

   
plt.imshow(img_rgb)
plt.axis('off')
plt.show()
No description has been provided for this image