In this tutorial, we are going to quickly go over how you can detect the age and gender of a face using OpenCV. In computer vision, detecting a face is a very important task. In the past, detecting a face required a lot of time and effort, but today we have pre-trained models that can do it in a few seconds. We will be using a pre-trained model in the OpenCV library to detect a face and return a ground truth label. It’s quite a simple model, but it’s a good starting point for beginners.

Required Modules:

OpenCV: It is a tool that specializes in the areas of image processing, video analysis, or computer vision. OpenCV can be used to help developers solve lots of problems in your field when it comes down to analyzing images and videos through sophisticated digital algorithms. The module features techniques that are usually applied when recognizing faces for example. After taking images or videos as input data, the module runs filters that convert them into boolean values so features can be recognized through comparison functions given that they share similar traits. So if you’re looking for an alternative that assists you with this kind of task then OpenCV is an option worth considering! 

The module can be installed using the command in your command prompt/terminal:

pip3 install opencv-python

Required Model files:

To detect the age and gender of a face using OpenCV, one needs a pre-trained model or set of images containing a large number of male and female faces of different ages. In this process, we will be using some simple models. All of these models are not very accurate but we can use these for the tutorial.

  1. Age_deploy.prototxt
  2. Age_net.caffemodel
  3. Gender_deploy.prototxt
  4. Gender_net.caffemodel
  5. Opencv_face_detector.pbtxt
  6. Opencv_face_detector_uint8.pb

Code:

After doing the above steps, we can start writing the code here, will write our parts of the code simultaneously, and discuss in detail what work we’re doing on each line before we move on.

#importing the opencv module
import cv2


# defining a function to create a blob  (blob is the binary long object classification )
def faceBox(faceNet,frame):
    frameHeight=frame.shape[0]
    frameWidth=frame.shape[1]
     #(dnn is the deep neural network it will only work in the latest version of opencv if you are using a version below 3.2 then you won't able to access the dnn in opencv library )
    blob=cv2.dnn.blobFromImage(frame, 1.0, (300,300), [104,117,123], swapRB=False) #inside this dnn present two functionality first one is a blobformimage and the blobformimages
    #setting the import in our blob
    faceNet.setInput(blob)
    #putting the blob into forward method
    detection=faceNet.forward()
    bboxs=[]
    #adding the bounding box
    for i in range(detection.shape[2]):
        confidence=detection[0,0,i,2]
        if confidence>0.7:
            x1=int(detection[0,0,i,3]*frameWidth)
            y1=int(detection[0,0,i,4]*frameHeight)
            x2=int(detection[0,0,i,5]*frameWidth)
            y2=int(detection[0,0,i,6]*frameHeight)
            bboxs.append([x1,y1,x2,y2])
            #creating the rectangle that will show around our face
            cv2.rectangle(frame, (x1,y1),(x2,y2),(0,255,0), 2)
    return frame, bboxs


#added the facemodel and faceproto here with the path of the file
faceProto = "opencv_face_detector.pbtxt"
faceModel = "opencv_face_detector_uint8.pb"

#added the ageProto and ageModel here with the path of the file
ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"

#added the genderProto and genderModel here with the path of the file
genderProto = "gender_deploy.prototxt"
genderModel = "gender_net.caffemodel"

#you can find the models in the source file that you can download at the end of the article




#we created the variable for the detecting our face
faceNet=cv2.dnn.readNet(faceModel, faceProto)
#we created the variable for the detecting our age
ageNet=cv2.dnn.readNet(ageModel,ageProto)
#we created the variable for the detecting our gender
genderNet=cv2.dnn.readNet(genderModel,genderProto)

#adding the mean value
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
#adding the age list range you can collected this age list from google image
ageList = [ '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
genderList = ['Male', 'Female']

#Here we created a video capture object and inside the parameter, it takes an argument so here we used 0 because we are using a laptop camera.
video=cv2.VideoCapture(0)

padding=20

#we created a final window look
while True:
    ret,frame=video.read()
    frame,bboxs=faceBox(faceNet,frame)
    #creating bounding boxs and getting results
    #and loop through all the values from here
    for bbox in bboxs:
        #extracting face from here
        #bbox 1-3 will give us the width and bbox 0-2 will give us height and finally give us the face
        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)]
        #now we need to pop the phase from our blob
        blob=cv2.dnn.blobFromImage(face, 1.0, (227,227), MODEL_MEAN_VALUES, swapRB=False)

        genderNet.setInput(blob)
        genderPred=genderNet.forward()
        gender=genderList[genderPred[0].argmax()]

        ageNet.setInput(blob)
        agePred=ageNet.forward()
        age=ageList[agePred[0].argmax()]
        #argmax is for the maximum value

        label="{},{}".format(gender,age)
        cv2.rectangle(frame,(bbox[0], bbox[1]-30), (bbox[2], bbox[1]), (0,255,0),-1)
        #adding the text for showing age and gender
        cv2.putText(frame, label, (bbox[0], bbox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 1,cv2.LINE_AA)

    #add window name here
    cv2.imshow("age and gender detection",frame)
    k=cv2.waitKey(1)
    if k==ord('q'):
        break
video.release()
cv2.destroyAllWindows()

Output:

Once you’re sure that your code is correct, it’s time to run it. Before you do that, ensure that your webcam is plugged in and then hit enter or run that code. You should see a rectangle around your face with the results in the top right corner of the screen stating your gender and approximate age in words based on what was decided by the machine. The results aren’t completely accurate but you get the gist of how this process works!

Conclusion:

OpenCV (Open Source Computer Vision) is a great package that can help anyone get started with computer vision tasks. It contains a wide range of tools that you can use to do tasks like image segmentation, motion detection, and facial recognition. In this tutorial, we covered how to detect the age and gender of a face using OpenCV. We looked at how to use OpenCV pre-trained models to detect faces, and how to use the data returned about the face to determine the age and gender of the face. The OpenCV models that we used are very basic and not very accurate but they are a good starting point for beginners that are just getting started with computer vision. Let us know if you guys have any questions/comments regarding this process. Happy coding!

You can download the source code from here.

Here are some useful tutorials that you can read: