Age prediction of characters in deep learning

insert image description here

1. Age detection

insert image description here
Paper address: The author of the paper "Age and Gender Classification using Convolutional Neural Networks"
proposed a simple network structure similar to AlexNet, which learned a total of 8 age groups:

  1. 0-2
  2. 4-6
  3. 8-12
  4. 15-20
  5. 25-32
  6. 38-43
  7. 48-53
  8. 60-100

Note: These age groups are not continuous.
First of all, it is necessary to understand whether it is suitable to use regression or classification to detect age. Give
a chestnut:

1. Return
insert image description here

2. Classification
insert image description here
Age prediction is based on the appearance of the face. Some people are well maintained and look younger, but the actual age will be different from the measured one. It is difficult for the network model to predict the actual real age without inferring other relevant information. If it is regarded as a regression problem, it is difficult for the model to predict an accurate value of the age in the image, but as a classification problem, predicting an age group is relatively easier to train the model and produces higher accuracy than regression.

2. Thinking method

Automatically identify age steps:

1. Detect the face in the input image or video
2. Extract the facial region of interest (ROI)
3. Use the age detector to predict the age of the person
4. Return the result

For a classifier that detects faces:

Classifier Advantages and disadvantages
Haar Cascade Fast, runs on embedded devices, but low accuracy
HOG + Linear SVM Compared with the Haar cascade, it is more accurate, but the speed is slower, and the detection effect is not good for occlusion and face angle changes
Deep Learning Detector Compared with the above two, the effect is the best, but it needs to consume more computing resources

3. Code implementation

environment:

  • win10
  • pycharm
  • anaconda3
  • python3.7
  • opencv4.2.0

For OpenCV try to use the latest version, you can refer to this simple and quick installation with only one command line: https://blog.csdn.net/y459541195/article/details/104851892

file structure:

insert image description here

3.1 Single image detection code

import numpy as np
import cv2

"""
#图片年龄预测
执行:
python test_age.py 

"""
# 检测年龄段
AGE_LIST = ["(0-2)","(4-6)","(8-12)","(15-20)","(25-32)","(38-43)","(48-53)","(60-100)"]

# 人脸检测模型路径
prototxtPathF ="./models/face_detector/face_deploy.prototxt"
weightsPathF = "./models/face_detector/res10_300x300_ssd_iter_140000.caffemodel"
# 加载人脸模型
faceNet = cv2.dnn.readNet(prototxtPathF,weightsPathF)

# 年龄检测模型
prototxtPathA ="./models/age_detector/age_deploy.prototxt"
weightsPathA = "./models/age_detector/age_net.caffemodel"
#加载模型
ageNet = cv2.dnn.readNet(prototxtPathA,weightsPathA)

#获取图像
image = cv2.imread("./input/test01.jpg")
src = image.copy()
(h,w)= image.shape[:2]

# 构造blob
blob = cv2.dnn.blobFromImage(image,1.0,(300,300),
                             (104,177,123))
# 送入网络计算
faceNet.setInput(blob)
detect = faceNet.forward()
# 检测
for i in range(0,detect.shape[2]):
    confidence = detect[0,0,i,2]
    # 过滤掉小的置信度,计算坐标,提取面部roi,构造面部blob特征
    if confidence > 0.5:
        box = detect[0,0,i,3:7]*np.array([w,h,w,h])
        (startX,startY,endX,endY) = box.astype("int")
        face = image[startY:endY,startX:endX]
        faceBlob = cv2.dnn.blobFromImage(face, 1.0, (227, 227),
                                         (78.4263377603, 87.7689143744, 114.895847746),
                                         swapRB=False)
        # 预测年龄
        ageNet.setInput(faceBlob)
        predictions = ageNet.forward()
        i = predictions[0].argmax()
        age = AGE_LIST[i]
        ageConfidence = predictions[0][i]

        #显示打印
        text = "age{}:{:.2f}%".format(age,ageConfidence*100)
        print(text)

        #绘制显示框
        y = startY - 10 if startY - 10 > 10 else startY + 10
        cv2.rectangle(image, (startX, startY), (endX, endY),
                      (0, 0, 255), 2)
        cv2.putText(image, text, (startX, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

cv2.imshow("Result",image)
cv2.waitKey(0)

3.2 Video stream detection code

import numpy as np
import cv2
import imutils

"""
#视频流年龄预测
执行:
python test_video_age.py 
"""
def detect_age(frame,faceNet,ageNet,minConfidence=0.5):
    # 检测年龄段
    AGE_LIST = ["(0-2)","(4-6)","(8-12)","(15-20)","(25-32)","(38-43)","(48-53)","(60-100)"]
    #定义空列表存放结果
    results = []
    (h,w)= frame.shape[:2]
    # 构造blob
    blob = cv2.dnn.blobFromImage(frame,1.0,(300,300),
                                 (104,177,123))
    # 送入网络计算
    faceNet.setInput(blob)
    detect = faceNet.forward()
    # 检测
    for i in range(0,detect.shape[2]):
        confidence = detect[0,0,i,2]
        # 过滤掉小的置信度,计算坐标,提取面部roi,
        if confidence > minConfidence:
            box = detect[0,0,i,3:7]*np.array([w,h,w,h])
            (startX,startY,endX,endY) = box.astype("int")
            face = frame[startY:endY,startX:endX]
            # 过滤干扰
            if face.shape[0]<20 or face.shape[1]<20:
                continue
            # 构造面部blob特
            faceBlob = cv2.dnn.blobFromImage(face, 1.0, (227, 227),
                                             (78.4263377603, 87.7689143744, 114.895847746),
                                             swapRB=False)
            # 预测年龄
            ageNet.setInput(faceBlob)
            predictions = ageNet.forward()
            i = predictions[0].argmax()
            age = AGE_LIST[i]
            ageConfidence = predictions[0][i]
            # 构造字典存放结果
            dicts = {
    
    
               "location":(startX,startY,endX,endY),
               "age":(age,ageConfidence)
           }
        results.append(dicts)
    return results



# 人脸检测模型路径
prototxtPathF ="./models/face_detector/face_deploy.prototxt"
weightsPathF = "./models/face_detector/res10_300x300_ssd_iter_140000.caffemodel"
# 加载人脸模型
faceNet = cv2.dnn.readNet(prototxtPathF,weightsPathF)

# 年龄检测模型
prototxtPathA ="./models/age_detector/age_deploy.prototxt"
weightsPathA = "./models/age_detector/age_net.caffemodel"
#加载模型
ageNet = cv2.dnn.readNet(prototxtPathA,weightsPathA)

#获取视频图像
videoPath = "./input/test1.mp4"
vs = cv2.VideoCapture(videoPath)

#处理视频流
while True:
    (grabbed,frame) = vs.read()

    # 判断是否结束
    if not grabbed:
        print("无视频读取...")
        break
    frame = imutils.resize(frame,width=720)

    #调用上面函数计算
    results = detect_age(frame,faceNet,ageNet,minConfidence=0.5)
    for  i in results:
        #显示信息
        text = "age{}:{:.2f}%".format(i["age"][0], i["age"][1] * 100)
        (startX,startY,endX,endY) = i["location"]
        # 绘制显示框
        y = startY - 10 if startY - 10 > 10 else startY + 10
        cv2.rectangle(frame, (startX, startY), (endX, endY),
                      (0, 0, 255), 2)
        cv2.putText(frame, text, (startX, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
    # 显示
    cv2.imshow("Result", frame)
    key = cv2.waitKey(1) & 0xFF
    # 按q键退出循环
    if key == ord("q"):
        break
cv2.destroyAllWindows()
vs.release()

4. Test results

4.1 Single image test

Command line input in the virtual environment:

python test_age.py 

Effect one:
insert image description here

Effect two:

insert image description here

Effect three:
insert image description here

4.2 Video stream detection

Age detection in deep learning


Video address: https://www.bilibili.com/video/BV16g4y187iQ/

Reference:
1.https://talhassner.github.io/home/publication/2015_CVPR
2.https://github.com/dpressel/rude-carnie
3.https://github.com/GilLevi/AgeGenderDeepLearning

Guess you like

Origin blog.csdn.net/y459541195/article/details/105611391