HomePROJECTSAge and Gender Detection Python project with source code

Age and Gender Detection Python project with source code

Introduction to Age and Gender Detection – The task of detecting age and gender, however, is an inherently difficult problem, more so than many other computer vision tasks. The main reason for this difficulty gap lies in the data required to train these types of systems.

While general object detection tasks can often have access to hundreds of thousands or even millions of images for training, datasets with age and/or gender labels are considerably smaller, usually in the thousands or, at best, tens of thousands.

The reason is that to have tags for such images, we need to access the personal information of the subjects in the images. Namely, we would need their date of birth and gender, and in particular date of birth is infrequently published information.

Namely, we would need their date of birth and gender, and in particular date of birth is infrequently published information. Therefore, we have to settle for the nature of this problem that we are addressing and adapt network architectures and algorithmic approaches to deal with these limitations.

Age and Gender Detection with Python
The areas of classification by age and sex have been studied for decades. Various approaches have been taken over the years to tackle this problem, with varying levels of success. Now let’s start with the task of detecting age and gender using the Python programming language.

I will present the problem of gender detection as a classification problem and the age detection problem as a regression problem. However, estimating age accurately using regression is difficult. Even humans cannot accurately predict an age by looking at a person. However, we do know if they are in their 30s or 40s. This is also what I’m going to follow using Python.

Getting Started:
Now let’s get started with the task of Age and Gender detection using the Python programming language. I will first start with writing the code for detecting faces because without face detection we will not be able to move further with the task of age and gender prediction.

You can download the necessary OpenCV pre-trained models that you will need in the task of age and gender detection from here. Now after importing the OpenCV module in your python file you can get started with the code below.

Python code for Face Detection:

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)

    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

Now the next step is to predict the gender of humans in the image. Here I will load the gender network into memory and transmit the detected face across the network for the gender detection task.

Python code for Gender Detection:

genderProto = "gender_deploy.prototxt"
genderModel = "gender_net.caffemodel"
ageNet = cv.dnn.readNet(ageModel, ageProto)

genderList = ['Male', 'Female']

blob = cv.dnn.blobFromImage(face, 1, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
genderPreds = genderNet.forward()
gender = genderList[genderPreds[0].argmax()]
print("Gender Output : {}".format(genderPreds))
print("Gender : {}".format(gender))

Python code for age detection

ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"
ageNet = cv.dnn.readNet(ageModel, ageProto)

ageList = ['(0 - 2)', '(4 - 6)', '(8 - 12)', '(15 - 20)', '(25 - 32)', '(38 - 43)', '(48 - 53)', '(60 - 100)']

agePreds = ageNet.forward()
age = ageList[agePreds[0].argmax()]
print("Gender Output : {}".format(agePreds))
print("Gender : {}".format(age))

Now the next task is to predict the age of the human in the image. Here I will load the ageing network and use the forward pass to get the output. Since the network architecture is similar to that of the Gender Network, we can make the most of all outputs to get the intended age group for the task to detect age.

display output

label = "{}, {}".format(gender, age)
cv.putText(frameFace, label, (bbox[0], bbox[1]-20), cv.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 3, cv.LINE_AA)
cv.imshow("Age Gender Demo", frameFace)

NOTE – In order to run the project of Python, you have to download Python IDLE or Pycharam. In the video I have explained how to download and install it.

Download and Install Python

Download and install Pycharm


Additional Reading


If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

Thank you 🙂 Keep Learning !



Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

- Advertisment -