Predict Age using Convolutional Neural Network in Python

In this tutorial program, we will learn about building Age Predictor using machine learning with the language used is Python. So here I am going to discuss what are the basic steps of this machine learning problem and how to approach it.

We will use computer vision library that is openCV and Convolutional Neural Network in Python.

We are going to add an effect to the image in order to predict age. We will use the below two steps:

  1. Loading of the image and Specifying the parameters.
  2. Detection of a face with Region Of Index(ROI).
  3. Age Prediction.
  4. Final Output with Confidence.

Python Libraries to import

The basic libraries are Numpy and Pandas. Along with them, we have OpenCV library cv2 used in computer vision libraries.

import numpy as np
import pandas as pd
import cv2
import os

Loading of the image

Image loading is needed as images are first detected for face to form bounding boxes.

We are going to specify different parameters for the loaded image to give desired results.

#loading image for age detection
pathtxt = os.path.sep.join([args["face"])
weightsPath = os.path.sep.join([args["age"],
ageNet = cv2.dnn.readNet(pathtxt, weightsPath)
tet_img = os.path.join(paths, "test.jpg")

Detection of Face and Region Of Index(ROI)

In an image, we need to form the coordinates to use parameters like confidence.

Confidence will give the probability of the image falling in the age brackets.

We are going to divide the age into ranges as predicting exact age is difficult as depends on many features of the human face.

#using image to load other parameters
with open('alb_labels.json', 'r') as f:
    data = json.load(d)

data = []
with open('alb_labels.json') as f:
    for line in f:

#passing image through blob for passing filters
imag = cv2.imread(args["img"])
(h, w) = img.shape[:4]
blobs = cv2.dnn.blobFromImage(image, 2.0, (600, 600),
  (154.0, 197.0, 83.0))

Age Prediction with neural network – Python

We are going to take the average, maximum and minimum values of the confidence values.

Take the bounding box coordinates for the face formation image with confidence values.

We are going to use this pre-trained neural network model in giving predictions.

#passing values
x = preds[0].argmax()
y = preds[1].argmin()
z = preds[2].argavg()
a = preds[3].arg()

file2 = os.path.join(paths, "1.jpg")
img_ppl = cv2.imread(file2, 0)
print(img_ppl.shape, img_ppl.size, img_ppl.dtype)

#bounding box final image formation
template = img_ppl[180:130, 950:800]
preds = ageNet.backward()
cv2.imshow('img', template)

img1 = img
b, e = shape[::-1]
ageConfidence = preds[0][i]


Final Predictions

We are going to predict the age range with confidence values.

The Final Output:

	 Predict Age using Convolutional Neural Network in Python

Leave a Reply

Your email address will not be published. Required fields are marked *