《计算机视觉》—— 基于PyCharm中的dlib库实现人脸关键点定位

时间:2024-10-17 07:13:09
import numpy as np import cv2 import dlib # 读取图片 image = cv2.imread('kobe_2.jpg') # 构造人脸检测器 detector = dlib.get_frontal_face_detector() # 检测人脸 faces = detector(image, 0) # dlib.shape_predictor 载入模型(加载预测器) # 可以从 https://github.com/davisking/dlib-models 下载 xmlopencv 自己训练好的特征,dlib人脸关键点的检测模型 predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # 获取每一张脸的关键点(实现检测) for face in faces: shape = predictor(image, face) # 获取关键点 # 将关键点转换为坐标(x,y)的形式 landmarks = np.array([[p.x, p.y] for p in shape.parts()]) # 绘制每一张脸的关键点(绘制shape中的每个点) for idx, point in enumerate(landmarks): pos = [point[0], point[1]] # 当前关键点的坐标 # 针对当前关键点,绘制一个实心圆 cv2.circle(image, pos, 3, color=(0, 255, 0), thickness=-1) # 将每个关键点的索引号写在旁边, 普通大小的等宽字体 线条类型:抗锯齿线条。 cv2.putText(image, str(idx), pos, cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA) # 显示结果 cv2.imshow("result", image) cv2.waitKey(0) # 关闭所有OpenCV创建的窗口 cv2.destroyAllWindows()