以上代码并没有直接计算人脸的长宽,而是通过计算眼睛和嘴巴之间的距离来估计人脸大小。如果需要计算人脸的长宽,可以在检测到人脸后,使用`face.right() - face.left()`和`face.bottom() - face.top()`来分别计算人脸的宽度和高度。例如:
```python
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
img = cv2.imread('test.jpg')
faces = detector(img)
for face in faces:
landmarks = predictor(img, face)
eye_dist = landmarks.part(45).x - landmarks.part(36).x
mouth_dist = landmarks.part(54).x - landmarks.part(48).x
face_size = eye_dist + mouth_dist
# 计算人脸的长宽
face_width = face.right() - face.left()
face_height = face.bottom() - face.top()
cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 2)
for i in range(68):
cv2.circle(img, (landmarks.part(i).x, landmarks.part(i).y), 2, (0, 0, 255), -1)
cv2.putText(img, f"Face size: {face_size}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.putText(img, f"Face width: {face_width}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.putText(img, f"Face height: {face_height}", (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们计算了人