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之使用Python操作数据库(1)
Nov 25 Python
Python数据库的连接实现方法与注意事项
Feb 27 Python
Python列出一个文件夹及其子目录的所有文件
Jun 30 Python
Python编程实现输入某年某月某日计算出这一天是该年第几天的方法
Apr 18 Python
python下载图片实现方法(超简单)
Jul 21 Python
Python numpy 常用函数总结
Dec 07 Python
Python hashlib模块用法实例分析
Jun 12 Python
Mac在python3环境下安装virtualwrapper遇到的问题及解决方法
Jul 09 Python
Django logging配置及使用详解
Jul 23 Python
Python3显示当前时间、计算时间差及时间加减法示例代码
Sep 07 Python
Django+uni-app实现数据通信中的请求跨域的示例代码
Oct 12 Python
Python 依赖库太多了该如何管理
Nov 08 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
《被神捡到的男人》动画化计划进行中!
2020/03/06 日漫
手冲咖啡应该是现代精品咖啡店的必备选项吗?
2021/03/03 冲泡冲煮
php中长文章分页显示实现代码
2012/09/29 PHP
关于php操作mysql执行数据库查询的一些常用操作汇总
2013/06/24 PHP
PHP常用文件操作函数和简单实例分析
2016/06/03 PHP
php并发加锁示例
2016/10/17 PHP
php mysql_real_escape_string addslashes及mysql绑定参数防SQL注入攻击
2016/12/23 PHP
老生常谈PHP中的数据结构:DS扩展
2017/07/17 PHP
dess中一个简单的多路委托的实现
2010/07/20 Javascript
前端开发的开始---基于面向对象的Ajax类
2010/09/17 Javascript
JavaScript数组各种常见用法实例分析
2015/08/04 Javascript
js实现类似MSN提示的页面效果代码分享
2015/08/24 Javascript
AngularJS ng-style中使用filter
2016/09/21 Javascript
原生JS获取元素的位置与尺寸实现方法
2017/10/18 Javascript
vue二级路由设置方法
2018/02/09 Javascript
详解React项目如何修改打包地址(编译输出文件地址)
2019/03/21 Javascript
Openlayers实现点闪烁扩散效果
2020/09/24 Javascript
vue实现井字棋游戏
2020/09/29 Javascript
Vue 实现可视化拖拽页面编辑器
2021/02/01 Vue.js
Python列表计数及插入实例
2014/12/17 Python
深入解析Python编程中JSON模块的使用
2015/10/15 Python
python对配置文件.ini进行增删改查操作的方法示例
2017/07/28 Python
Python实现京东秒杀功能代码
2019/05/16 Python
python 猴子补丁(monkey patch)
2019/06/26 Python
如何在python中执行另一个py文件
2020/04/30 Python
html5+css3气泡组件的实现
2014/11/21 HTML / CSS
衰败城市英国官网:Urban Decay英国
2020/04/29 全球购物
公司新员工的演讲稿注意事项
2014/01/01 职场文书
办公室文员工作职责
2014/01/31 职场文书
查摆剖析材料范文
2014/09/30 职场文书
2014年作风建设剖析材料
2014/10/23 职场文书
2015年党员个人剖析材料
2014/12/18 职场文书
市场营销计划书
2015/01/17 职场文书
导游词之无锡梅园
2019/11/28 职场文书
浅谈Python numpy创建空数组的问题
2021/05/25 Python
关于python3 opencv 图像二值化的问题(cv2.adaptiveThreshold函数)
2022/04/04 Python