通过dlib人脸关键点实现嘴巴内部轮廓图提取
时间: 2023-11-03 16:04:15 浏览: 42
可以通过以下步骤使用dlib库提取嘴巴内部轮廓图:
1. 导入dlib库并加载人脸检测器和关键点检测器模型:
```python
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
```
这里需要下载dlib预训练的人脸检测器和关键点检测器模型文件,其中"shape_predictor_68_face_landmarks.dat"是针对68个关键点的检测模型。
2. 加载图片并进行人脸检测和关键点检测:
```python
import cv2
img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
landmarks = predictor(gray, rects[0])
```
这里使用OpenCV库读取图片,将彩色图片转换为灰度图像,然后使用dlib的人脸检测器和关键点检测器模型对图像进行检测。
3. 提取嘴巴内部轮廓点:
```python
mouth_points = []
for i in range(48, 60):
mouth_points.append((landmarks.part(i).x, landmarks.part(i).y))
for i in range(64, 68):
mouth_points.append((landmarks.part(i).x, landmarks.part(i).y))
mask = np.zeros_like(gray)
cv2.fillPoly(mask, [np.array(mouth_points)], 255)
mouth_img = cv2.bitwise_and(gray, mask)
```
这里根据dlib模型中的关键点编号提取嘴巴内部轮廓点,然后使用OpenCV库中的fillPoly()函数将其转化为二值掩膜图像。最后,使用OpenCV库中的bitwise_and()函数将原始灰度图像和掩膜图像进行按位与操作,得到嘴巴内部轮廓图像。
4. 显示结果:
```python
cv2.imshow("Mouth Contour", mouth_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这里使用OpenCV库显示提取的嘴巴内部轮廓图像。
完整代码如下:
```python
import cv2
import dlib
import numpy as np
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)
rects = detector(gray, 0)
landmarks = predictor(gray, rects[0])
mouth_points = []
for i in range(48, 60):
mouth_points.append((landmarks.part(i).x, landmarks.part(i).y))
for i in range(64, 68):
mouth_points.append((landmarks.part(i).x, landmarks.part(i).y))
mask = np.zeros_like(gray)
cv2.fillPoly(mask, [np.array(mouth_points)], 255)
mouth_img = cv2.bitwise_and(gray, mask)
cv2.imshow("Mouth Contour", mouth_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```