《计算机视觉》—— 基于dlib库的人脸关键部位的轮廓检测
def drawLine(start, end):
pts = shape[start: end]
for l in range(1, len(pts)):
ptA = tuple(pts[l - 1])
ptB = tuple(pts[l])
cv2.line(image, ptA, ptB, (0, 255, 0), 2)
def drawConvexHull(start, end):
Facial = shape[start: end + 1]
mouthHull = cv2.convexHull(Facial)
cv2.drawContours(image, [mouthHull], -1, (0, 255, 0), 2)
cap = cv2.VideoCapture(0) # 0-->打开电脑自带的摄像头, 1-->打开电脑外接的摄像头
detector = dlib.get_frontal_face_detector() # 构造脸部位置检测器
# 获取人脸关键点定位模型
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
if not cap.isOpened(): # 判断摄像头是否正常打开
print("Cannot open camera")
exit()
while True: # 若正常打开摄像头则对摄像头拍摄的每一帧画面进行循环处理
ret, image = cap.read() # 如果正确读取一帧图像,ret为True, image-->读取的画面
image = cv2.flip(image, 1) # 图片翻转,水平翻转(镜像)
# 如果没有正确读取到图像,则退出循环
if not ret:
print("不能读取摄像头")
break
faces = detector(image, 0) # 检测人脸方框位置
for face in faces: # 对获取到得到 faces ,逐个遍历
shape = predictor(image, face) # 获取关键点
# 将关键点转换为坐标(x, y)的形式
shape = np.array([[p.x, p.y] for p in shape.parts()])
drawConvexHull(36, 41) # 绘制右眼凸包
drawConvexHull(42, 47) # 绘制左眼凸包
drawConvexHull(48, 59) # 绘制最外部凸包
drawConvexHull(60, 67) # 绘制嘴内部凸包
drawLine(0, 17) # 绘制脸颊点线
drawLine(17, 22) # 绘制左眉毛点线
drawLine(22, 27) # 绘制右眉毛点线
drawLine(27, 36) # 绘制鼻子点线
cv2.imshow("Frame", image)
# 检查是否按下ESC键(ASCII码27),如果按下则退出循环
if cv2.waitKey(10) == 27:
break
# 释放摄像头资源
cap.release()
# 关闭所有OpenCV创建的窗口
cv2.destroyAllWindows()