Python | Face Detection

By Casper_x | Python Programs | 1 Mar 2023


Face Detection

Artificial intelligence is a technology that has evolved significantly in recent years. One of its most popular application areas is facial recognition, which allows for the detection and identification of human faces in images and videos. 

In this article, we will explore a Python face detection script using the 'OpenCV' library. We will discover how this script works, how it can be used to detect faces in a live video, and how it can be customized to meet specific needs. So, buckle up for this fascinating journey into the world of face detection with Python and OpenCV!

 
     What is OpenCV ?

 

Official Link : https://opencv.org

OpenCV is an open source library for image processing and computer vision. It contains numerous functions and algorithms for image manipulation, object detection, shape and motion recognition, and much more

OpenCV is widely used in various fields such as robotics, surveillance, automotive, face recognition, and augmented reality.

 

     Prerequisites :

The code starts by importing the ‘opencv-python’ library

pip install opencv-python

 

     Program :

 

This program uses OpenCV to detect faces in a live video. It loads a pre-trained face detection model and initializes video capture from the camera.

# Generally on this repertory ‘../cv2/data/‘ on your venv

face_cascade = cv2.CascadeClassifier(‘/Your/Path/To/This/Files/haarcascade_frontalface_default.xml ')

print(« Camera opening and face detection  :", time.strftime("%d/%m/%Y"), "at", time.strftime("%H:%M:%S"))

 

# Initialize the video capture 

cap = cv2.VideoCapture(0)

Then a function is created to take a picture if a face is detected, with information such as the date and time of detection and the number of faces detected. 

# Function to take a photo if a face is detected

def take_picture_if_face_detected(frame, faces, num_faces, quality=110):

    if len(faces) > 0:

        filename = "/Your/Saving/Path/For/Photo/" + "face_detected_" + time.strftime("%Y%m%d_%H%M%S") + ".jpg"

        cv2.putText(frame, "Date/Hour : " + time.strftime("%d/%m/%Y %H:%M:%S"), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)

        cv2.putText(frame, "Detected Faces : " + str(num_faces), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)

        cv2.imwrite(filename, frame, [cv2.IMWRITE_JPEG_QUALITY, quality])

Before the loop, don’t forget to set the variable ‘num_faces’ to 0.

num_faces = 0

The program reads each frame of the video and detects faces using the face detection model, then draws rectangles around the detected faces.

while True:

    # Lire un frame

    ret, frame = cap.read()

 

    # Convert to grayscale

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

 

    # Detect the face

    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

 

    # Increment the detected face counter

    num_faces = len(faces)

 

    # Draw rectangles around detected face

    for (x, y, w, h) in faces:

        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 4)

 The function to take a picture is called for each frame, and the video is displayed in real-time with the rectangles around the detected faces. 

    # Call the function to take a photo if a face is detected

    take_picture_if_face_detected(frame, faces, num_faces, quality=110) 

The user can press the 'q' key to exit the video. 

  # Exit if you press the ‘q’ key.

    if cv2.waitKey(1) & 0xFF == ord('q'):

        print("User has quit.")

        break

Finally, the video capture is released and the windows are destroyed.

print(« End of camera session on :", time.strftime("%d/%m/%Y"), "at", time.strftime("%H:%M:%S"))

# Release video capture and destroy windows

cap.release()

cv2.destroyAllWindows()

Leave a comment if you have any questions

 

If you enjoy my blog posts, you can support me by a tip in my wallet.

Thanks for you support 🫶

 

BTC : bc1qvfmetg2d36mmntrg56ld0tdrte8cqeygjxdpsg

ETH  | USDC | USDT : 0x02AbfBf22fA72d068Ff305e58dF782e58F863274

DOGE : DLtGbPrFvwW5y7jFuvuDAkZGNB2eAErAxA

 

See you soon ! 🤙

Casper_X 👻

Here is the full program :

 

import cv2
import time

# Generally on this repertory ‘../cv2/data/‘ on your venv
face_cascade = cv2.CascadeClassifier(‘/Your/Path/To/This/Files/haarcascade_frontalface_default.xml ')
print(« Camera opening and face detection  :", time.strftime("%d/%m/%Y"), "at", time.strftime("%H:%M:%S"))

# Initialize the video capture 
cap = cv2.VideoCapture(0)

# Function to take a photo if a face is detected
def take_picture_if_face_detected(frame, faces, num_faces, quality=110):
    if len(faces) > 0:
        filename = "/Your/Saving/Path/For/Photo/" + "face_detected_" + time.strftime("%Y%m%d_%H%M%S") + ".jpg"
        cv2.putText(frame, "Date/Hour : " + time.strftime("%d/%m/%Y %H:%M:%S"), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2) 
        cv2.putText(frame, "Detected Faces : " + str(num_faces), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2) 
        cv2.imwrite(filename, frame, [cv2.IMWRITE_JPEG_QUALITY, quality])
        print("Face detected ! Photo enregistrée à", time.strftime("%H:%M:%S"))

num_faces = 0
while True:
    # Lire un frame
    ret, frame = cap.read()

    # Convert to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect the face
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # Increment the detected face counter
    num_faces = len(faces)

    # Call the function to take a photo if a face is detected
    take_picture_if_face_detected(frame, faces, num_faces, quality=110)

    # Draw rectangles around detected face
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 4)

    # Display image
    cv2.imshow('frame', frame)

    # Exit if you press the ‘q’ key.
    if cv2.waitKey(1) & 0xFF == ord('q'):
        print("User has quit.")
        break

print("End of camera session on :", time.strftime("%d/%m/%Y"), "à", time.strftime("%H:%M:%S"))
# Release video capture and destroy windows
cap.release()
cv2.destroyAllWindows()

How do you rate this article?

5


Casper_x
Casper_x

Python | Crypto | Javascript | Programming


Python Programs
Python Programs

Tutorials on the programming language 'Python'. In this blog you will find several basics Python programs to complete. Hope you enjoy the content !

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.