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解决字典中的值是列表问题的方法
Mar 04 Python
python base64 decode incorrect padding错误解决方法
Jan 08 Python
Python中的localtime()方法使用详解
May 22 Python
学习python 之编写简单乘法运算题
Feb 27 Python
python对配置文件.ini进行增删改查操作的方法示例
Jul 28 Python
利用Opencv中Houghline方法实现直线检测
Feb 11 Python
在Windows中设置Python环境变量的实例讲解
Apr 28 Python
python 在屏幕上逐字显示一行字的实例
Dec 24 Python
python开发游戏的前期准备
May 05 Python
Python集中化管理平台Ansible介绍与YAML简介
Jun 12 Python
Python Handler处理器和自定义Opener原理详解
Mar 05 Python
Python 数据分析之逐块读取文本的实现
Dec 14 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 魔术方法详解
2014/11/11 PHP
ThinkPHP3.2框架自带分页功能实现方法示例
2019/05/13 PHP
javascript 哈希表(hashtable)的简单实现
2010/01/20 Javascript
checkbox选中与未选中判断示例
2014/08/04 Javascript
使用js画图之正弦曲线
2015/01/12 Javascript
js实现仿京东2级菜单效果(带延时功能)
2015/08/27 Javascript
基于JavaScript实现百叶窗动画效果不只单纯flas可以实现
2016/02/29 Javascript
fullPage.js和CSS3实现全屏滚动效果
2017/05/05 Javascript
Angular搜索 过滤 批量删除 添加 表单验证功能集锦(实例代码)
2017/10/25 Javascript
Angular4 Select选择改变事件的方法
2018/10/09 Javascript
详解Vue SSR( Vue2 + Koa2 + Webpack4)配置指南
2018/11/13 Javascript
详解js中let与var声明变量的区别
2020/04/05 Javascript
JS定义函数的几种常用方法小结
2019/05/23 Javascript
nodejs二进制与Buffer的介绍与使用
2019/07/11 NodeJs
Vue中el-form标签中的自定义el-select下拉框标签功能
2020/04/20 Javascript
[39:53]完美世界DOTA2联赛PWL S2 LBZS vs Forest 第一场 11.19
2020/11/19 DOTA
小结Python用fork来创建子进程注意事项
2014/07/03 Python
python对html代码进行escape编码的方法
2015/05/04 Python
总结网络IO模型与select模型的Python实例讲解
2016/06/27 Python
Python读取mat文件,并转为csv文件的实例
2018/07/04 Python
对python:print打印时加u的含义详解
2018/12/15 Python
python中使用 xlwt 操作excel的常见方法与问题
2019/01/13 Python
Python小白必备的8个最常用的内置函数(推荐)
2019/04/03 Python
pyqt5 使用label控件实时显示时间的实例
2019/06/14 Python
python os.fork() 循环输出方法
2019/08/08 Python
python3使用print打印带颜色的字符串代码实例
2019/08/22 Python
python安装本地whl的实例步骤
2019/10/12 Python
python读取mysql数据绘制条形图
2020/03/25 Python
举例详解HTML5中使用JSON格式提交表单
2015/06/16 HTML / CSS
River Island美国官网:英国高街时尚品牌
2018/09/04 全球购物
大学生求职信范文应怎么写
2014/01/01 职场文书
销售员个人求职的自我评价
2014/02/10 职场文书
售票员岗位职责
2015/02/15 职场文书
花木兰观后感
2015/06/10 职场文书
劳务派遣管理制度(样本)
2019/08/23 职场文书
JS异步堆栈追踪之为什么await胜过Promise
2021/04/28 Javascript