Gender Prediction And Age Detection In Images Using OpenCV
Introduction
Facial analysis from photos has sparked a lot of attention since it can help with a variety of issues, including better customer ad targeting, better content recommendation systems, security surveillance, and other areas.
Age and gender are significant aspects of face characteristics, and determining them is a prerequisite for such activities. Many businesses use these technologies for a variety of reasons, including making it easier to work with clients, better adapt to their needs, and provide a positive experience. The gender and age of people make it easier to recognise and predict their requirements.
Even for us humans, detecting gender and age from an image is difficult because it is entirely based on appearances, which can be difficult to anticipate at times. People of the same age can appear significantly differently than we might expect.
Application
In the subject of surveillance computer vision, age and gender prediction are frequently used. Advances in computer vision have made this prediction much more practical and accessible to the general public. Because of its utility in intelligent real-world applications, this study topic has seen significant advancements.
A person’s identity, age, gender, emotions, and ethnicity are all determined by the traits on their face. Age and gender classification are two of these features that can be particularly useful in a variety of real-world applications, including
- Security and video surveillance
- Human-computer interaction
- Biometrics
- Entertainment
And many more.
Implementation
Now lets learn how to use the OpenCV library in Python to determine age and gender using a camera or picture input.
Framework used is Caffe for creation of model using prototype file.
Let’s get this party started. Make sure you have OpenCV installed if you don’t already have it.
$ pip install opencv-python numpy
Step 1: Importing libraries
# Import required modules
import cv2 as cv
import math
import time
from google.colab.patches import cv2_imshow
Step 2: Finding bounding box coordinates in Frame
Using below user defined function we get the coordinates for bounding boxes or we can say location of face in image
def getFaceBox(net, frame, conf_threshold=0.7):
frameOpencvDnn = frame.copy()
frameHeight = frameOpencvDnn.shape[0]
frameWidth = frameOpencvDnn.shape[1]
blob = cv.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False) net.setInput(blob)
detections = net.forward()
bboxes = []
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)
bboxes.append([x1, y1, x2, y2])
cv.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight/150)), 8)
return frameOpencvDnn, bboxes
Step 3: Loading model and weight files
The following files must be included in the project directory:
gender_net.caffemodel
: Pre-trained model weights for gender detection.deploy_gender.prototxt
: Model architecture for the gender detection model .age_net.caffemodel
:Pre-trained model weights for age detection.deploy_age.prototxt
:Model architecture for the age detection model.res10_300x300_ssd_iter_140000_fp16.caffemodel
: Pre-trained model weights for face detection.deploy.prototxt.txt
: Model architecture for the face detection model.- All You Can Download from HERE(Credit).
We have a.pb file for face detection, which is a protobuf file (protocol buffer) that contains the graph definition and training weights of the model. This is what we’ll use to execute the trained model. While a.pb file contains the protobuf in binary format, a.pbtxt file has it in text format. TensorFlow files are included. The.prototxt files provide the network configuration for age and gender, whereas the.caffemodel file defines the internal states of the layers’ parameters.
Then, for face, age, and gender detection models, define the weights and architectures variables
faceProto = "/content/opencv_face_detector.pbtxt"
faceModel = "/content/opencv_face_detector_uint8.pb"
ageProto = "/content/age_deploy.prototxt"
ageModel = "/content/age_net.caffemodel"
genderProto = "/content/gender_deploy.prototxt"
genderModel = "/content/gender_net.caffemodel"
Step 4: Mentioning age and gender category list
Set up the model’s mean values and the lists of age groups and genders to categorise from.
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']
Step 5: Function to predict gender and age
To load the networks, use the readNet() method. The first parameter is used to store training weights, while the second is used to save network configuration.
# Load networkageNet = cv.dnn.readNet(ageModel, ageProto)
genderNet = cv.dnn.readNet(genderModel, genderProto)
faceNet = cv.dnn.readNet(faceModel, faceProto)
Step 6: Function Which predict gender and age
Below user defined function is pipline or we can say implementation of main workflow in which image goes to function to get loaction and further for prediction of age range and gender
def age_gender_detector(frame):
# Read frame
t = time.time()
frameFace, bboxes = getFaceBox(faceNet, frame)
for bbox in bboxes:
# print(bbox)
face = frame[max(0,bbox[1]-padding):min(bbox[3]+padding,frame.shape[0]-1),max(0,bbox[0]-padding):min(bbox[2]+padding, frame.shape[1]-1)]blob = cv.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
genderNet.setInput(blob)
genderPreds = genderNet.forward()
gender = genderList[genderPreds[0].argmax()]
# print("Gender Output : {}".format(genderPreds))
print("Gender : {}, conf = {:.3f}".format(gender, genderPreds[0].max()))ageNet.setInput(blob)
agePreds = ageNet.forward()
age = ageList[agePreds[0].argmax()]
print("Age Output : {}".format(agePreds))
print("Age : {}, conf = {:.3f}".format(age, agePreds[0].max()))label = "{},{}".format(gender, age)
cv.putText(frameFace, label, (bbox[0], bbox[1]-10), cv.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2, cv.LINE_AA)
return frameFace
Step 7: Prediction
from google.colab import files
uploaded = files.upload()
input = cv.imread("2.jpg")
output = age_gender_detector(input)
cv2_imshow(output)
Here, we can see the confidence of prediction for gender is 1(100%) and for age is somehow less because its hard to be accurate
In this blog, We have learned how to create an Age predictor that can also detect your face and highlight it with the border.