通过dlib获取人脸关键点后怎样截取眼球和嘴巴内部轮廓图
时间: 2024-02-15 15:04:02 浏览: 89
dlib剪切人脸照片
使用 dlib 获取人脸关键点后,可以通过以下步骤截取眼球和嘴巴内部轮廓图:
1. 导入所需库
```
import dlib
import cv2
import numpy as np
```
2. 加载人脸关键点检测器
```
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('path_to_shape_predictor_file')
```
3. 加载图像并检测人脸
```
img = cv2.imread('path_to_image_file')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
```
4. 遍历检测到的人脸
```
for face in faces:
landmarks = predictor(gray, face)
```
5. 获取眼睛和嘴巴的关键点坐标
```
left_eye_pts = np.array([(landmarks.part(36).x, landmarks.part(36).y),
(landmarks.part(37).x, landmarks.part(37).y),
(landmarks.part(38).x, landmarks.part(38).y),
(landmarks.part(39).x, landmarks.part(39).y),
(landmarks.part(40).x, landmarks.part(40).y),
(landmarks.part(41).x, landmarks.part(41).y)], np.int32)
right_eye_pts = np.array([(landmarks.part(42).x, landmarks.part(42).y),
(landmarks.part(43).x, landmarks.part(43).y),
(landmarks.part(44).x, landmarks.part(44).y),
(landmarks.part(45).x, landmarks.part(45).y),
(landmarks.part(46).x, landmarks.part(46).y),
(landmarks.part(47).x, landmarks.part(47).y)], np.int32)
mouth_pts = np.array([(landmarks.part(48).x, landmarks.part(48).y),
(landmarks.part(49).x, landmarks.part(49).y),
(landmarks.part(50).x, landmarks.part(50).y),
(landmarks.part(51).x, landmarks.part(51).y),
(landmarks.part(52).x, landmarks.part(52).y),
(landmarks.part(53).x, landmarks.part(53).y),
(landmarks.part(54).x, landmarks.part(54).y),
(landmarks.part(55).x, landmarks.part(55).y),
(landmarks.part(56).x, landmarks.part(56).y),
(landmarks.part(57).x, landmarks.part(57).y),
(landmarks.part(58).x, landmarks.part(58).y),
(landmarks.part(59).x, landmarks.part(59).y),
(landmarks.part(60).x, landmarks.part(60).y),
(landmarks.part(61).x, landmarks.part(61).y),
(landmarks.part(62).x, landmarks.part(62).y),
(landmarks.part(63).x, landmarks.part(63).y),
(landmarks.part(64).x, landmarks.part(64).y),
(landmarks.part(65).x, landmarks.part(65).y),
(landmarks.part(66).x, landmarks.part(66).y),
(landmarks.part(67).x, landmarks.part(67).y)], np.int32)
```
6. 使用 `cv2.fillPoly` 函数绘制眼睛和嘴巴的内部轮廓
```
eye_mask = np.zeros((img.shape[0], img.shape[1]), np.uint8)
cv2.fillPoly(eye_mask, [left_eye_pts], 255)
cv2.fillPoly(eye_mask, [right_eye_pts], 255)
left_eye = cv2.bitwise_and(gray, gray, mask=eye_mask)
right_eye = cv2.bitwise_and(gray, gray, mask=eye_mask)
mouth_mask = np.zeros((img.shape[0], img.shape[1]), np.uint8)
cv2.fillPoly(mouth_mask, [mouth_pts], 255)
mouth = cv2.bitwise_and(gray, gray, mask=mouth_mask)
```
7. 显示结果
```
cv2.imshow('Left Eye', left_eye)
cv2.imshow('Right Eye', right_eye)
cv2.imshow('Mouth', mouth)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,这只是一个简单的示例代码,您需要根据实际情况进行调整和优化。
阅读全文