天天看點

人臉對齊--采用dlib庫的68_face_landmark進行人臉對齊操作

簡單說說人臉對齊操作的部分作用

人臉對齊操作的目的就是能夠把檢測到的水準角度不正的人臉采用數學的方式進行角度的糾正。進而,在一定程度上提升後期人臉識别的精确度。

人臉對齊操作的基本步驟

  • 人臉檢測
  • 人臉關鍵點資訊檢測(眼睛,鼻子,嘴巴,下吧等…)
  • 人臉對齊

人臉對齊的方法有很多,本文隻是采用dlib庫提供的68點關鍵點資訊檢測的模型來實作人臉對齊操作,本人能力和技術有限,代碼和思路供大家參考和學習,不足之處還請多多諒解!!互相學習!!

直接上代碼

注意:需要提前安裝好dlib庫

(代碼的功能: 批量對檔案夾内的人臉照片進行人臉檢測以及人臉對齊操作,并且将檢測和對齊好的人臉儲存至指定目錄)

face_alignment.py

# -*-coding: utf-8-*-
# author: HXY
"""
采用68個關鍵點進行批量圖檔中人臉對齊操作
"""
import os
import sys
import dlib
import logging 
import time
import numpy as np
from cv2 import cv2 as cv2

 
def logset():
    #設定日志格式
    logging.basicConfig(level=logging.INFO, format='%(asctime)s -%(filename)s:%(lineno)d - %(levelname)s - %(message)s')
    

def load_model():
    '''
    1. 加載需要對齊的人臉照片;
    2. 加載特征點檢測模型
    '''
    current_path = os.getcwd()
    logging.debug(current_path + '\n')
    model_path = current_path + '/main/dlib_model/shape_predictor_68_face_landmarks.dat'
    
    detector = dlib.get_frontal_face_detector()
    landmark = dlib.shape_predictor(model_path)
    logging.info('Landmark model load sucessed !!!')
    return detector, landmark


def face_aligniment(file_path, save_path):
    '''
    對檔案夾中的照片進行批量的人臉對齊操作
    '''
    logging.info('Begin to alignment faces !!!')
    imgs = os.listdir(file_path)
    for img in imgs:
        img_full_path = file_path + '/' + img
        bgr_imgs = cv2.imread(img_full_path)
        if bgr_imgs is None:
            logging.warn('Load pics failed !!! Please check file path !!!')
            exit()
        
        # 照片顔色通道轉換:dlib檢測的圖檔空間是RGB, cv2的顔色空間是BGR
        rgb_imgs = cv2.cvtColor(bgr_imgs, cv2.COLOR_BGR2RGB)
        face_location = detector(rgb_imgs, 1)
        if len(face_location) == 0:
            logging.warn('No face detected in pic: {}'.format(img_full_path))
            continue
        
        # 人臉關鍵點檢測
        face_keypoints = dlib.full_object_detections()
        for location in face_location:
            face_keypoints.append(landmark(rgb_imgs, location))
            
        # 人臉對齊
        alignmented_face = dlib.get_face_chips(rgb_imgs, face_keypoints, size=120)
        logging.info('Alignment face sucessed: {}'.format(img_full_path))
        # 儲存對齊後的人臉照片
        for image in alignmented_face:
            rgb_img = np.array(image).astype(np.uint8)
            bgr_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR)
            cv2.imwrite(save_path + str(img.split('.')[0]) + '.jpg', bgr_img)
        cv2.destroyAllWindows()


if __name__ == '__main__':
    logset()
    detector, landmark = load_model()
    save_path = 'aligmented/'
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    start = time.time()
    face_aligniment(file_path='./main/alignment', 
                                       save_path=save_path)
    end = time.time()
    logging.info('Operate Finished !!! Costed time:{} s'.format(end-start)) 
           

(ps: 使用代碼時,隻需要修改需要對齊操作的人臉照片路徑、照片存儲路徑以及68_points模型的路徑即可)

對齊效果圖展示:

  • 原圖
    人臉對齊--采用dlib庫的68_face_landmark進行人臉對齊操作
  • 對齊後的人臉
    人臉對齊--采用dlib庫的68_face_landmark進行人臉對齊操作

繼續閱讀