Python3+opencv3+dlib 使用摄像头实时提取人脸68个关键点

正文是解释,若懒得看解释就直接到最下方找完整代码
如果需要dlib库的5点或者68点的dat文件,可在下方blog下载

https://blog.csdn.net/Mimido_luoluo/article/details/107774321

使用dlib库可以实现对人脸68个关键点进行标定,还可以搞5个点的标定,只需更换dat文件即可

首先需要引用dat文件、加载检测器预测器:
dlib.get_frontal_face_detector()可以获取人脸检测器
dlib.shape_predictor(dat文件路径)可以配上检测使用的dat文件

predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)

之后需要打开摄像头:

captureframe = cv2.VideoCapture(0)

注意:部分电脑可能会有terminating async callback之类的报错,可以用下面代码解决,即后方加一个cv2.CAP_DSHOW

captureframe = cv2.VideoCapture(0 , cv2.CAP_DSHOW)

接下来便是主循环,对摄像头获取图片逐帧处理
使用 while(1) 实现
在while(1)内:
首先获取一帧图片并且转换为灰度图
前面 ReturnValue 是返回 Bool 值,用以表示图片是否读取正确,本程序中用处不大;后者 frame 才是返回的图片值
转化灰度图用 cvtColor,你懂得

ReturnValue, frame = captureframe.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

检测灰度图片的人脸位置返回给 rects
返回的是人脸所在的区域即rectangles的坐标的首元素地址,如下图在这里插入图片描述

rects = detector(gray,1)

之后需要遍历 rects 元素,即所有的人脸,对每一个人脸检测68个特征点,并保存坐标到 landmarks

for i in range(len(rects)):
            landmarks = np.matrix([[p.x,p.y] for p in predictor(gray,rects[i]).parts()])

下一步对提取到的点进行遍历,并在原来的彩色图画点

for idx,point in enumerate(landmarks):
	pos=(point[0,0],point[0,1])
	points_keys.append([point[0,0],point[0,1]])
	cv2.circle(frame,pos,2,(255,0,0),-1)

最后显示图片并进行短暂延迟:

cv2.imshow('frame',frame)
cv2.waitKey(5)

完整代码:

import dlib
import numpy as np
import cv2


predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
points_keys = []

captureframe = cv2.VideoCapture(0 , cv2.CAP_DSHOW)
while(1):
        ReturnValue, frame = captureframe.read()
        gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        
        rects = detector(gray,1)
        for i in range(len(rects)):
            landmarks = np.matrix([[p.x,p.y] for p in predictor(gray,rects[i]).parts()])
            for idx,point in enumerate(landmarks):
                pos=(point[0,0],point[0,1])
                points_keys.append([point[0,0],point[0,1]])
                cv2.circle(frame,pos,2,(255,0,0),-1)
                
        cv2.imshow('frame',frame)
        cv2.waitKey(5)
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值