首页
/ 【亲测免费】 Gender-and-Age-Detection 项目使用教程

【亲测免费】 Gender-and-Age-Detection 项目使用教程

2026-01-17 08:43:27作者:齐添朝

1. 项目的目录结构及介绍

Gender-and-Age-Detection/
├── LICENSE
├── README.md
├── _config.yml
├── age_deploy.prototxt
├── age_net.caffemodel
├── detect.py
├── gender_deploy.prototxt
├── gender_net.caffemodel
├── girl1.jpg
├── girl2.jpg
├── kid1.jpg
├── kid2.jpg
├── man1.jpg
├── man2.jpg
├── opencv_face_detector.pbtxt
├── opencv_face_detector_uint8.pb
└── woman1.jpg

目录结构说明

  • LICENSE: 项目许可证文件。
  • README.md: 项目说明文档。
  • _config.yml: 项目配置文件。
  • age_deploy.prototxt: 年龄检测模型的配置文件。
  • age_net.caffemodel: 年龄检测模型的权重文件。
  • detect.py: 项目的主启动文件,用于检测性别和年龄。
  • gender_deploy.prototxt: 性别检测模型的配置文件。
  • gender_net.caffemodel: 性别检测模型的权重文件。
  • girl1.jpg, girl2.jpg, kid1.jpg, kid2.jpg, man1.jpg, man2.jpg, woman1.jpg: 示例图片文件。
  • opencv_face_detector.pbtxt: 人脸检测模型的配置文件。
  • opencv_face_detector_uint8.pb: 人脸检测模型的权重文件。

2. 项目的启动文件介绍

detect.py

detect.py 是项目的主启动文件,用于检测图片或摄像头中人脸的性别和年龄。以下是该文件的主要功能和使用方法:

import cv2
import numpy as np
import argparse

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--image')
    args = parser.parse_args()
    return args

def main():
    args = get_args()
    image_path = args.image

    # 加载模型和配置文件
    age_net = cv2.dnn.readNetFromCaffe('age_deploy.prototxt', 'age_net.caffemodel')
    gender_net = cv2.dnn.readNetFromCaffe('gender_deploy.prototxt', 'gender_net.caffemodel')
    face_net = cv2.dnn.readNetFromCaffe('opencv_face_detector.pbtxt', 'opencv_face_detector_uint8.pb')

    # 读取图片
    frame = cv2.imread(image_path)

    # 检测人脸
    blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], True, False)
    face_net.setInput(blob)
    detections = face_net.forward()

    # 处理检测结果
    for i in range(detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence > 0.7:
            box = detections[0, 0, i, 3:7] * np.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])
            (x, y, x1, y1) = box.astype("int")
            face = frame[y:y1, x:x1]

            # 检测性别
            blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), [78.4263377603, 87.7689143744, 114.895847746], swapRB=False)
            gender_net.setInput(blob)
            gender_preds = gender_net.forward()
            gender = gender_list[gender_preds[0].argmax()]

            # 检测年龄
登录后查看全文
热门项目推荐
相关项目推荐