python人脸性别年龄识别代码
时间: 2023-07-23 22:12:58 浏览: 212
以下是使用Python编写的基于OpenCV和dlib库的人脸性别年龄识别代码:
```python
import cv2
import dlib
# 加载人脸检测模型和性别年龄识别模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
age_net = cv2.dnn.readNetFromCaffe("deploy_age.prototxt", "age_net.caffemodel")
gender_net = cv2.dnn.readNetFromCaffe("deploy_gender.prototxt", "gender_net.caffemodel")
# 加载输入图片
img = cv2.imread("test.jpg")
# 人脸检测
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 0)
# 遍历每一个检测到的人脸
for face in faces:
# 获取人脸区域
x1, y1, x2, y2 = face.left(), face.top(), face.right(), face.bottom()
# 获取人脸关键点
shape = predictor(gray, face)
# 提取人脸特征
face_roi = img[y1:y2, x1:x2]
blob = cv2.dnn.blobFromImage(face_roi, scalefactor=1.0, size=(227, 227),
mean=(78.4263377603, 87.7689143744, 114.895847746),
swapRB=False, crop=False)
# 进行性别识别
gender_net.setInput(blob)
gender_preds = gender_net.forward()
gender = "Male" if gender_preds[0][0] > gender_preds[0][1] else "Female"
# 进行年龄识别
age_net.setInput(blob)
age_preds = age_net.forward()
age = int(age_preds[0][0] * 100)
# 在图片上绘制性别和年龄信息
cv2.putText(img, "{}, {}".format(gender, age), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 显示结果图片
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`deploy_age.prototxt`和`age_net.caffemodel`是年龄识别模型的配置文件和权重文件,`deploy_gender.prototxt`和`gender_net.caffemodel`是性别识别模型的配置文件和权重文件。需要自行下载和配置。此外,还需要下载`shape_predictor_68_face_landmarks.dat`文件,该文件用于人脸关键点检测。
阅读全文