人臉識別-利用相似性變換將人臉對齊

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "wxf"
# Email: [email protected]
# Date: 2018/8/20

# ****目前還有問題:變換後存在不正常拉伸問題,是否是正常現象還需要再分析

# 利用相似性變換將人臉對齊
import os
import cv2
import numpy as np


def mkr(dr):
    if not os.path.exists(dr):
        os.mkdir(dr)

file_dir_base = 'G:/wxf/deep_Learn/sphereface/train/data/'
data_set = 'lfw'
data_set_files = file_dir_base + data_set + '_process.txt'

# ---對齊設置---
# 樣本大小,裁剪大小
# crop_img_size = (96, 112)
crop_img_size = (150, 150)
# 矯正目標 眼睛兩個點,鼻子一個點,嘴兩個點
coord5point = np.float32([[30.2946, 51.6963],
                          [65.5318, 51.5014],
                          [48.0252, 71.7366],
                          [33.5493, 92.3655],
                          [62.7299, 92.2041]])
# 矯正目標 眼睛兩個點,嘴兩個點 getPerspectiveTransform 函數只支持4點的,因此只能用這個了
coord4point = np.float32([[30.2946, 51.6963],
                          [65.5318, 51.5014],
                          [33.5493, 92.3655],
                          [62.7299, 92.2041]])

with open(data_set_files, 'r') as f:
    dataList = f.readlines()

for img_roi_pts in dataList:
    img_roi_pts = img_roi_pts.strip().split(' ')
    img_path = img_roi_pts[0]
    filename = os.path.basename(img_path)  # 文件名
    filepath = os.path.dirname(img_path)  # 文件路徑
    filepath = filepath.replace(data_set, data_set+'-112X96')

    img = cv2.imread(img_path)

    face_num = int(img_roi_pts[1])
    for i in range(face_num):
        offset = i * 14  # roi + pts = 7個點 故偏移量爲14
        face_roi = img_roi_pts[2+offset:6+offset]
        face_landmarks = img_roi_pts[6+offset:16+offset]

        face_roi = map(int, face_roi)
        face_landmarks = map(int, face_landmarks)

        pts4 = np.float32([[face_landmarks[0], face_landmarks[1]],
                           [face_landmarks[2], face_landmarks[3]],
                           [face_landmarks[6], face_landmarks[7]],
                           [face_landmarks[8], face_landmarks[9]]])

        M = cv2.getPerspectiveTransform(pts4, coord4point)
        res = cv2.warpPerspective(img, M, crop_img_size)
        mkr(filepath)

        cv2.imwrite(os.path.join(filepath, filename), res)
        cv2.waitKey(1)

        cv2.rectangle(img, (face_roi[0], face_roi[1]), (face_roi[2], face_roi[3]), (0, 0, 255), 3)
        cv2.circle(img, (face_landmarks[0], face_landmarks[1]), 2, (255, 0, 0), -1)
        cv2.circle(img, (face_landmarks[2], face_landmarks[3]), 2, (255, 0, 0), -1)
        cv2.circle(img, (face_landmarks[6], face_landmarks[7]), 2, (255, 0, 0), -1)
        cv2.circle(img, (face_landmarks[8], face_landmarks[9]), 2, (255, 0, 0), -1)
        cv2.imshow("res", res)
        cv2.imshow("img", img)
        cv2.waitKey(0)
    pass
pass
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章