基於Dlib進行人臉特徵點檢測的Python代碼實現

一.Python代碼實現

import sys
import os
import glob
import dlib
import numpy as np
import cv2
#把imread中的路徑修改爲自己的圖片路徑,圖片格式爲jpeg格式
img=cv2.imread("/home/kd/PycharmProjects/python-pro/datasets/8.jpeg")
detector= dlib.get_frontal_face_detector()
#檢測出有幾張臉在圖片中
dets = detector(img, 1)
img_faces=[]
#加載模型
#把dlib.shape_predictor("path")中的path修改爲自己存儲的.dat文件的路徑
predictor = dlib.shape_predictor('/home/kd/PycharmProjects/python-pro/dlib_model/shape_predictor_68_face_landmarks.dat')
for i,face in enumerate(dets):
    x = dlib.rectangle.left(dets[i])
    y = dlib.rectangle.top(dets[i])
    h = dlib.rectangle.height(dets[i])
    w = dlib.rectangle.width(dets[i])
    img_faces.append([x, y, w, h])
    length = len(img_faces)
    for i in range(length):
        cv2.rectangle(img, (img_faces[i][0], img_faces[i][1]),
             (img_faces[i][0] + img_faces[i][2], img_faces[i][1] + img_faces[i][3]), (0, 0, 255))

    #提取出每一張臉的特徵點
    face_feature = predictor(img,face)
    for i,pt in enumerate(face_feature.parts()):
        pt_pos=(pt.x,pt.y)
        cv2.circle(img,pt_pos,2,(255,255,255),1)
    cv2.namedWindow("face feature",cv2.WINDOW_AUTOSIZE)
    cv2.imshow("face feature",img)

cv2.waitKey(0)

 二.使用Dlib提取人臉特徵(68維)

臉是由眼睛、鼻子、嘴、下巴等局部構成,這些局部之間的結構關係,便是作爲人臉的重要特徵。人臉特徵的提取,是對人臉進行特徵建模的過程。

使用Dlib可提取人臉的68個特徵點,這些特徵點描述了眉毛、眼睛、鼻子、嘴巴,以及整個臉部的輪廓,如下圖所示:

 三.Dlib人臉特徵模型的下載:

下載地址:http://dlib.net/files/

5個特徵點的模型:shape_predictor_5_face_landmarks.dat.bz2

68個特徵點的模型:shape_predictor_68_face_landmarks.dat.bz2

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章