前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python使用dlib实现人脸检测

Python使用dlib实现人脸检测

作者头像
Awesome_Tang
发布2019-02-25 10:00:55
9580
发布2019-02-25 10:00:55
举报
文章被收录于专栏:FSocietyFSociety
前期准备

在开始之前,你得先做如下准备:

  • opencv 这个一般没啥问题,通过pip install opencv-python安装即可。
  • dlib 安装dlib之前需要安装好cmake,之后再通过pip install dlib安装,如果报错的话,再自行百度吧,我是折腾了一下午才弄好。
  • 下载dlib提供的检测模型文件 下载地址:http://dlib.net/files/ 文件名shape_predictor_68_face_landmarks.dat
人脸检测
单一图片

代码部分实现起来非常简单,不过十几行的事,不过需要注意的是,通过cv2.imread读取的图片是BRG通道的,需要转成RGB通道,不然通过pyplot显示图片会变色。

  • 代码部分
代码语言:javascript
复制
import cv2
import dlib
import matplotlib.pyplot as plt
import numpy as np

predictor_path = 'shape_predictor_68_face_landmarks.dat'
test_img = 'test.png'
img = cv2.imread(test_img)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)

faces = detector(img, 0)
if len(faces):
    print '==> Found %d face in this image.' % len(faces)
    for i in range(len(faces)):
        landmarks = np.matrix([[p.x, p.y] for p in predictor(img, faces[i]).parts()])
        for point in landmarks:
            pos = (point[0, 0], point[0, 1])
            cv2.circle(img, pos, 3, color=(0, 255, 0),thickness=3)
else:
    print 'Face not found!'

# opencv读取图片是BRG通道的,需要专成RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 8))
plt.subplot(121)
plt.imshow(plt.imread(test_img))
plt.axis('off')
plt.subplot(122)
plt.imshow(img)
plt.axis('off')
plt.show()
  • 效果如下

68点人脸检测

摄像头读取

我们可以通过cv2.VideoCapture(0)调起摄像头,camera.read会返回两个参数,第一个代表是否获取到图像帧,第二个代表图像帧内容,剩下的部分就跟上面一样了,传给dlib进行人脸检测就好了。

  • 完整代码
代码语言:javascript
复制
# -*- coding: utf-8 -*-

# @author: Awesome_Tang
# @date: 2018-12-31
# @version: python2.7

import cv2
import dlib
import numpy as np
import os


class Config(object):
    predictor_path = 'shape_predictor_68_face_landmarks.dat'
    test_img = 'test.jpg'
    width = 640
    height = 480


class FaceDetective():

    def __init__(self):
        self.detector = dlib.get_frontal_face_detector()
        self.predictor = dlib.shape_predictor(Config.predictor_path)

    def check_file(self,path):
        if os.path.exists(path):
            img = cv2.imread(path)
            return img
        else:
            raise IOError('No such file : "%s", please check!' % path)

    def detective(self, frame):
        faces = self.detector(frame, 0)
        if len(faces):
            print '==> Found %d face in this frame.' % len(faces)
            for i in range(len(faces)):
                landmarks = np.matrix([[p.x, p.y] for p in self.predictor(frame, faces[i]).parts()])
                for point in landmarks:
                    pos = (point[0, 0], point[0, 1])
                    cv2.circle(frame, pos, 3, color=(0, 0, 255),thickness=3)
        else:
            print 'Face not found!'
        return frame

    def run_camera(self):
        camera = cv2.VideoCapture(0)
        camera.set(cv2.CAP_PROP_FRAME_WIDTH, Config.width)
        camera.set(cv2.CAP_PROP_FRAME_HEIGHT, Config.height)
        while True:
            detected, frame = camera.read()

            if detected:
                frame = cv2.flip(frame, 1)
                frame = self.detective(frame)
            cv2.imshow("AwesomeTang", frame)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        camera.release()
        cv2.destroyAllWindows()

    def single_image(self,img_path):
        img = self.check_file(img_path)
        img = self.detective(img)
        cv2.namedWindow("AwesomeTang", 0)
        cv2.resizeWindow("AwesomeTang", Config.width, Config.height)
        cv2.imshow("AwesomeTang",img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == '__main__':
    p = FaceDetective()
    #p.single_image(Config.test_img)
    p.run_camera()
  • 效果如下

skr~ skr~~

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.01.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前期准备
  • 人脸检测
    • 单一图片
      • 摄像头读取
      相关产品与服务
      人脸识别
      腾讯云神图·人脸识别(Face Recognition)基于腾讯优图强大的面部分析技术,提供包括人脸检测与分析、比对、搜索、验证、五官定位、活体检测等多种功能,为开发者和企业提供高性能高可用的人脸识别服务。 可应用于在线娱乐、在线身份认证等多种应用场景,充分满足各行业客户的人脸属性识别及用户身份确认等需求。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档