【三:dlib人臉關鍵點】python3.5實現人臉關鍵點提取

人臉檢測在系列二中,使用了dlib自帶的人臉檢測器(detector),關鍵點提取需要一個特徵提取器(predictor),爲了構建特徵提取器,預訓練模型必不可少。

官方提供了訓練自己模型的例子,除了自行進行訓練外,還可以使用官方提供的一個模型。該模型可從dlib sourceforge庫下載:

http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2

這個庫支持68個關鍵點的提取,face++提供了102個特徵點,如果需要更多的特徵點,我們需要自己去訓練。

# -*-encoding=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'
predictor_path = current_path +'./model/shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)

for f in sys.argv[1:]:
    img = cv2.imread(f, cv2.IMREAD_COLOR)
    dets = detector(img, 2)
    print("Number of faces detected: {}".format(len(dets)))
    for index, face in enumerate(dets):
        print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom()))
        shape = predictor(img,face)
        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)
        left = face.left()
        top = face.top()
        right = face.right()
        bottom = face.bottom()
        cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 1)
        cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
        cv2.imshow(f, img)

k = cv2.waitKey(0)
cv2.destroyAllWindows()

運行命令爲python xxx.py 1.jpg

如果是在pycharm ide 中,則只需在Edit Configurations 中的Script parameters項中配置1.jpg即可

試驗原始圖:

試驗原始圖

試驗結果圖:

結果圖

 

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