Open In App

Face Detection using Python and OpenCV with webcam

Last Updated : 17 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.

Approach/Algorithms used for Face Detection

  1. This project uses LBPH (Local Binary Patterns Histograms) Algorithm to detect faces. It labels the pixels of an image by thresholding the neighborhood of each pixel and considers the result as a binary number.
  2. LBPH uses 4 parameters : 
    (i) Radius: the radius is used to build the circular local binary pattern and represents the radius around the 
    central pixel. 
    (ii) Neighbors : the number of sample points to build the circular local binary pattern. 
    (iii) Grid X : the number of cells in the horizontal direction. 
    (iv) Grid Y : the number of cells in the vertical direction.
  3. The model built is trained with the faces with tag given to them, and later on, the machine is given a test data and machine decides the correct label for it. 

Face Detection using Python

Step 1: Setup Your Google Colab Environment

  • Open Google Colab: Go to Google Colab.
  • Create a new notebook: Click on File -> New Notebook.
  • Install OpenCV: Since Colab doesn’t have OpenCV pre-installed, run the following command to install it.
 !pip install opencv-python opencv-contrib-python

Step 2:Upload Haarcascade File

The code relies on haarcascade_frontalface_default.xml to detect faces. You need to upload this file. Download the file from this link.

In Colab, upload it by clicking on the “Files” icon on the left sidebar and selecting “Upload.”

Step 3:Code for Face Detection (First Part)

Now you can run the first part of the code for capturing face images and saving them to a dataset. Copy and paste the following code into a Colab cell.

import cv2
import numpy as np

# Haarcascade file path (make sure this file is uploaded)
haar_file = 'haarcascade_frontalface_default.xml'

# Load the image from your uploaded file
img_path = '/content/sample_image.jpg'  # Update with your image path
image = cv2.imread(img_path)

if image is None:
    print("Image not loaded correctly.")
else:
    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Load Haarcascade for face detection
    face_cascade = cv2.CascadeClassifier(haar_file)

    # Detect faces
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Draw rectangles around faces
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)

    # Show the image with detected faces
    cv2.imshow('Detected Faces', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Step 4: Upload an Image to Colab

  1. You need to first upload an image manually in Colab.
  2. Click on the “Files” icon on the left sidebar in Colab.
  3. Upload your image (e.g., face_image.jpg).

Following code should be run after the model has been trained for the faces :

import cv2
import os

# Haarcascade file path (Ensure the correct path is set if using Google Drive)
haar_file = 'haarcascade_frontalface_default.xml'

# Upload an image to Colab (Change the file path as needed)
image_path = 'face_image.jpg'  # Replace with the path to your uploaded image

# Load the image
image = cv2.imread(image_path)

# Check if the image was loaded successfully
if image is None:
    print("Error: Could not load image.")
else:
    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Load Haarcascade for face detection
    face_cascade = cv2.CascadeClassifier(haar_file)

    # Detect faces in the image
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Draw rectangles around faces
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)

    # Display the output image with detected faces
    cv2.imwrite('output_image.jpg', image)
    from google.colab.patches import cv2_imshow
    cv2_imshow(image)

    # Optionally, save the image with rectangles
    cv2.imwrite('/content/output_image.jpg', image)

Note : Above programs will not run on online IDE. 
 
It may look something different because I had integrated the above program on flask framework. Running of second program yields results similar to the below image : 

imresizer-1728833810749




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg