python dlib学习(二):人脸特征点标定

前言

上次介绍了人脸检测的程序(python dlib学习(一):人脸检测),这次介绍人脸特征点标定。dlib提供了训练好的模型,可以识别人脸的68个特征点。
下载链接:http://pan.baidu.com/s/1i46vPu1。

程序

还是直接上代码,注释在程序中。用到了python-opencv、dlib。

# -*- coding: utf-8 -*-
import sys
import dlib
import cv2
import os

current_path = os.getcwd()  # 获取当前路径
predictor_path = current_path + "\\model\\shape_predictor_68_face_landmarks.dat"  # shape_predictor_68_face_landmarks.dat是进行人脸标定的模型,它是基于HOG特征的,这里是他所在的路径
face_directory_path = current_path + "\\faces\\"    # 存放人脸图片的路径

detector = dlib.get_frontal_face_detector() #获取人脸分类器
predictor = dlib.shape_predictor(predictor_path)    # 获取人脸检测器

# 传入的命令行参数
for f in sys.argv[1:]:
    # 图片路径,目录+文件名
    face_path = face_directory_path + f

    # opencv 读取图片,并显示
    img = cv2.imread(f, cv2.IMREAD_COLOR)

    # 摘自官方文档:
    # image is a numpy ndarray containing either an 8bit grayscale or RGB image.
    # opencv读入的图片默认是bgr格式,我们需要将其转换为rgb格式;都是numpy的ndarray类。
    b, g, r = cv2.split(img)    # 分离三个颜色通道
    img2 = cv2.merge([r, g, b])   # 融合三个颜色通道生成新图片

    dets = detector(img, 1) #使用detector进行人脸检测 dets为返回的结果
    print("Number of faces detected: {}".format(len(dets)))   # 打印识别到的人脸个数
    # enumerate是一个Python的内置方法,用于遍历索引
    # index是序号;face是dets中取出的dlib.rectangle类的对象,包含了人脸的区域等信息
    # left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置
    for index, face in enumerate(dets):
        print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom()))

        # 这里不需要画出人脸的框了
        # left = face.left()
        # top = face.top()
        # right = face.right()
        # bottom = face.bottom()
        # cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
        # cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
        # cv2.imshow(f, img)

        shape = predictor(img, face)  # 寻找人脸的68个标定点 
        # print(shape)
        # print(shape.num_parts)
        # 遍历所有点,打印出其坐标,并用蓝色的圈表示出来
        for index, pt in enumerate(shape.parts()):
            print('Part {}: {}'.format(index, pt))
            pt_pos = (pt.x, pt.y)
            cv2.circle(img, pt_pos, 2, (255, 0, 0), 1)

        # 在新窗口中显示
        cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
        cv2.imshow(f, img)

# 等待按键,随后退出,销毁窗口
k = cv2.waitKey(0)
cv2.destroyAllWindows()

还有一点补充的:
我的文件夹结构是这样的:
python dlib学习(二):人脸特征点标定_第1张图片
faces中存放图片,运行程序时指定名字,会到这个文件夹中读取图片。
python dlib学习(二):人脸特征点标定_第2张图片
model文件夹中存放模型。
这里写图片描述

运行结果

python dlib学习(二):人脸特征点标定_第3张图片

官方例程

最后给出官方例程,也可以参考官方例程。

#!/usr/bin/python
# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
#
#   This example program shows how to find frontal human faces in an image and
#   estimate their pose.  The pose takes the form of 68 landmarks.  These are
#   points on the face such as the corners of the mouth, along the eyebrows, on
#   the eyes, and so forth.
#
#   This face detector is made using the classic Histogram of Oriented
#   Gradients (HOG) feature combined with a linear classifier, an image pyramid,
#   and sliding window detection scheme.  The pose estimator was created by
#   using dlib's implementation of the paper:
#      One Millisecond Face Alignment with an Ensemble of Regression Trees by
#      Vahid Kazemi and Josephine Sullivan, CVPR 2014
#   and was trained on the iBUG 300-W face landmark dataset.
#
#   Also, note that you can train your own models using dlib's machine learning
#   tools. See train_shape_predictor.py to see an example.
#
#   You can get the shape_predictor_68_face_landmarks.dat file from:
#   http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
#
# COMPILING/INSTALLING THE DLIB PYTHON INTERFACE
#   You can install dlib using the command:
#       pip install dlib
#
#   Alternatively, if you want to compile dlib yourself then go into the dlib
#   root folder and run:
#       python setup.py install
#   or
#       python setup.py install --yes USE_AVX_INSTRUCTIONS
#   if you have a CPU that supports AVX instructions, since this makes some
#   things run faster.  
#
#   Compiling dlib should work on any operating system so long as you have
#   CMake and boost-python installed.  On Ubuntu, this can be done easily by
#   running the command:
#       sudo apt-get install libboost-python-dev cmake
#
#   Also note that this example requires scikit-image which can be installed
#   via the command:
#       pip install scikit-image
#   Or downloaded from http://scikit-image.org/download.html. 

import sys
import os
import dlib
import glob
from skimage import io

if len(sys.argv) != 3:
    print(
        "Give the path to the trained shape predictor model as the first "
        "argument and then the directory containing the facial images.\n"
        "For example, if you are in the python_examples folder then "
        "execute this program by running:\n"
        "    ./face_landmark_detection.py shape_predictor_68_face_landmarks.dat ../examples/faces\n"
        "You can download a trained facial shape predictor from:\n"
        "    http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2")
    exit()

predictor_path = sys.argv[1]
faces_folder_path = sys.argv[2]

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
win = dlib.image_window()

for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. 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 k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # 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.
        win.add_overlay(shape)

    win.add_overlay(dets)
    dlib.hit_enter_to_continue()

你可能感兴趣的:(机器学习,OpenCV,Python,图像处理,Python,dlib学习)