python使用dlib进行人脸检测和关键点的示例


Posted in Python onDecember 05, 2020
#!/usr/bin/env python
# -*- coding:utf-8-*-
# file: {NAME}.py
# @author: jory.d
# @contact: dangxusheng163@163.com
# @time: 2020/04/10 19:42
# @desc: 使用dlib进行人脸检测和人脸关键点

import cv2
import numpy as np
import glob
import dlib

FACE_DETECT_PATH = '/home/build/dlib-v19.18/data/mmod_human_face_detector.dat'
FACE_LANDMAKR_5_PATH = '/home/build/dlib-v19.18/data/shape_predictor_5_face_landmarks.dat'
FACE_LANDMAKR_68_PATH = '/home/build/dlib-v19.18/data/shape_predictor_68_face_landmarks.dat'


def face_detect():
  root = '/media/dangxs/E/Project/DataSet/VGG Face Dataset/vgg_face_dataset/vgg_face_dataset/vgg_face_dataset'
  imgs = glob.glob(root + '/**/*.jpg', recursive=True)
  assert len(imgs) > 0

  detector = dlib.get_frontal_face_detector()
  predictor = dlib.shape_predictor(FACE_LANDMAKR_68_PATH)
  for f in imgs:
    img = cv2.imread(f)
    # The 1 in the second argument indicates that we should upsample the image
    # 1 time. This will make everything bigger and allow us to detect more
    # faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))
    for i, d in enumerate(dets):
      x1, y1, x2, y2 = d.left(), d.top(), d.right(), d.bottom()
      print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
        i, x1, y1, x2, y2))

      cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)

      # Get the landmarks/parts for the face in box d.
      shape = predictor(img, d)
      print("Part 0: {}, Part 1: {} ...".format(shape.part(0), shape.part(1)))
      # # Draw the face landmarks on the screen.
      '''
      # landmark 顺序: 外轮廓 - 左眉毛 - 右眉毛 - 鼻子 - 左眼 - 右眼 - 嘴巴
      '''
      for i in range(shape.num_parts):
        x, y = shape.part(i).x, shape.part(i).y
        cv2.circle(img, (x, y), 2, (0, 0, 255), 1)
        cv2.putText(img, str(i), (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.3, (0, 0, 255), 1)

    cv2.resize(img, dsize=None, dst=img, fx=2, fy=2)
    cv2.imshow('w', img)
    cv2.waitKey(0)


def face_detect_mask():
  root = '/media/dangxs/E/Project/DataSet/VGG Face Dataset/vgg_face_dataset/vgg_face_dataset/vgg_face_dataset'
  imgs = glob.glob(root + '/**/*.jpg', recursive=True)
  assert len(imgs) > 0

  detector = dlib.get_frontal_face_detector()
  predictor = dlib.shape_predictor(FACE_LANDMAKR_68_PATH)
  for f in imgs:
    img = cv2.imread(f)
    # The 1 in the second argument indicates that we should upsample the image
    # 1 time. This will make everything bigger and allow us to detect more
    # faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))
    for i, d in enumerate(dets):
      x1, y1, x2, y2 = d.left(), d.top(), d.right(), d.bottom()
      print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
        i, x1, y1, x2, y2))

      cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)

      # Get the landmarks/parts for the face in box d.
      shape = predictor(img, d)
      print("Part 0: {}, Part 1: {} ...".format(shape.part(0), shape.part(1)))
      # # Draw the face landmarks on the screen.
      '''
      # landmark 顺序: 外轮廓 - 左眉毛 - 右眉毛 - 鼻子 - 左眼 - 右眼 - 嘴巴
      '''
      points = []
      for i in range(shape.num_parts):
        x, y = shape.part(i).x, shape.part(i).y
        if i < 26:
          points.append([x, y])
        # cv2.circle(img, (x, y), 2, (0, 0, 255), 1)
        # cv2.putText(img, str(i), (x,y),cv2.FONT_HERSHEY_COMPLEX, 0.3 ,(0,0,255),1)

      # 只把脸切出来
      points[17:] = points[17:][::-1]
      points = np.asarray(points, np.int32).reshape(-1, 1, 2)
      img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
      black_img = np.zeros_like(img)
      cv2.polylines(black_img, [points], 1, 255)
      cv2.fillPoly(black_img, [points], (1, 1, 1))
      mask = black_img
      masked_bgr = img * mask

      # 位运算时需要转化成灰度图像
      mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
      masked_gray = cv2.bitwise_and(img_gray, img_gray, mask=mask_gray)

    cv2.resize(img, dsize=None, dst=img, fx=2, fy=2)
    cv2.imshow('w', img)
    cv2.imshow('mask', mask)
    cv2.imshow('mask2', masked_gray)
    cv2.imshow('mask3', masked_bgr)
    cv2.waitKey(0)


if __name__ == '__main__':
  face_detect()

python使用dlib进行人脸检测和关键点的示例

python使用dlib进行人脸检测和关键点的示例

python使用dlib进行人脸检测和关键点的示例

以上就是python使用dlib进行人脸检测和关键点的示例的详细内容,更多关于python 人脸检测的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python基于pygame实现响应游戏中事件的方法(附源码)
Nov 11 Python
python实现识别相似图片小结
Feb 22 Python
详解Python中的动态属性和特性
Apr 07 Python
对python数据切割归并算法的实例讲解
Dec 12 Python
python读取指定字节长度的文本方法
Aug 27 Python
python with语句的原理与用法详解
Mar 30 Python
Keras 加载已经训练好的模型进行预测操作
Jun 17 Python
Python闭包装饰器使用方法汇总
Jun 29 Python
pycharm中如何自定义设置通过“ctrl+滚轮”进行放大和缩小实现方法
Sep 16 Python
python自动化测试三部曲之request+django实现接口测试
Oct 07 Python
Python将list元素转存为CSV文件的实现
Nov 16 Python
Python first-order-model实现让照片动起来
Jun 25 Python
python从ftp获取文件并下载到本地
Dec 05 #Python
python基于socket模拟实现ssh远程执行命令
Dec 05 #Python
Python实现PS滤镜中的USM锐化效果
Dec 04 #Python
python 模拟登陆github的示例
Dec 04 #Python
python中round函数保留两位小数的方法
Dec 04 #Python
python中pow函数用法及功能说明
Dec 04 #Python
python对输出的奇数偶数排序实例代码
Dec 04 #Python
You might like
PHP面向对象的使用教程 简单数据库连接
2006/11/25 PHP
色色整理的PHP面试题集锦
2012/03/08 PHP
简单的php缓存类分享     php缓存机制
2014/01/22 PHP
php socket客户端及服务器端应用实例
2014/07/04 PHP
PHP实现ftp上传文件示例
2014/08/21 PHP
PHP简单判断iPhone、iPad、Android及PC设备的方法
2016/10/11 PHP
curl 出现错误的调试方法(必看)
2017/02/13 PHP
基于jQuery的图片不完全按比例自动缩小
2014/07/11 Javascript
JS实现5秒钟自动封锁div层的方法
2015/02/20 Javascript
基于jQuery实现点击最后一行实现行自增效果的表格
2016/01/12 Javascript
JavaScript 2048 游戏实例代码(简单易懂)
2016/03/25 Javascript
Vuejs第十篇之vuejs父子组件通信
2016/09/06 Javascript
移动端滑动插件Swipe教程
2016/10/16 Javascript
使用JavaScript解决网页图片拉伸问题(推荐)
2016/11/25 Javascript
canvas实现流星雨的背景效果
2017/01/13 Javascript
详谈Angular 2+ 的表单(一)之模板驱动型表单
2017/04/25 Javascript
Webpack实现按需打包Lodash的几种方法详解
2017/05/08 Javascript
vue项目引入字体.ttf的方法
2018/09/28 Javascript
jQuery实现的自定义轮播图功能详解
2018/12/28 jQuery
微信小程序实现Swiper轮播图效果
2019/11/22 Javascript
改进Django中的表单的简单方法
2015/07/17 Python
PyQt5笔记之弹出窗口大全
2019/06/20 Python
python实现连续变量最优分箱详解--CART算法
2019/11/22 Python
Python如何将函数值赋给变量
2020/04/28 Python
CSS3使用多列制作瀑布流
2016/05/10 HTML / CSS
CSS3条纹背景制作的实战攻略
2016/05/31 HTML / CSS
HTML5画渐变背景图片并自动下载实现步骤
2013/11/18 HTML / CSS
利用三角函数在canvas上画虚线的方法
2018/01/11 HTML / CSS
澳大利亚领先的亚麻品牌:Bed Threads
2019/12/16 全球购物
口腔工艺技术专业毕业生自荐信
2013/09/27 职场文书
新郎婚宴答谢词
2014/01/19 职场文书
个人近期表现材料
2014/02/11 职场文书
初中生300字旷课检讨书
2014/11/19 职场文书
学校青年志愿者活动总结
2015/05/06 职场文书
高中诗歌鉴赏教学反思
2016/02/16 职场文书
pandas:get_dummies()与pd.factorize()的用法及区别说明
2021/05/21 Python