python-opencv 人脸68点特征点检测

python-opencv 人脸68点特征点检测

不是很难,主要还是掉包,来看一下代码啊:

# coding: utf-8
# 导包
import numpy as np
import dlib
import cv2


class face_emotion(object):
    def __init__(self):
        # 人脸检测器对象,通过它拿到人脸矩形框坐标
        self.detector = dlib.get_frontal_face_detector()

        # 加载预训练模型,创建 人脸关键点检测器 对象
        self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

        # 创建 cv2 视频捕捉对象 or 摄像头对象
        # 将视频流从默认的摄像头(设备索引0)读取到内存中
        # 0 是设备索引号,可以替换为其他设备 1、2。。。
        # ls /dev/video* 查看设备号
        self.cap = cv2.VideoCapture(0)

    def feature_point_detection(self):
        # 循环读取视频帧 or 图像
        if True:
            # 读入 1 帧视频
            # flag:一个布尔值,指示是否成功读取到了视频帧
            # img:一个 numpy 数组,存储了图像的像素值,(0-255)
            # flag, img = self.cap.read()

            # 读入 1 张图像
            img = cv2.imread("image/beauty.png")

            # 取灰度
            # gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

            # 使用人脸检测器检测人脸,返回 faces 矩形框坐标数据
            faces = self.detector(img, 0)
            print(faces)
            # exit()

            # 如果检测到人脸
            if faces:
                # 对每张人脸都标出 68 个特征点
                # for i in range(len(faces)):
                for k, d in enumerate(faces):
                    shape = self.predictor(img, d)
                    print(shape)
                    # 用圆圈标识每个特征点,(shape.part(i).x, shape.part(i).y) 每个特征点的坐标
                    for i in range(68):
                        index = str(i)
                       
                        cv2.putText(
                            img,
                            index,
                            (shape.part(i).x, shape.part(i).y),  # 左下角
                            cv2.FONT_HERSHEY_SIMPLEX,
                            0.4,  # 0.4:表示文本的缩放因子,可以调整文本的大小
                            (255, 0, 0)
                        )

            # 窗口显示
            cv2.imshow("img", img)
            

            # cv2.waitKey(1) 监听键盘输入,0xFF == 27 键盘 ESC 键值 27
            if cv2.waitKey(0) & 0xFF == 27:
                cv2.destroyAllWindows()

        # 释放摄像头
    #    self.cap.release()

        # 删除建立的窗口
        


if __name__ == "__main__":
    my_face = face_emotion()
    my_face.feature_point_detection()

运行结果如下:
运行

猜你喜欢

转载自blog.csdn.net/weixin_43327597/article/details/134624635