Open In App

Age Detection using Deep Learning in OpenCV

Last Updated : 13 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of age prediction might sound simple at first but it’s quite challenging in real-world applications. While predicting age is typically seen as a regression problem this approach faces many uncertainties like camera quality, brightness, climate condition, background, etc. In this article we’ll build a program that predicts the age of a person from an image using deep learning i.e Age Predictor project using OpenCV

Workflow of Age Prediction Model

Instead of predicting an exact age a more effective approach is to categorize age into specific ranges. Researchers found that this classification approach significantly improved accuracy in real-world scenarios. The workflow for building the age detection system includes:

Workflow with OpenCV

  1. Live Feed: The process begins with a live feed typically a video stream from a camera or webcam. This feed will be processed frame by frame to detect faces in real-time.
  2. Face Detection Model: The live feed is passed through a Face Detection Model. The model detects faces within the frame, using a deep learning-based approach like OpenCV’s DNN module.
  3. Crop Face Blob from Frame: Once faces are detected the next step is to crop the face region from the detected frame. This region of interest (ROI) is then passed into the next stages for age prediction.
  4. Age Detection Model: The cropped face is passed into the Age Detection Model. This model predicts the age of the person by classifying them into specific age ranges. The model uses pre-trained networks to make predictions based on the face’s features.
  5. Gender Detection Model: Similar to the age detection the cropped face is also passed into the Gender Detection Model. This model predicts the gender like male or female based on their facial characteristics.
  6. Output Image: Finally the predicted age and gender are added as text annotations on the frame. The processed frame with these annotations is shown as the output image.

Now that we know the workflow we can start budling model in python.

Implementing Age prediction Model

For simplicity and better understanding we will be only predicting age of person. Here is the step by step process to implement it.

1. Importing Libraries

First we need to import numpy and OpenCV libraries for the project. 

Python
import cv2
import numpy as np
from google.colab.patches import cv2_imshow 

2. Loading Pre-trained Models

Next we’ll load the pre-trained models for face detection and age prediction. OpenCV’s deep neural network (DNN) module allows us to use these models. You can download all Pre trained model from here.

  • face_proto and face_model: Files for the pre-trained face detection model.
  • age_proto and age_model: Files for the pre-trained age prediction model.
  • cv2.dnn.readNetFromTensorflow: Reads the face detection model into OpenCV.
  • cv2.dnn.readNetFromCaffe: Reads the age prediction model into OpenCV.
Python
face_proto = "opencv_face_detector.pbtxt"
face_model = "opencv_face_detector_uint8.pb"
age_proto = "age_deploy.prototxt"
age_model = "age_net.caffemodel"

face_net = cv2.dnn.readNetFromTensorflow(face_model, face_proto)
age_net = cv2.dnn.readNetFromCaffe(age_proto, age_model)

3. Detecting Faces in an Image

We now define a function to detect faces in an image. This function uses OpenCV’s DNN module to process the image and find faces.

  • cv2.dnn.blobFromImage: Converts the image into a blob format required by the DNN model.
  • net.setInput(blob): Sets the input to the face detection model.
  • net.forward(): Runs the forward pass to detect faces.
  • confidence threshold: Filters out faces that have a low detection confidence.
Python
def detect_faces(net, frame, conf_threshold=0.7):
    frame_height = frame.shape[0]
    frame_width = frame.shape[1]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], False, False)
    net.setInput(blob)
    detections = net.forward()
    face_boxes = []
    for i in range(detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence > conf_threshold:
            x1 = int(detections[0, 0, i, 3] * frame_width)
            y1 = int(detections[0, 0, i, 4] * frame_height)
            x2 = int(detections[0, 0, i, 5] * frame_width)
            y2 = int(detections[0, 0, i, 6] * frame_height)
            face_boxes.append([x1, y1, x2, y2])
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), int(round(frame_height/150)), 8)
    return frame, face_boxes

4. Predicting Age

Once faces are detected we can predict the age for each detected face. This is done by preprocessing the face image and passing it through the age prediction model.

  • cv2.dnn.blobFromImage: Prepares the face image by resizing and normalizing it for input into the age prediction model.
  • net.forward(): Runs the forward pass to predict the age.
  • age_preds[0].argmax(): Finds the index of the highest probability, which corresponds to the predicted age range.
Python
def predict_age(face, net):
    blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
    net.setInput(blob)
    age_preds = net.forward()
    age = age_list[age_preds[0].argmax()]
    return age

5. Processing a Single Image

Finally we will define a function to process an image. This function will load the image, detect faces, predict the age for each face and display the result.

  • cv2.imread: Reads the image from the provided path.
  • detect_faces: Detects faces in the image.
  • predict_age: Predicts the age for each face.
  • cv2.putText: Adds the predicted age as text on the image.
  • cv2_imshow: Displays the image.
Python
def process_image(image_path):
    frame = cv2.imread(image_path)
 
    if frame is None:
        print(f"Error: Image not found at {image_path}")
        return

    frame, face_boxes = detect_faces(face_net, frame)
    
    for (x1, y1, x2, y2) in face_boxes:
        face = frame[max(0, y1-20):min(y2+20, frame.shape[0]-1), 
                     max(0, x1-20):min(x2+20, frame.shape[1]-1)]
        age = predict_age(face, age_net)
        cv2.putText(frame, f"Age: {age}", (x1, y1-10), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2, cv2.LINE_AA)
 
    cv2_imshow(frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

image_path = "kid1.jpg"
process_image(image_path)

Output:

download

Age Prediction

Here used a image of kid to predict his age and we can see model is working fine by giving a age range of 4-6 for the kid.

You can easily adapt this approach to process real-time video feeds and further enhance the system by adding features like gender classification or emotion detection. Additionally experimenting with custom pre-trained models such as YOLO for face detection can improve accuracy and performance. In this article you not only learn how to integrate OpenCV with deep learning models for image processing and age detection but also gain insights into expanding the system to create more interactive and advanced applications.

Get the complete source code link here:

Source code : click here.



Next Article

Similar Reads