Age and Gender Detection Using OpenCV in Python
Last Updated :
17 Apr, 2023
In this article, we will discuss the process of creating an Age and Gender Predictor using OpenCV.
Let’s divide the task into 2 parts:
- Age prediction – The prediction will be in the form of categories where categories are a few age intervals like 0-6,18-25, etc.
- Gender prediction – The prediction is a classifier based where categories are Male and Female.
The approach followed for each task is as follows
The main problems in this project are the quality of the camera, brightness in the room, the background of the person, the boy cut in the case of girls/the long hair of boys.
The solution to this problem is quite simple, instead of predicting an exact image, we will work on the face of the person only. The flowchart below shows the flow of code.
Now that we have clarity of our problem, let’s go ahead and start with the code.
Import Libraries
- Opencv: To Read and process the image which includes resizing, making a face blob, forming a bounding box, etc.
- Matplotlib: To plot the image.
Python3
import cv2
import matplotlib.pyplot as plt
|
Importing Image
To import the image we will be using OpenCV.
Python3
image = cv2.imread( 'image.jpg' )
image = cv2.resize(image, ( 720 , 640 ))
|
Importing Models
To download the below pre-trained models follow this link.
Python3
face1 = "opencv_face_detector.pbtxt"
face2 = "opencv_face_detector_uint8.pb"
age1 = "age_deploy.prototxt"
age2 = "age_net.caffemodel"
gen1 = "gender_deploy.prototxt"
gen2 = "gender_net.caffemodel"
MODEL_MEAN_VALUES = ( 78.4263377603 , 87.7689143744 , 114.895847746 )
face = cv2.dnn.readNet(face2, face1)
age = cv2.dnn.readNet(age2, age1)
gen = cv2.dnn.readNet(gen2, gen1)
|
Defining the categories of age and gender in the list.
Python3
la = [ '(0-2)' , '(4-6)' , '(8-12)' , '(15-20)' ,
'(25-32)' , '(38-43)' , '(48-53)' , '(60-100)' ]
lg = [ 'Male' , 'Female' ]
|
Copying the image so that we can further use it for demonstrating the final output.
Now as we are all set. Let’s start identifying the face blob from the image.
Python3
fr_h = fr_cv.shape[ 0 ]
fr_w = fr_cv.shape[ 1 ]
blob = cv2.dnn.blobFromImage(fr_cv, 1.0 , ( 300 , 300 ),
[ 104 , 117 , 123 ], True , False )
face.setInput(blob)
detections = face.forward()
|
Create the bounding box so that further use it in the output image. (For better understanding)
Python3
faceBoxes = []
for i in range (detections.shape[ 2 ]):
confidence = detections[ 0 , 0 , i, 2 ]
if confidence > 0.7 :
x1 = int (detections[ 0 , 0 , i, 3 ] * fr_w)
y1 = int (detections[ 0 , 0 , i, 4 ] * fr_h)
x2 = int (detections[ 0 , 0 , i, 5 ] * fr_w)
y2 = int (detections[ 0 , 0 , i, 6 ] * fr_h)
faceBoxes.append([x1, y1, x2, y2])
cv2.rectangle(fr_cv, (x1, y1), (x2, y2),
( 0 , 255 , 0 ), int ( round (fr_h / 150 )), 8 )
faceBoxes
|
Output :
[[482, 40, 604, 262]]
Finally, implementing the gender and age detection on the face extracted.
Python3
if not faceBoxes:
print ( "No face detected" )
for faceBox in faceBoxes:
face = fr_cv[ max ( 0 , faceBox[ 1 ] - 15 ):
min (faceBox[ 3 ] + 15 , fr_cv.shape[ 0 ] - 1 ),
max ( 0 , faceBox[ 0 ] - 15 ): min (faceBox[ 2 ] + 15 ,
fr_cv.shape[ 1 ] - 1 )]
blob = cv2.dnn.blobFromImage(
face, 1.0 , ( 227 , 227 ), MODEL_MEAN_VALUES, swapRB = False )
gen.setInput(blob)
genderPreds = gen.forward()
gender = lg[genderPreds[ 0 ].argmax()]
age.setInput(blob)
agePreds = age.forward()
age = la[agePreds[ 0 ].argmax()]
cv2.putText(fr_cv,
f '{gender}, {age}' ,
(faceBox[ 0 ] - 150 , faceBox[ 1 ] + 10 ),
cv2.FONT_HERSHEY_SIMPLEX,
1.3 ,
( 217 , 0 , 0 ),
4 ,
cv2.LINE_AA)
plt.figure(figsize = ( 7 , 7 ))
plt.imshow(fr_cv)
|
Output :
Output Image
More improvement:
We can use another pre-trained model like YOLOv5.
Share your thoughts in the comments
Please Login to comment...