步骤如下:
- **安装库:**pip install dlib opencv-python
- 导入库
- 加载人脸检测模型
- 加载人脸形状预测模型
- 加载人脸图像
- 使用 dlib 检测人脸
- 使用人脸形状预测模型预测人脸形状
- 分割人脸各个区域
python
import cv2
import dlib
# 加载人脸检测模型
face_detector = dlib.get_frontal_face_detector()
# 加载人脸形状预测模型
shape_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 加载人脸图像
image = cv2.imread("image.jpg")
# 使用 dlib 检测人脸
faces = face_detector(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# 使用人脸形状预测模型预测人脸形状
shapes = []
for face in faces:
shapes.append(shape_predictor(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), face))
# 分割人脸各个区域并计算颜色
for shape in shapes:
# 提取眉毛区域
left_brow_rect = (shape.part(17).x, shape.part(21).y,
shape.part(21).x - shape.part(17).x,
shape.part(21).y - shape.part(17).y)
right_brow_rect = (shape.part(22).x, shape.part(26).y,
shape.part(26).x - shape.part(22).x,
shape.part(26).y - shape.part(22).y)
# 提取眼睛区域
left_eye_rect = (shape.part(36).x, shape.part(42).y,
shape.part(42).x - shape.part(36).x,
shape.part(42).y - shape.part(36).y)
right_eye_rect = (shape.part(45).x, shape.part(51).y,
shape.part(51).x - shape.part(45).x,
shape.part(51).y - shape.part(45).y)
# 提取鼻子区域
nose_rect = (shape.part(27).x, shape.part(35).y,
shape.part(35).x - shape.part(27).x,
shape.part(35).y - shape.part(27).y)
# 提取嘴巴区域
mouth_rect = (shape.part(48).x, shape.part(60).y,
shape.part(60).x - shape.part(48).x,
shape.part(60).y - shape.part(48).y)
# 计算各个区域的颜色
left_brow_color = cv2.mean(image[left_brow_rect])[0]
right_brow_color = cv2.mean(image[right_brow_rect])[0]
left_eye_color = cv2.mean(image[left_eye_rect])[0]
right_eye_color = cv2.mean(image[right_eye_rect])[0]
nose_color = cv2.mean(image[nose_rect])[0]
mouth_color = cv2.mean(image[mouth_rect])[0]
# 打印颜色值
print("Left brow color:", left_brow_color)
print("Right brow color:", right_brow_color)
print("Left eye color:", left_eye_color)
print("Right eye color:", right_eye_color)
print("Nose color:", nose_color)
print("Mouth color:", mouth_color)