python识别人脸年龄性别代码
时间: 2023-07-23 08:13:07 浏览: 194
以下是使用Python进行人脸性别年龄识别的示例代码,基于face_recognition、dlib和OpenCV库:
```python
import face_recognition
import cv2
# 加载输入图像
image = cv2.imread('test.jpg')
# 检测人脸并进行性别、年龄识别
face_locations = face_recognition.face_locations(image, model='hog')
face_encodings = face_recognition.face_encodings(image, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# 进行性别识别
face_image = image[top:bottom, left:right]
face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
gender_preds = face_recognition.face_gender([face_encoding])
gender = 'Male' if gender_preds[0] > 0.5 else 'Female'
# 进行年龄识别
face_landmarks = face_recognition.face_landmarks(face_image)
if len(face_landmarks) > 0:
left_eye = face_landmarks[0]['left_eye']
right_eye = face_landmarks[0]['right_eye']
eye_center = (left_eye[3][0] + right_eye[0][0]) // 2, (left_eye[3][1] + right_eye[0][1]) // 2
distance = ((left_eye[0][0] - right_eye[3][0]) ** 2 + (left_eye[0][1] - right_eye[3][1]) ** 2) ** 0.5
age_net = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel')
age_blob = cv2.dnn.blobFromImage(face_image, 1, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
age_net.setInput(age_blob)
age_preds = age_net.forward()
age = int(age_preds[0][0] * distance + age_preds[0][1])
# 在图像上绘制人脸框和性别、年龄信息
cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
text = '{}: {}'.format(gender, age)
cv2.putText(image, text, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# 显示结果图像
cv2.imshow('Output', image)
cv2.waitKey(0)
```
需要注意的是,此代码使用了dlib库进行人脸检测和面部特征点标定,使用了face_recognition库进行人脸识别和性别识别,使用了OpenCV的dnn模块进行年龄识别。此外,还需要下载并加载年龄分类器的模型文件(deploy_age.prototxt、age_net.caffemodel)。
阅读全文