人臉識別之Python DLib庫進行人臉關鍵點識別

1、首先安裝DLib模塊

這裏只介紹linux安裝的過程,windows安裝過程請自行百度python

一、首先,安裝dlib、skimage前;先安裝libboostlinux

sudo apt-get install libboost-python-dev cmake

 

接下來到dlib官網dlib.net下載最新的dlib版本(我下的是dlib-19.7),進入文件所在目錄解壓windows

bzip2 -d dlib-19.7.tar.bz2
tar xvf dlib-19.7.tar

 

這是一個二級解壓過程,解壓獲得文件dlib-19.7,進入該目錄下,執行以下命令安裝dlibspa

python setup.py install

 

安裝完成後,切換到python,鍵入import dlib,無異常提示代表安裝成功!
接着安裝skimage.net

sudo apt-get install python-skimage

2、人臉檢測

import sys
import dlib
from skimage import io

detector = dlib.get_frontal_face_detector() 
window = dlib.image_window()  
img = io.imread("1.jpg")

dets = detector(img, 1)  
print("Number of faces detected: {}".format(len(dets))) 
for i, d in enumerate(dets):
    print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(i, d.left(), d.top(), d.right(), d.bottom()))

window.clear_overlay()
window.set_image(img) 
window.add_overlay(dets)
dlib.hit_enter_to_continue() 

首先調用dlib.get_frontal_face_detector() 來加載dlib自帶的人臉檢測器
dets = detector(img, 1)將檢測器應用在輸入圖片上,結果返回給dets(參數1表示對圖片進行上採樣一次,有利於檢測到更多的人臉);
dets的個數即爲檢測到的人臉的個數;
遍歷dets能夠獲取到檢測到的每一個人臉四個座標極值。
爲了框出檢測到的人臉,用dlib.image_window()來加載顯示窗口,window.set_image(img)先將圖片顯示到窗口上,再利用window.add_overlay(dets)來繪製檢測到的人臉框;
dlib.hit_enter_to_continue()用於等待點擊(相似於opencv的cv2.waitKey(0),不加這個會出現閃退)。
檢測結果以下圖:
orm

3、關鍵點的提取blog

實現關鍵點描述須要用到用於特徵提取的官方模型,下載地址以下: 
http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
圖片

 

# -*- coding: utf-8 -*-

import dlib
import numpy
from skimage import io
import cv2

predictor_path = "../data/shape_predictor_68_face_landmarks.dat"
faces_path = "1.jpg"

'''加載人臉檢測器、加載官方提供的模型構建特徵提取器'''
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)

win = dlib.image_window()
img = io.imread(faces_path)

win.clear_overlay()
win.set_image(img)

dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))

for k, d in enumerate(dets):
    shape = predictor(img, d)
    landmark = numpy.matrix([[p.x, p.y] for p in shape.parts()])
    print("face_landmark:")
    print (landmark)  # 打印關鍵點矩陣
    win.add_overlay(shape)  #繪製特徵點
    for idx, point in enumerate(landmark):
        pos = (point[0, 0], point[0, 1])
        cv2.putText(img, str(idx), pos, fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
                    fontScale=0.3, color=(0, 255, 0))
        # cv2.circle(img, pos, 3, color=(0, 255, 0))
    win.set_image(img)

dlib.hit_enter_to_continue()

 

首先經過dlib.shape_predictor(predictor_path)從路徑中加載模型,返回的predictor就是特徵提取器 ip

對dets遍歷,用predictor(img, d)計算檢測到的每張人臉的關鍵點;
獲取每一個關鍵點座標shape.parts()的x,y值,存入landmark矩陣(模型默認提取68個關鍵點,因此landmark爲68×2矩陣)。
關鍵點提取結果以下:
utf-8

源碼獲取方式,關注公總號RaoRao1994,查看往期精彩-全部文章,便可獲取資源下載連接

更多資源獲取,請關注公總號RaoRao1994

相關文章
相關標籤/搜索