Face detection

This scrips allows to detect faces on real time and remark it on a red square.

Enter into python virtual enviroment:

# workon cv

Execute the code :

# python3 faces.py

Let's explain the code

In the first part we need to import the libraries that we are going to use:

import cv2
import sys
from time import sleep

Decleare variable to know where is the databases so we could create our face cascade algorithm and start capturing the frames of the default webcam.

cascPath = "database.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)

Here we capture the video, The read() functions reads one frame from the video sources.

while True:
    if not video_capture.isOpened():
        print('No camera detected.')
        sleep(5)
        pass

    # Read each frame
    ret, frame = video_capture.read()

Then we create rectangles so we could put on the frame when a face is detected.

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Create a  rectangle when a face is detected
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 9, 9), 2)


    cv2.imshow('Face detector', frame)

Finallly we need to realase the webcam and destroy the frame that we create.

Last updated