python代码:对采集的图像进行人脸检测,并使用方位检测算法检测人脸的朝向
时间: 2024-05-10 10:21:25 浏览: 8
以下是一个使用OpenCV库和dlib库检测人脸并检测人脸方向的Python代码:
```
import cv2
import dlib
# 加载dlib库中的人脸检测器和方向检测器模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 加载图像
img = cv2.imread("test.jpg")
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用人脸检测器检测图像中的人脸
faces = detector(gray)
# 遍历检测到的人脸
for face in faces:
# 使用方向检测器检测人脸的方向
shape = predictor(gray, face)
# 获取人脸关键点
landmarks = shape.parts()
# 计算人脸方向角度
angle = dlib.get_face_chin_angle(landmarks)
# 打印人脸方向角度
print("Face direction angle:", angle)
# 在图像中绘制人脸区域和方向角度
cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)
cv2.putText(img, "Angle: {:.2f}".format(angle), (face.left(), face.top() - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示图像
cv2.imshow("Face detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注:在运行代码之前,需要先下载dlib库中的人脸检测器和方向检测器模型文件,并将其放置在同一目录下。```shape_predictor_68_face_landmarks.dat```可以在dlib的官方网站上下载。