Close Menu
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
Facebook X (Twitter) Instagram
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us
Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
How To Electronics
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
How To Electronics
Home » Age & Gender Classification with OpenCV & Deep Learning on Raspberry Pi
Raspberry Pi Raspberry Pi Projects

Age & Gender Classification with OpenCV & Deep Learning on Raspberry Pi

Mamtaz AlamBy Mamtaz AlamUpdated:September 6, 20237 Mins Read
Share Facebook Twitter LinkedIn Telegram Reddit WhatsApp
Age & Gender Classification with OpenCV on Raspberry Pi
Share
Facebook Twitter LinkedIn Pinterest Email Reddit Telegram WhatsApp

Overview:

This project is about Age & Gender Classification with OpenCV and Deep Learning (specifically Convolutional Neural Networks or CNNs) on Raspberry Pi 4 Computer.

With the rise of social platforms, automatically determining age and gender from images has become increasingly important. However, the accuracy of current methods on real-world photos isn’t as good as the progress we’ve seen in face recognition. In this study, we demonstrate that using deep-convolutional neural networks (CNN) can significantly enhance the accuracy of age and gender classification. The model is based on Gil Levi & Tal Hassner Model published in 2015. It introduce a straightforward CNN design that’s effective even when there’s not a lot of data to train on.

In this guide, we’ll learn how to use OpenCV and Deep Learning to tell a person’s age and gender using a Raspberry Pi 4. OpenCV is a tool that helps computers understand pictures and videos. Deep Learning is a way for computers to learn from data, like how we learn from experience. When we combine these two, we can make a computer guess a person’s age and gender by looking at their picture. By the end of this guide, you’ll have a full idea of Age & Gender Classification Project with OpenCV & Deep Learning on Raspberry Pi.




Components Required

We need the following components for this project. You can purchase all items from given links:

S.N.ComponentsQuantityPurchase Link
1Raspberry Pi 41Amazon | SunFounder
2Raspberry Pi Camera1Amazon | SunFounder
2SD Card 16/32 GB1Amazon | SunFounder
35V, 3A DC Adapter for RPi1Amazon | SunFounder
4LCD Display (Optional)1Amazon | SunFounder
5Mouse & Keyboard (Optional)1Amazon | SunFounder

Raspberry Pi Camera Connection

The Raspberry Pi Camera is a peripheral device developed by the Raspberry Pi Foundation to be used with their series of Raspberry Pi single-board computers. The camera module provides a way to add video/photo capabilities to Raspberry Pi projects.

For this project, we can use a 5 mega-pixel Raspberry Pi Camera.

Raspberry Pi Camera Connection

Simply connect the Camera Module to the Raspberry Pi 4 Board using the Camera Connector.

To use the Camera you need to enable the Camera Module first. Open the Raspberry Pi Configuration Tool by typing sudo raspi-config in the terminal. Navigate to Interfacing Options > Camera and enable it.




Age & Gender Classification Method

The model proposed by Levi and Hassner in 2015 is a convolutional neural network (CNN). CNNs are a category of neural networks that have proven very effective in areas such as image recognition and classification. Their model was trained on the Adience dataset, which is unfiltered and not aligned, making it suitable for real-world, unconstrained images.

Age & Gender Classification using OpenCV & Convolutional neural networks CNN Deep Learning

The classification process is broken down into two primary steps:

  • Step 1: Face Detection – The first step involves scanning the input video stream to detect faces. This is crucial as the subsequent classification is based on the facial features.
  • Step 2: Age and Gender Prediction – Once a face is detected, the next step is to extract the face’s Region of Interest (ROI). This ROI is then fed into the age and gender detector algorithm. The algorithm analyzes the facial features and predicts both the age and gender of the individual.

The gender prediction will categorize the individual as either ‘Male‘ or ‘Female‘. For age prediction, the model classifies the individual into one of the predefined age brackets: (0 – 2), (4 – 6), (8 – 12), (15 – 20), (25 – 32), (38 – 43), (48 – 53), or (60 – 100).




Raspberry Pi Setup, Libraries & Dependencies Installation

OpenCV is required for Age and Gender Classification, and other image processing tasks present in the code. Hence you need to install the OpenCV first. Follow the following guide to install OpenCV in your system:

How to Install & Setup OpenCV on Raspberry Pi 4

The next step is to install picamera. Therefore install it using pip.

1
pip3 install picamera

Create a folder in the Home directory of your Raspberry Pi with any name such as “Age_Gender_Classfication“.

The code references multiple files used for age and gender classification. Download these files from the following links:

  1. opencv_face_detector.pbtxt
  2. opencv_face_detector_uint8.pb
  3. age_deploy.prototxt
  4. age_net.caffemodel
  5. gender_deploy.prototxt
  6. gender_net.caffemodel

Add these files to the folder you created above.

The setup part is complete now. We can move to the Age & Gender Classification Project with OpenCV & Deep Learning on Raspberry Pi.


Raspberry Pi Python Code for Age & Gender Classification

Now let’s develop a Python Code that helps in the classification of age and geneder using the OpenCV library and Raspberry Pi Camera.


Python Code

Open Thonny IDE and paste the following code to the Thonny Editor. Save this file with the any name such as “classification.py” to the folder that we created earlier. Ensure that these all the downloaded files are present in the directory mentioned in the code (/home/mypi/Age_Gender_Classfication/).

Here is the complete code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import cv2
 
def highlightFace(net, frame, conf_threshold=0.7):
    frameOpencvDnn = frame.copy()
    frameHeight = frameOpencvDnn.shape[0]
    frameWidth = frameOpencvDnn.shape[1]
    blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False)
    net.setInput(blob)
    detections = net.forward()
    faceBoxes = []
    for i in range(detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence > conf_threshold:
            x1 = int(detections[0, 0, i, 3] * frameWidth)
            y1 = int(detections[0, 0, i, 4] * frameHeight)
            x2 = int(detections[0, 0, i, 5] * frameWidth)
            y2 = int(detections[0, 0, i, 6] * frameHeight)
            faceBoxes.append([x1, y1, x2, y2])
            cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight/150)), 8)
    return frameOpencvDnn, faceBoxes
 
faceProto = "/home/mypi/Age_Gender_Classfication/opencv_face_detector.pbtxt"
faceModel = "/home/mypi/Age_Gender_Classfication/opencv_face_detector_uint8.pb"
ageProto = "/home/mypi/Age_Gender_Classfication/age_deploy.prototxt"
ageModel = "/home/mypi/Age_Gender_Classfication/age_net.caffemodel"
genderProto = "/home/mypi/Age_Gender_Classfication/gender_deploy.prototxt"
genderModel = "/home/mypi/Age_Gender_Classfication/gender_net.caffemodel"
 
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
genderList = ['Male', 'Female']
 
faceNet = cv2.dnn.readNet(faceModel, faceProto)
ageNet = cv2.dnn.readNet(ageModel, ageProto)
genderNet = cv2.dnn.readNet(genderModel, genderProto)
 
video = cv2.VideoCapture(0)
padding = 20
 
hasFrame, frame = video.read()
if not hasFrame:
    print("Couldn't read a frame from the video.")
    exit()
 
desired_window_width = 480
ratio = desired_window_width / frame.shape[1]
height = int(frame.shape[0] * ratio)
 
while True:
    hasFrame, frame = video.read()
    if not hasFrame:
        break
    frame = cv2.resize(frame, (desired_window_width, height))
 
    resultImg, faceBoxes = highlightFace(faceNet, frame)
 
    for faceBox in faceBoxes:
        face = frame[
            max(0, faceBox[1] - padding):min(faceBox[3] + padding, frame.shape[0] - 1),
            max(0, faceBox[0] - padding):min(faceBox[2] + padding, frame.shape[1] - 1)
        ]
        blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
        genderNet.setInput(blob)
        genderPreds = genderNet.forward()
        gender = genderList[genderPreds[0].argmax()]
 
        ageNet.setInput(blob)
        agePreds = ageNet.forward()
        age = ageList[agePreds[0].argmax()]
 
        text = "{}:{}".format(gender, age)
        cv2.putText(resultImg, text, (faceBox[0], faceBox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2, cv2.LINE_AA)
        cv2.imshow("Detecting age and gender", resultImg)
 
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break
 
cv2.destroyAllWindows()
video.release()



Code Explanation

Let’s break down the code and explain each section:

1
import cv2

This line imports the OpenCV library, which is a popular library for computer vision tasks.

1
2
3
def highlightFace(net, frame, conf_threshold=0.7):
    ...
    return frameOpencvDnn, faceBoxes

This function, highlightFace, is designed to detect and highlight faces in a given image (frame). It uses a deep learning model (net) and a confidence threshold (conf_threshold). The function returns the image with highlighted faces and the bounding boxes of the detected faces.

1
2
3
4
faceProto = ".../opencv_face_detector.pbtxt"
faceModel = ".../opencv_face_detector_uint8.pb"
...
genderNet = cv2.dnn.readNet(genderModel, genderProto)

Here, paths to various pre-trained models and their configurations are defined. These models are for face detection, age classification, and gender classification. The models are then loaded into memory using their respective paths.

1
2
3
4
5
video = cv2.VideoCapture(0)
padding = 20
hasFrame, frame = video.read()
...
height = int(frame.shape[0] * ratio)

The webcam is accessed to capture video frames. The first frame is read to determine the video resolution, and the desired height of the frame is calculated based on a fixed width.

1
2
3
while True:
    ...
    cv2.imshow("Detecting age and gender", resultImg)

This is the main loop where each frame from the webcam is processed. For each frame:

  • The frame is resized.
  • Faces are detected using the highlightFace function.
  • For each detected face, the face region is extracted, and gender and age are predicted using the respective models.
  • Predicted gender and age are displayed on the frame.
  • The processed frame is displayed in a window.

1
2
3
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
    break

This section checks for a key press. If the “q” key is pressed, the loop is exited.

1
2
cv2.destroyAllWindows()
video.release()

After exiting the loop, all OpenCV windows are closed, and the video capture is released.


Testing & Results

Run the above code. A window will appear immediately which shows the image from Camera.



To detect the age and gender, you may introduce yourself or some other person in front of Camera or use an image. The age and gender will be shown in the screen.

The model works well for both male and female and can accurately detect the age group.

Age & Gender Classification with OpenCV Deep Learning

Some age category is missed or undefined in the code, in that case the nearest age group is shown.

Age & Gender Classification with OpenCV

You may try this model with smaller age groups or older age groups.


Conclusion

In conclusion, our project successfully harnessed the capabilities of OpenCV and Deep Learning to classify age and gender from images using a Raspberry Pi 4. Drawing inspiration from the model by Gil Levi & Tal Hassner, we’ve demonstrated that deep-convolutional neural networks can significantly improve classification accuracy, even with limited training data.

The combination of OpenCV’s image processing and the advanced learning techniques of Deep Learning has enabled us to create a reliable system. As a result, anyone using our guide can now efficiently determine age and gender from photos, showcasing the practical applications of integrating advanced technologies in real-world scenarios.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Reddit Telegram WhatsApp
Previous ArticleMeasure Wind Speed & Direction with Ultrasonic Anemometer & Arduino
Next Article The Best 60W Electric Soldering Iron Station – Test & Review

Related Posts

ADXL375 Accelerometer with Raspberry Pi Pico & MicroPython

ADXL375 Accelerometer with Raspberry Pi Pico & MicroPython

Updated:July 24, 2025
Interface BMI160 with Raspberry Pi Pico & MicroPython

Interface BMI160 with Raspberry Pi Pico & MicroPython

Updated:February 2, 20253K
Shift Register 74HC595 with Raspberry Pi Pico & MicroPython

Shift Register 74HC595 with Raspberry Pi Pico & MicroPython

Updated:February 2, 202513K
Interfacing XBee Module with Raspberry Pi Pico & MicroPython

Interfacing XBee Module with Raspberry Pi Pico & MicroPython

Updated:February 2, 20253K
Modbus RTU with Raspberry Pi Pico & Micropython

Modbus RTU with Raspberry Pi Pico & MicroPython

Updated:February 2, 20258K
Fever Detector with MLX90640 & OpenCV Raspberry Pi

Thermal Fever Detector with MLX90640 & OpenCV Raspberry Pi

Updated:February 2, 20256K
Add A Comment

CommentsCancel reply

Latest Posts
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

May 31, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

May 10, 2026
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

May 2, 2026
A Guide to Sourcing Obsolete ICs for Vintage Projects

Beyond AliExpress: A Guide to Sourcing Obsolete ICs for Vintage Projects

April 21, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

April 27, 2026
Building a Smart Sensor Node with a BLE Microcontroller

Building a Smart Sensor Node with a BLE Microcontroller

February 26, 2026
High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

April 27, 2026
DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

February 1, 2026
Top Posts & Pages
  • How to use INA219 DC Current Sensor Module with Arduino
    How to use INA219 DC Current Sensor Module with Arduino
  • 12V DC to 220V AC Inverter Circuit & PCB
    12V DC to 220V AC Inverter Circuit & PCB
  • Designing of MPPT Solar Charge Controller using Arduino
    Designing of MPPT Solar Charge Controller using Arduino
  • ECG Graph Monitoring with AD8232 ECG Sensor & Arduino
    ECG Graph Monitoring with AD8232 ECG Sensor & Arduino
  • How to use INA226 DC Current Sensor with Arduino
    How to use INA226 DC Current Sensor with Arduino
  • Buck Converter: Basics, Working, Design & Application
    Buck Converter: Basics, Working, Design & Application
  • How to use Modbus RTU with ESP32 to read Sensor Data
    How to use Modbus RTU with ESP32 to read Sensor Data
  • IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
    IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
Categories
  • Arduino Projects (197)
  • Articles (60)
    • Learn Electronics (19)
    • Product Review (15)
    • Tech Articles (28)
  • Electronics Circuits (46)
    • 555 Timer Projects (21)
    • Op-Amp Circuits (7)
    • Power Electronics (13)
  • IoT Projects (204)
    • ESP32 MicroPython (7)
    • ESP32 Projects (81)
    • ESP32-CAM Projects (15)
    • ESP8266 Projects (76)
    • LoRa/LoRaWAN Projects (22)
  • Microcontrollers (38)
    • AMB82-Mini IoT AI Camera (4)
    • BLE Projects (18)
    • STM32 Projects (19)
  • Raspberry Pi (93)
    • Raspberry Pi Pico Projects (57)
    • Raspberry Pi Pico W Projects (12)
    • Raspberry Pi Projects (24)
Follow Us
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • YouTube
About Us

“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.

Copyright © How To Electronics. All rights reserved.
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.