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 pass 语句使用示例
Mar 11 Python
Linux中Python 环境软件包安装步骤
Mar 31 Python
Python端口扫描简单程序
Nov 10 Python
python学习之matplotlib绘制散点图实例
Dec 09 Python
PyQt5主窗口动态加载Widget实例代码
Feb 07 Python
对Django 转发和重定向的实例详解
Aug 06 Python
如何使用python3获取当前路径及os.path.dirname的使用
Dec 13 Python
Python图像处理库PIL中图像格式转换的实现
Feb 26 Python
如何使用python代码操作git代码
Feb 29 Python
Python3.6 中的pyinstaller安装和使用教程
Mar 16 Python
python爬虫学习笔记之Beautifulsoup模块用法详解
Apr 09 Python
Pytorch实现将模型的所有参数的梯度清0
Jun 24 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
解析thinkphp中的导入文件标签
2013/06/20 PHP
实用的简单PHP分页集合包括使用方法
2013/10/21 PHP
codeigniter框架批量插入数据
2014/01/09 PHP
PHP实现XML与数据格式进行转换类实例
2015/07/29 PHP
PHP的文件操作与算法实现的面试题示例
2015/08/10 PHP
浅谈PHP的反射API
2017/02/26 PHP
PHP实现微信支付(jsapi支付)流程步骤详解
2018/03/15 PHP
laravel csrf排除路由,禁止,关闭指定路由的例子
2019/10/21 PHP
Laravel 5.2 文档 数据库 ―― 起步介绍
2019/10/21 PHP
JS 继承实例分析
2008/11/04 Javascript
30个最好的jQuery 灯箱插件分享
2011/04/25 Javascript
Node.js和PHP根据ip获取地理位置的方法
2014/03/14 Javascript
javascript实现起伏的水波背景效果
2016/05/16 Javascript
JSP基于Bootstrap分页显示实例解析
2016/06/12 Javascript
原生js的RSA和AES加密解密算法
2016/10/08 Javascript
Node.js websocket使用socket.io库实现实时聊天室
2017/02/20 Javascript
js模仿微信朋友圈计算时间显示几天/几小时/几分钟/几秒之前
2017/04/27 Javascript
JavaScript简单实现合并两个Json对象的方法示例
2017/10/16 Javascript
详解基于Vue2.0实现的移动端弹窗(Alert, Confirm, Toast)组件
2018/08/02 Javascript
vue项目打包之后背景样式丢失的解决方案
2019/01/17 Javascript
使用VueRouter的addRoutes方法实现动态添加用户的权限路由
2019/06/03 Javascript
详解vue父子组件关于模态框状态的绑定方案
2019/06/05 Javascript
微信小程序基于Taro的分享图片功能实践详解
2019/07/12 Javascript
完美解决通过IP地址访问VUE项目的问题
2020/07/18 Javascript
[06:30]DOTA2英雄梦之声_第15期_死亡先知
2014/06/21 DOTA
深入理解python try异常处理机制
2016/06/01 Python
Python3批量生成带logo的二维码方法
2019/06/24 Python
Python3内置模块之base64编解码方法详解
2019/07/13 Python
python对绑定事件的鼠标、按键的判断实例
2019/07/17 Python
Python Django view 两种return的实现方式
2020/03/16 Python
AMAVII眼镜官网:时尚和设计师太阳镜
2019/05/05 全球购物
会计应届生的自荐信
2013/12/13 职场文书
人事任命书范文
2014/06/04 职场文书
工作作风建设心得体会
2014/10/22 职场文书
公司业务员管理制度
2015/08/05 职场文书
手把手教你制定暑期学习计划,让你度过充实的暑假
2019/08/22 职场文书