一、项目介绍:

通过摄像头实时识别人物的年龄和性别


二、环境安装

  • 平台:windows 10
  • 编译器:pycharm
  • cuda 11.3
  • cudnn 8.2.0.53
conda create -n ageandsex python=3.8
conda activate ageandsex
pip install opencv-python

三、执行代码

执行age&sex.py文件

四、核心代码

import cv2
import numpy as np

# 定义年龄和性别的标签
age_labels = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
gender_labels = ['Male', 'Female']

# 网络模型    预训练模型
faceProto = "age_gender/opencv_face_detector.pbtxt"
faceModel = "age_gender/opencv_face_detector_uint8.pb"

ageProto = "age_gender/age_deploy.prototxt"
ageModel = "age_gender/age_net.caffemodel"

genderProto = "age_gender/gender_deploy.prototxt"
genderModel = "age_gender/gender_net.caffemodel"

# 加载年龄和性别模型
ageNet = cv2.dnn.readNet(ageModel, ageProto)
genderNet = cv2.dnn.readNet(genderModel, genderProto)

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()

    # 获取图像的高度和宽度
    h, w = frame.shape[:2]

    # 从图像中构建一个blob用于年龄和性别识别
    blob = cv2.dnn.blobFromImage(frame, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)

    # 年龄识别
    ageNet.setInput(blob)
    agePreds = ageNet.forward()
    age = age_labels[np.argmax(agePreds)]

    # 性别识别
    genderNet.setInput(blob)
    genderPreds = genderNet.forward()
    gender = gender_labels[np.argmax(genderPreds)]

    # 在图像上绘制年龄和性别信息
    info = f'Age: {age}, Gender: {gender}'
    cv2.putText(frame, info, (10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

    # 显示结果
    cv2.imshow('Age and Gender Detection', frame)

    # 检测按键q是否被按下如果是则退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头和关闭窗口
cap.release()
cv2.destroyAllWindows()
资源下载
免费资源
链接点击下载(提取码: ab8i)复制