python opencv人脸性别年龄识别代码
时间: 2023-09-28 10:08:14 浏览: 163
以下是一个基于OpenCV和深度学习的人脸性别年龄识别代码示例:
```python
import cv2
import math
import argparse
# 加载模型文件
face_caffe_model = "deploy.prototxt"
face_caffe_weight = "res10_300x300_ssd_iter_140000.caffemodel"
gender_caffe_model = "gender_net.caffemodel"
gender_caffe_weight = "gender_deploy.prototxt"
age_caffe_model = "age_net.caffemodel"
age_caffe_weight = "age_deploy.prototxt"
# 定义性别和年龄标签
gender_labels = ['Male', 'Female']
age_labels = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
# 加载人脸检测模型和性别、年龄识别模型
face_net = cv2.dnn.readNetFromCaffe(face_caffe_model, face_caffe_weight)
gender_net = cv2.dnn.readNetFromCaffe(gender_caffe_model, gender_caffe_weight)
age_net = cv2.dnn.readNetFromCaffe(age_caffe_model, age_caffe_weight)
# 处理人脸图像
def process_face_image(image):
# 提取图像大小
(h, w) = image.shape[:2]
# 构建人脸检测的输入blob
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
(300, 300), (104.0, 177.0, 123.0))
# 通过人脸检测网络检测人脸
face_net.setInput(blob)
detections = face_net.forward()
# 遍历检测结果
for i in range(0, detections.shape[2]):
# 提取置信度
confidence = detections[0, 0, i, 2]
# 过滤掉低置信度的检测结果
if confidence > 0.5:
# 计算人脸位置坐标
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# 提取人脸ROI区域
face = image[startY:endY, startX:endX]
# 构建性别和年龄检测的输入blob
face_blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227),
(78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
# 通过性别和年龄检测网络进行性别和年龄识别
gender_net.setInput(face_blob)
gender_preds = gender_net.forward()
age_net.setInput(face_blob)
age_preds = age_net.forward()
# 提取性别和年龄标签
gender_label = gender_labels[gender_preds[0].argmax()]
age_label = age_labels[age_preds[0].argmax()]
# 计算年龄和性别的置信度
gender_confidence = gender_preds[0].max()
age_confidence = age_preds[0].max()
# 在图像中绘制人脸框、性别和年龄标签
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
label = "{}, {:.2f}%".format(gender_label, gender_confidence * 100)
cv2.putText(image, label, (startX, startY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
label = "{}, {:.2f}%".format(age_label, age_confidence * 100)
cv2.putText(image, label, (startX, startY + (endY - startY) + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
return image
# 主函数
if __name__ == '__main__':
# 解析命令行参数
parser = argparse.ArgumentParser()
parser.add_argument('--image', required=True, help='path to input image')
args = parser.parse_args()
# 加载输入图像
image = cv2.imread(args.image)
# 处理人脸图像并显示结果
result = process_face_image(image)
cv2.imshow("Output", result)
cv2.waitKey(0)
```
注意:在运行代码之前,你需要下载相应的模型文件并将其放置在正确的路径下,才能正常运行代码。
阅读全文