Path: blob/master/Face-Recognition-with-ArcFace/align/align_trans.py
3142 views
import numpy as np1import cv22from align.matlab_cp2tform import get_similarity_transform_for_cv2345# reference facial points, a list of coordinates (x,y)6REFERENCE_FACIAL_POINTS = [ # default reference facial points for crop_size = (112, 112); should adjust REFERENCE_FACIAL_POINTS accordingly for other crop_size7[30.29459953, 51.69630051],8[65.53179932, 51.50139999],9[48.02519989, 71.73660278],10[33.54930115, 92.3655014],11[62.72990036, 92.20410156]12]1314DEFAULT_CROP_SIZE = (96, 112)151617class FaceWarpException(Exception):18def __str__(self):19return 'In File {}:{}'.format(20__file__, super.__str__(self))212223def get_reference_facial_points(output_size = None,24inner_padding_factor = 0.0,25outer_padding=(0, 0),26default_square = False):27"""28Function:29----------30get reference 5 key points according to crop settings:310. Set default crop_size:32if default_square:33crop_size = (112, 112)34else:35crop_size = (96, 112)361. Pad the crop_size by inner_padding_factor in each side;372. Resize crop_size into (output_size - outer_padding*2),38pad into output_size with outer_padding;393. Output reference_5point;40Parameters:41----------42@output_size: (w, h) or None43size of aligned face image44@inner_padding_factor: (w_factor, h_factor)45padding factor for inner (w, h)46@outer_padding: (w_pad, h_pad)47each row is a pair of coordinates (x, y)48@default_square: True or False49if True:50default crop_size = (112, 112)51else:52default crop_size = (96, 112);53!!! make sure, if output_size is not None:54(output_size - outer_padding)55= some_scale * (default crop_size * (1.0 + inner_padding_factor))56Returns:57----------58@reference_5point: 5x2 np.array59each row is a pair of transformed coordinates (x, y)60"""61#print('\n===> get_reference_facial_points():')6263#print('---> Params:')64#print(' output_size: ', output_size)65#print(' inner_padding_factor: ', inner_padding_factor)66#print(' outer_padding:', outer_padding)67#print(' default_square: ', default_square)6869tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)70tmp_crop_size = np.array(DEFAULT_CROP_SIZE)7172# 0) make the inner region a square73if default_square:74size_diff = max(tmp_crop_size) - tmp_crop_size75tmp_5pts += size_diff / 276tmp_crop_size += size_diff7778#print('---> default:')79#print(' crop_size = ', tmp_crop_size)80#print(' reference_5pts = ', tmp_5pts)8182if (output_size and83output_size[0] == tmp_crop_size[0] and84output_size[1] == tmp_crop_size[1]):85#print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size))86return tmp_5pts8788if (inner_padding_factor == 0 and89outer_padding == (0, 0)):90if output_size is None:91#print('No paddings to do: return default reference points')92return tmp_5pts93else:94raise FaceWarpException(95'No paddings to do, output_size must be None or {}'.format(tmp_crop_size))9697# check output size98if not (0 <= inner_padding_factor <= 1.0):99raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)')100101if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0)102and output_size is None):103output_size = tmp_crop_size * \104(1 + inner_padding_factor * 2).astype(np.int32)105output_size += np.array(outer_padding)106#print(' deduced from paddings, output_size = ', output_size)107108if not (outer_padding[0] < output_size[0]109and outer_padding[1] < output_size[1]):110raise FaceWarpException('Not (outer_padding[0] < output_size[0]'111'and outer_padding[1] < output_size[1])')112113# 1) pad the inner region according inner_padding_factor114#print('---> STEP1: pad the inner region according inner_padding_factor')115if inner_padding_factor > 0:116size_diff = tmp_crop_size * inner_padding_factor * 2117tmp_5pts += size_diff / 2118tmp_crop_size += np.round(size_diff).astype(np.int32)119120#print(' crop_size = ', tmp_crop_size)121#print(' reference_5pts = ', tmp_5pts)122123# 2) resize the padded inner region124#print('---> STEP2: resize the padded inner region')125size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2126#print(' crop_size = ', tmp_crop_size)127#print(' size_bf_outer_pad = ', size_bf_outer_pad)128129if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]:130raise FaceWarpException('Must have (output_size - outer_padding)'131'= some_scale * (crop_size * (1.0 + inner_padding_factor)')132133scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]134#print(' resize scale_factor = ', scale_factor)135tmp_5pts = tmp_5pts * scale_factor136# size_diff = tmp_crop_size * (scale_factor - min(scale_factor))137# tmp_5pts = tmp_5pts + size_diff / 2138tmp_crop_size = size_bf_outer_pad139#print(' crop_size = ', tmp_crop_size)140#print(' reference_5pts = ', tmp_5pts)141142# 3) add outer_padding to make output_size143reference_5point = tmp_5pts + np.array(outer_padding)144tmp_crop_size = output_size145#print('---> STEP3: add outer_padding to make output_size')146#print(' crop_size = ', tmp_crop_size)147#print(' reference_5pts = ', tmp_5pts)148149#print('===> end get_reference_facial_points\n')150151return reference_5point152153154def get_affine_transform_matrix(src_pts, dst_pts):155"""156Function:157----------158get affine transform matrix 'tfm' from src_pts to dst_pts159Parameters:160----------161@src_pts: Kx2 np.array162source points matrix, each row is a pair of coordinates (x, y)163@dst_pts: Kx2 np.array164destination points matrix, each row is a pair of coordinates (x, y)165Returns:166----------167@tfm: 2x3 np.array168transform matrix from src_pts to dst_pts169"""170171tfm = np.float32([[1, 0, 0], [0, 1, 0]])172n_pts = src_pts.shape[0]173ones = np.ones((n_pts, 1), src_pts.dtype)174src_pts_ = np.hstack([src_pts, ones])175dst_pts_ = np.hstack([dst_pts, ones])176177# #print(('src_pts_:\n' + str(src_pts_))178# #print(('dst_pts_:\n' + str(dst_pts_))179180A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)181182# #print(('np.linalg.lstsq return A: \n' + str(A))183# #print(('np.linalg.lstsq return res: \n' + str(res))184# #print(('np.linalg.lstsq return rank: \n' + str(rank))185# #print(('np.linalg.lstsq return s: \n' + str(s))186187if rank == 3:188tfm = np.float32([189[A[0, 0], A[1, 0], A[2, 0]],190[A[0, 1], A[1, 1], A[2, 1]]191])192elif rank == 2:193tfm = np.float32([194[A[0, 0], A[1, 0], 0],195[A[0, 1], A[1, 1], 0]196])197198return tfm199200201def warp_and_crop_face(src_img,202facial_pts,203reference_pts = None,204crop_size=(96, 112),205align_type = 'smilarity'):206"""207Function:208----------209apply affine transform 'trans' to uv210Parameters:211----------212@src_img: 3x3 np.array213input image214@facial_pts: could be2151)a list of K coordinates (x,y)216or2172) Kx2 or 2xK np.array218each row or col is a pair of coordinates (x, y)219@reference_pts: could be2201) a list of K coordinates (x,y)221or2222) Kx2 or 2xK np.array223each row or col is a pair of coordinates (x, y)224or2253) None226if None, use default reference facial points227@crop_size: (w, h)228output face image size229@align_type: transform type, could be one of2301) 'similarity': use similarity transform2312) 'cv2_affine': use the first 3 points to do affine transform,232by calling cv2.getAffineTransform()2333) 'affine': use all points to do affine transform234Returns:235----------236@face_img: output face image with size (w, h) = @crop_size237"""238239if reference_pts is None:240if crop_size[0] == 96 and crop_size[1] == 112:241reference_pts = REFERENCE_FACIAL_POINTS242else:243default_square = False244inner_padding_factor = 0245outer_padding = (0, 0)246output_size = crop_size247248reference_pts = get_reference_facial_points(output_size,249inner_padding_factor,250outer_padding,251default_square)252253ref_pts = np.float32(reference_pts)254ref_pts_shp = ref_pts.shape255if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:256raise FaceWarpException(257'reference_pts.shape must be (K,2) or (2,K) and K>2')258259if ref_pts_shp[0] == 2:260ref_pts = ref_pts.T261262src_pts = np.float32(facial_pts)263src_pts_shp = src_pts.shape264if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:265raise FaceWarpException(266'facial_pts.shape must be (K,2) or (2,K) and K>2')267268if src_pts_shp[0] == 2:269src_pts = src_pts.T270271# #print('--->src_pts:\n', src_pts272# #print('--->ref_pts\n', ref_pts273274if src_pts.shape != ref_pts.shape:275raise FaceWarpException(276'facial_pts and reference_pts must have the same shape')277278if align_type is 'cv2_affine':279tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])280# #print(('cv2.getAffineTransform() returns tfm=\n' + str(tfm))281elif align_type is 'affine':282tfm = get_affine_transform_matrix(src_pts, ref_pts)283# #print(('get_affine_transform_matrix() returns tfm=\n' + str(tfm))284else:285tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)286# #print(('get_similarity_transform_for_cv2() returns tfm=\n' + str(tfm))287288# #print('--->Transform matrix: '289# #print(('type(tfm):' + str(type(tfm)))290# #print(('tfm.dtype:' + str(tfm.dtype))291# #print( tfm292293face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))294295return face_img296297