python opencv 人脸识别性别年龄代码
时间: 2023-10-18 22:29:28 浏览: 179
以下是一个基于Python和OpenCV的人脸识别代码,可以实现对人脸的性别和年龄识别:
```python
import cv2
import math
# 加载Haar特征分类器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 初始化人脸性别和年龄识别模型
gender_net = cv2.dnn.readNetFromCaffe('deploy_gender.prototxt', 'gender_net.caffemodel')
age_net = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel')
# 定义性别和年龄标签
gender_list = ['Male', 'Female']
age_list = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
# 初始化摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头捕获的帧
ret, frame = cap.read()
# 转换成灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 绘制人脸矩形框,并进行性别和年龄识别
for (x, y, w, h) in faces:
# 绘制人脸矩形框
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
# 根据人脸大小调整图像大小
face = cv2.resize(gray[y:y + h, x:x + w], (227, 227))
# 进行性别识别
gender_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
gender_net.setInput(gender_blob)
gender_preds = gender_net.forward()
gender = gender_list[gender_preds[0].argmax()]
# 进行年龄识别
age_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
age_net.setInput(age_blob)
age_preds = age_net.forward()
age = age_list[age_preds[0].argmax()]
# 在人脸矩形框下方绘制性别和年龄信息
cv2.putText(frame, "Gender: " + gender, (x, y + h + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.putText(frame, "Age: " + age, (x, y + h + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# 显示帧
cv2.imshow('frame', frame)
# 按'q'键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
```
其中,`deploy_gender.prototxt`和`gender_net.caffemodel`是用于性别识别的深度学习模型文件;`deploy_age.prototxt`和`age_net.caffemodel`是用于年龄识别的深度学习模型文件。在代码中,我们使用`cv2.dnn.readNetFromCaffe()`函数读取模型文件,并使用`cv2.dnn.blobFromImage()`函数将人脸图像转换成网络所需的格式。最后,根据网络输出的预测结果,确定性别和年龄标签,并在图像上显示出来。
阅读全文