人脸识别-利用相似性变换将人脸对齐

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "wxf"
# Email: yingxiongmowenchuchu@126.com
# 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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值