python使用dlib进行人脸检测和关键点的示例

 更新时间:2020年12月05日 10:15:52   作者:dangxusheng  
这篇文章主要介绍了python使用dlib进行人脸检测和关键点的示例,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
#!/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 人脸检测的资料请关注脚本之家其它相关文章!

相关文章

  • Python实现删除列表中满足一定条件的元素示例

    Python实现删除列表中满足一定条件的元素示例

    这篇文章主要介绍了Python实现删除列表中满足一定条件的元素,结合具体实例形式对比分析了Python针对列表元素的遍历、复制、删除等相关操作技巧,需要的朋友可以参考下
    2017-06-06
  • 盘点总结Python爬虫常用库(附官方文档)

    盘点总结Python爬虫常用库(附官方文档)

    在信息时代,数据是无处不在的宝藏,从网页内容、社交媒体帖子到在线商店的产品信息,互联网上存在着大量的数据等待被收集和分析,Python爬虫是一种强大的工具,用于从互联网上获取和提取数据
    2023-11-11
  • Python Jinja2 库灵活性广泛性应用场景实例解析

    Python Jinja2 库灵活性广泛性应用场景实例解析

    Jinja2,作为Python中最流行的模板引擎之一,为开发者提供了强大的工具,用于在Web应用和其他项目中生成动态内容,本文将深入研究 Jinja2 库的各个方面,提供更丰富的示例代码,能够充分理解其灵活性和广泛应用的场景
    2024-01-01
  • pydev debugger: process 10341 is connecting无法debu的解决

    pydev debugger: process 10341 is co

    这篇文章主要介绍了pydev debugger: process 10341 is connecting无法debu的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • Python生成短uuid的方法实例详解

    Python生成短uuid的方法实例详解

    python的uuid都是32位的,比较长,处理起来效率比较低。这篇文章主要介绍了Python生成短uuid的方法,需要的朋友可以参考下
    2018-05-05
  • python读取图片的几种方式及图像宽和高的存储顺序

    python读取图片的几种方式及图像宽和高的存储顺序

    这篇文章主要介绍了python读取图片的几种方式及图像宽和高的存储顺序,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • 在Python下进行UDP网络编程的教程

    在Python下进行UDP网络编程的教程

    这篇文章主要介绍了在Python下进行UDP网络编程的教程,UDP编程是Python网络编程部分的基础知识,示例代码基于Python2.x版本,需要的朋友可以参考下
    2015-04-04
  • Pycharm激活码激活两种快速方式(附最新激活码和插件)

    Pycharm激活码激活两种快速方式(附最新激活码和插件)

    这篇文章主要介绍了Pycharm两种快速激活方式(附最新激活码和插件) ,本文给大家分享两种方式,小编在文章给大家推荐方法二,大家可以根据自己需要选择,感兴趣的朋友跟随小编一起看看吧
    2020-03-03
  • python 常见的反爬虫策略

    python 常见的反爬虫策略

    这篇文章主要介绍了python反爬虫策略,帮助大家更好的理解和使用python 爬虫,感兴趣的朋友可以了解下
    2020-09-09
  • PyTorch实现线性回归详细过程

    PyTorch实现线性回归详细过程

    本文介绍PyTorch实现线性回归,线性关系是一种非常简单的变量之间的关系,因变量和自变量在线性关系的情况下,可以使用线性回归算法对一个或多个因变量和自变量间的线性关系进行建模,该模型的系数可以用最小二乘法进行求解,需要的朋友可以参考一下
    2022-03-03

最新评论