python opencv预测人脸性别年龄代码
时间: 2023-11-09 20:18:03 浏览: 94
以下是使用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))]
# 打印预测结果
print("Gender prediction: {}".format(gender_prediction))
print("Age prediction: {}".format(age_prediction))
```
注意,在运行此代码之前,你需要下载并提供以下文件:
- haarcascade_frontalface_default.xml:OpenCV的人脸检测器
- deploy_gender.prototxt:性别年龄分类器的网络架构文件
- gender_net.caffemodel:性别年龄分类器的预训练权重文件
阅读全文