opencv人脸性别年龄识别代码
时间: 2023-07-30 21:04:28 浏览: 105
以下是使用OpenCV进行人脸性别年龄识别的Python代码示例:
```python
import cv2
# 加载人脸检测器和性别、年龄分类器
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gender_classifier = cv2.dnn.readNetFromCaffe('deploy_gender.prototxt', 'gender_net.caffemodel')
age_classifier = cv2.dnn.readNetFromCaffe('deploy_age.prototxt', 'age_net.caffemodel')
# 加载输入图像并进行预处理
image = cv2.imread('test.jpg')
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
# 检测人脸并进行性别、年龄识别
face_rects = face_detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in face_rects:
# 提取人脸ROI并进行预处理
face_roi = image[y:y+h, x:x+w]
face_blob = cv2.dnn.blobFromImage(cv2.resize(face_roi, (227, 227)), 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746))
# 进行性别识别
gender_classifier.setInput(face_blob)
gender_preds = gender_classifier.forward()
gender = 'Male' if gender_preds[0][0] > gender_preds[0][1] else 'Female'
# 进行年龄识别
age_classifier.setInput(face_blob)
age_preds = age_classifier.forward()
age = int(age_preds[0][0] * 100)
# 在图像上绘制人脸框和性别、年龄信息
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = '{}: {}'.format(gender, age)
cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# 显示结果图像
cv2.imshow('Output', image)
cv2.waitKey(0)
```
需要注意的是,这段代码使用了OpenCV的dnn模块进行深度学习推理,因此需要安装OpenCV的contrib模块。此外,还需要下载并加载性别、年龄分类器的模型文件(deploy_gender.prototxt、gender_net.caffemodel、deploy_age.prototxt、age_net.caffemodel)。
阅读全文