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 相关文章推荐
Windows下实现Python2和Python3两个版共存的方法
Jun 12 Python
在Django框架中运行Python应用全攻略
Jul 17 Python
Python中对象的引用与复制代码示例
Dec 04 Python
Python cookbook(数据结构与算法)实现优先级队列的方法示例
Feb 18 Python
win10下tensorflow和matplotlib安装教程
Sep 19 Python
pandas ix &amp;iloc &amp;loc的区别
Jan 10 Python
python字符串循环左移
Mar 08 Python
Python3.5内置模块之random模块用法实例分析
Apr 26 Python
Python实现ElGamal加密算法的示例代码
Jun 19 Python
Python判断变量是否是None写法代码实例
Oct 09 Python
selenium携带cookies模拟登陆CSDN的实现
Jan 19 Python
Python作用域和名称空间的详细介绍
Apr 13 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
关于BIG5-HKSCS的解决方法
2007/03/20 PHP
PHP实现的简单路由和类自动加载功能
2018/03/13 PHP
jquery中使用$(#form).submit()重写提交表单无效原因分析及解决
2013/03/25 Javascript
javascript中强制执行toString()具体实现
2013/04/27 Javascript
js取消单选按钮选中示例代码
2013/11/14 Javascript
js使下拉列表框可编辑不止是选择
2013/12/12 Javascript
分享一则JavaScript滚动条插件源码
2015/03/03 Javascript
JSON相关知识汇总
2015/07/03 Javascript
jquery.cookie.js用法实例详解
2015/12/25 Javascript
基于angularjs实现图片放大镜效果
2016/08/31 Javascript
使用vue框架 Ajax获取数据列表并用BootStrap显示出来
2017/04/24 Javascript
详解vue mint-ui源码解析之loadmore组件
2017/10/11 Javascript
VUE饿了么树形控件添加增删改功能的示例代码
2017/10/17 Javascript
javascript实现QQ空间相册展示源码
2017/12/12 Javascript
详解基于vue-cli配置移动端自适应
2018/01/13 Javascript
小程序异步问题之多个网络请求依次执行并依次收集请求结果
2019/05/05 Javascript
微信小程序缓存支持二次开发封装实现解析
2019/12/16 Javascript
python实现计算资源图标crc值的方法
2014/10/05 Python
python中的迭代和可迭代对象代码示例
2017/12/27 Python
pandas带有重复索引操作方法
2018/06/08 Python
Django migrations 默认目录修改的方法教程
2018/09/28 Python
基于python实现KNN分类算法
2020/04/23 Python
Python初学者常见错误详解
2019/07/02 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
2020/03/24 Python
win7上tensorflow2.2.0安装成功 引用DLL load failed时找不到指定模块 tensorflow has no attribute xxx 解决方法
2020/05/20 Python
Python爬虫教程之利用正则表达式匹配网页内容
2020/12/08 Python
英国安全产品购物网站:The Safe Shop
2017/03/20 全球购物
wedgwood加拿大官网:1759年成立的英国国宝级陶瓷餐具品牌
2018/07/17 全球购物
Wiggle美国:英国骑行、跑步、游泳、铁人三项商店
2018/10/27 全球购物
MVC的各个部分都有那些技术来实现?如何实现?
2016/04/21 面试题
应届优秀本科大学毕业生自我鉴定
2014/01/21 职场文书
小学生植树节活动总结
2014/07/04 职场文书
公司演讲稿开场白
2014/08/25 职场文书
投资申请报告
2015/05/19 职场文书
2016高中社会实践心得体会范文
2016/01/14 职场文书
浅析MySQL如何实现事务隔离
2021/06/26 MySQL