计算机视觉40例:案例33绘制关键点案例34勾勒五官轮廓
案例33绘制关键点# 使用dlib进行人脸关键点检测68个特征点## 完整代码pythonimport numpy as npimport cv2import dlib# 读取图像img cv2.imread(people.jpg)# Step 1构造人脸检测器dlib初始化detector dlib.get_frontal_face_detector()# Step 2检测人脸框使用人脸检测器返回检测到的人脸框faces detector(img, 0)# Step 3载入模型加载预测器predictor dlib.shape_predictor(shape_predictor_68_face_landmarks.dat)# Step 4获取每一张脸的关键点实现检测for face in faces:# 获取关键点shape predictor(img, face)# 将关键点转换为坐标(x,y)的形式landmarks np.matrix([[p.x, p.y] for p in shape.parts()])# Step 5绘制每一张脸的关键点绘制shape中的每个点for idx, point in enumerate(landmarks):# 当前关键点的坐标pos (point[0, 0], point[0, 1])# 针对当前关键点绘制一个实心圆cv2.circle(img, pos, 2, color(0, 255, 0), thickness-1)# 字体font cv2.FONT_HERSHEY_SIMPLEX# 利用cv2.putText输出1-68索引序号加1显示时从1开始cv2.putText(img, str(idx 1), pos, font, 0.4, (255, 255, 255), 1, cv2.LINE_AA)# 绘制结果cv2.imshow(img, img)cv2.waitKey()cv2.destroyAllWindows()案例34勾勒五官轮廓python import numpy as np import dlib import cv2 # 模型初始化 shape_predictor shape_predictor_68_face_landmarks.dat #dace_landmark detector dlib.get_frontal_face_detector() predictor dlib.shape_predictor(shape_predictor) # 自定义函数drawLine将指定的点连接起来 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): # 注意凸包用来绘制眼睛、嘴 # 眼睛、嘴也可以用drawLine通过直线绘制 # 但是使用凸包绘制轮廓更方便进行颜色填充等设置 # 获取某个特定五官的点集 Facial shape[start:end] # 针对该五官构造凸包 mouthHull cv2.convexHull(Facial) # 把凸包轮廓绘制出来 cv2.drawContours(image, [mouthHull], -1, (0, 255, 0), 2) # 读取图像 imagecv2.imread(people.jpg) # 色彩空间转换彩色(BGR)--灰度Gray gray cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 获取人脸 faces detector(gray, 0) # 对检测到的rects逐个遍历 for face in faces: # 针对脸部的关键点进行处理构成坐标(x,y)形式 shape np.matrix([[p.x, p.y] for p in predictor(gray, face).parts()]) # 使用函数drawConexHull绘制嘴、眼睛 #获取嘴部的关键点集在整个脸部索引中其索引范围为[48,60],不包含61 drawConvexHull(48,59) # 嘴内部 drawConvexHull(60,68) # 左眼 drawConvexHull(42,48) # 右眼 drawConvexHull(36,42) # 使用函数drawLine绘制脸颊、眉毛、鼻子 # 将shape转换为np.array shapenp.array(shape) # 绘制脸颊把脸颊的各个关键点索引0-16不含17用线条连接起来 drawLine(0,17) # 绘制左眉毛通过将关键点连接实现索引18-21 drawLine(17,22) # 绘制右眉毛索引23-26 drawLine(22,27) # 鼻子索引27-36 drawLine(27,36) cv2.imshow(Frame, image) cv2.waitKey() cv2.destroyAllWindows()