使用Dlib库实现人脸轮廓绘制

目录

一、两个函数

1.连线

2.绘制轮廓

二、代码主体


一、两个函数

1.连线

  • 在画布上连接两个点
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)

2.绘制轮廓

  • 使用凸包函数绘制轮廓
  • convexHull(凸包函数)
def draeConvexHull(start, end):
    # 将指定的点构成一个凸包  多边形
    Facial = shape[start:end + 1]
    mouthHull = cv2.convexHull(Facial)  # 凸包函数  返回轮廓近似点集
    cv2.drawContours(image, [mouthHull], -1, (0, 255, 0), 2)  # 绘制轮廓

二、代码主体

  • 68个人脸关键点检测模型
  • 输入图片,改变大小
  • 构建人脸检测器,检测人脸
  • 构建人脸关键点检测模型
  • 遍历检测出的每张人脸,检测其68个关键点
  • 分别绘制线条与凸包
import numpy as np
import dlib
import cv2


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 draeConvexHull(start, end):
    # 将指定的点构成一个凸包  多边形
    Facial = shape[start:end + 1]
    mouthHull = cv2.convexHull(Facial)  # 凸包函数  返回轮廓近似点集
    cv2.drawContours(image, [mouthHull], -1, (0, 255, 0), 2)  # 绘制轮廓


image = cv2.imread('xzq.png')
image = cv2.resize(image, None, fx=1.5, fy=1.5)

detector = dlib.get_frontal_face_detector()  # 构造人脸检测器
faces = detector(image, 0)
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

for face in faces:
    shape = predictor(image, face)  # 获取关键点
    shape = np.array([[p.x, p.y] for p in shape.parts()])

    draeConvexHull(36, 41)
    draeConvexHull(42, 47)
    draeConvexHull(48, 59)
    draeConvexHull(60, 67)

    drawLine(0, 17)
    drawLine(17, 22)
    drawLine(22, 27)
    drawLine(27, 36)

cv2.imshow('frame', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:

猜你喜欢

转载自blog.csdn.net/weixin_65047977/article/details/143221190