年龄识别的python代码
时间: 2023-07-23 13:13:27 浏览: 41
以下是一个简单的年龄识别的 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")
# 定义标签
AGE_LABELS = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
# 加载图像
img = cv2.imread("test.jpg")
# 图像预处理
blob = cv2.dnn.blobFromImage(cv2.resize(img, (227, 227)), 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
# 年龄估计
age_net.setInput(blob)
age_preds = age_net.forward()
age = AGE_LABELS[age_preds[0].argmax()]
# 人脸检测
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
# 绘制人脸和年龄
for rect in rects:
x, y, w, h = rect.left(), rect.top(), rect.width(), rect.height()
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
shape = predictor(gray, rect)
for i in range(68):
cv2.circle(img, (shape.part(i).x, shape.part(i).y), 1, (0, 0, 255), -1)
cv2.putText(img, "Age: " + age, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
# 显示图像
cv2.imshow("Output", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,这只是一个简单的示例代码,并不是最优化的实现。此外,代码中的模型文件和测试图像需要您自己提供。