使用dlib人脸关键点检测实现摄像头眼球和嘴巴内部轮廓彩色图片的代码
时间: 2024-02-23 17:02:40 浏览: 87
人脸检测功能使用dlib库实现
以下是使用dlib库进行人脸关键点检测,并获取眼球和嘴巴内部轮廓的彩色图片的代码示例:
```python
import cv2
import dlib
import numpy as np
# 加载dlib的人脸检测器和关键点检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 读取摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, frame = cap.read()
if not ret:
break
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 使用dlib的人脸检测器检测人脸
faces = detector(gray)
# 遍历检测到的人脸
for face in faces:
# 使用dlib的关键点检测器检测人脸关键点
landmarks = predictor(gray, face)
# 获取眼球和嘴巴内部轮廓的关键点坐标
left_eye = 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 = 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 = 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)
# 使用关键点坐标绘制眼球和嘴巴内部轮廓的多边形
cv2.fillPoly(frame, [left_eye], (0, 255, 0))
cv2.fillPoly(frame, [right_eye], (0, 255, 0))
cv2.fillPoly(frame, [mouth], (0, 0, 255))
# 显示图像
cv2.imshow('frame', frame)
# 按下q键退出程序
if cv2.waitKey(1) == ord('q'):
break
# 释放摄像头和窗口
cap.release()
cv2.destroyAllWindows()
```
需要注意的是,在运行代码之前,需要先下载dlib的人脸关键点检测器模型文件shape_predictor_68_face_landmarks.dat,并将其放在与代码文件相同的目录下,才能正确运行。
阅读全文