python opencv识别人脸年龄性别代码
时间: 2023-09-28 16:08:14 浏览: 124
以下是使用Python OpenCV库进行人脸年龄性别识别的代码示例:
```python
import cv2
import math
# 加载人脸检测器和性别年龄分类器
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
gender_age_detector = cv2.dnn.readNetFromCaffe("deploy_gender.prototxt", "gender_net.caffemodel")
# 定义性别和年龄标签
gender_labels = ["Male", "Female"]
age_labels = ["0-2", "4-6", "8-12", "15-20", "25-32", "38-43", "48-53", "60-"]
# 加载输入图像
img = cv2.imread("image.jpg")
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_detector.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(30, 30))
# 对每个检测到的人脸进行处理
for (x,y,w,h) in faces:
# 提取人脸区域
face_img = img[y:y+h, x:x+w].copy()
# 将人脸区域转换为blob格式
blob = cv2.dnn.blobFromImage(face_img, 1, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
# 输入blob到性别年龄分类器
gender_age_detector.setInput(blob)
predictions = gender_age_detector.forward()
# 解析预测结果
gender_prediction = gender_labels[predictions[0].argmax()]
age_prediction = age_labels[int(math.floor(predictions[1].argmax() / 3.0))]
# 在图像中绘制矩形和标签
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
label = "{}, {}".format(gender_prediction, age_prediction)
cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow("Result", img)
cv2.waitKey(0)
```
注意,在运行此代码之前,你需要下载并提供以下文件:
- haarcascade_frontalface_default.xml:OpenCV的人脸检测器
- deploy_gender.prototxt:性别年龄分类器的网络架构文件
- gender_net.caffemodel:性别年龄分类器的预训练权重文件