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 相关文章推荐
Python2.x中str与unicode相关问题的解决方法
Mar 30 Python
Python多线程经典问题之乘客做公交车算法实例
Mar 22 Python
python正则实现计算器功能
Dec 14 Python
Python模拟脉冲星伪信号频率实例代码
Jan 03 Python
实例讲解Python脚本成为Windows中运行的exe文件
Jan 24 Python
django框架基于queryset和双下划线的跨表查询操作详解
Dec 11 Python
Anaconda+VSCode配置tensorflow开发环境的教程详解
Mar 30 Python
Python中如何引入第三方模块
May 27 Python
Python过滤掉numpy.array中非nan数据实例
Jun 08 Python
python如何使用腾讯云发送短信
Sep 17 Python
python 根据列表批量下载网易云音乐的免费音乐
Dec 03 Python
matplotlib常见函数之plt.rcParams、matshow的使用(坐标轴设置)
Jan 05 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短域名转换为实际域名函数
2011/01/17 PHP
PHP中操作ini配置文件的方法
2013/04/25 PHP
解析VS2010利用VS.PHP插件调试PHP的方法
2013/07/19 PHP
基于ThinkPHP实现的日历功能实例详解
2017/04/15 PHP
php 根据URL下载远程图片、压缩包、pdf等文件到本地
2019/07/26 PHP
解决ExtJS在chrome或火狐中正常显示在ie中不显示的浏览器兼容问题
2013/01/11 Javascript
js实现点击注册按钮开始读秒倒计时的小例子
2013/05/11 Javascript
jsp+javascript打造级连菜单的实例代码
2013/06/14 Javascript
extjs render 用法介绍
2013/09/11 Javascript
javaScript对文字按照拼音排序实现代码
2013/12/27 Javascript
Jquery Uploadify上传带进度条的简单实例
2014/02/12 Javascript
js中的如何定位固定层的位置
2014/06/15 Javascript
jQuery移动页面开发中的触摸事件与虚拟鼠标事件简介
2015/12/03 Javascript
JS字符串的切分用法实例
2016/02/22 Javascript
JS动态插入并立即执行回调函数的方法
2016/04/21 Javascript
JavaScript面试开发常用的知识点总结
2016/08/08 Javascript
Vue.JS入门教程之自定义指令
2016/12/08 Javascript
js实现带三角符的手风琴效果
2017/03/01 Javascript
JS实现简易计算器
2020/02/14 Javascript
[08:56]DOTA2-DPC中国联赛2月23日Recap集锦
2021/03/11 DOTA
python进阶教程之模块(module)介绍
2014/08/30 Python
Python基于pygame实现的font游戏字体(附源码)
2015/11/11 Python
python+matplotlib绘制3D条形图实例代码
2018/01/17 Python
5个很好的Python面试题问题答案及分析
2018/01/19 Python
python re正则匹配网页中图片url地址的方法
2018/12/20 Python
Django框架下静态模板的继承操作示例
2019/11/08 Python
Python GUI库PyQt5图形和特效样式QSS介绍
2020/02/25 Python
草莓网官网:StrawberryNET
2019/08/21 全球购物
客户代表自我评价范例
2013/09/24 职场文书
勿忘国耻9.18演讲稿(经典篇)
2014/09/14 职场文书
售房协议书范本2014
2014/10/23 职场文书
2015年乡镇人大工作总结
2015/04/22 职场文书
社区敬老月活动总结
2015/05/07 职场文书
导游词之湖北梁子湖
2019/11/07 职场文书
pandas DataFrame.shift()函数的具体使用
2021/05/24 Python
图文详解nginx日志切割的实现
2022/01/18 Servers