Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Face-Recognition-with-ArcFace/align/align_trans.py
3142 views
1
import numpy as np
2
import cv2
3
from align.matlab_cp2tform import get_similarity_transform_for_cv2
4
5
6
# reference facial points, a list of coordinates (x,y)
7
REFERENCE_FACIAL_POINTS = [ # default reference facial points for crop_size = (112, 112); should adjust REFERENCE_FACIAL_POINTS accordingly for other crop_size
8
[30.29459953, 51.69630051],
9
[65.53179932, 51.50139999],
10
[48.02519989, 71.73660278],
11
[33.54930115, 92.3655014],
12
[62.72990036, 92.20410156]
13
]
14
15
DEFAULT_CROP_SIZE = (96, 112)
16
17
18
class FaceWarpException(Exception):
19
def __str__(self):
20
return 'In File {}:{}'.format(
21
__file__, super.__str__(self))
22
23
24
def get_reference_facial_points(output_size = None,
25
inner_padding_factor = 0.0,
26
outer_padding=(0, 0),
27
default_square = False):
28
"""
29
Function:
30
----------
31
get reference 5 key points according to crop settings:
32
0. Set default crop_size:
33
if default_square:
34
crop_size = (112, 112)
35
else:
36
crop_size = (96, 112)
37
1. Pad the crop_size by inner_padding_factor in each side;
38
2. Resize crop_size into (output_size - outer_padding*2),
39
pad into output_size with outer_padding;
40
3. Output reference_5point;
41
Parameters:
42
----------
43
@output_size: (w, h) or None
44
size of aligned face image
45
@inner_padding_factor: (w_factor, h_factor)
46
padding factor for inner (w, h)
47
@outer_padding: (w_pad, h_pad)
48
each row is a pair of coordinates (x, y)
49
@default_square: True or False
50
if True:
51
default crop_size = (112, 112)
52
else:
53
default crop_size = (96, 112);
54
!!! make sure, if output_size is not None:
55
(output_size - outer_padding)
56
= some_scale * (default crop_size * (1.0 + inner_padding_factor))
57
Returns:
58
----------
59
@reference_5point: 5x2 np.array
60
each row is a pair of transformed coordinates (x, y)
61
"""
62
#print('\n===> get_reference_facial_points():')
63
64
#print('---> Params:')
65
#print(' output_size: ', output_size)
66
#print(' inner_padding_factor: ', inner_padding_factor)
67
#print(' outer_padding:', outer_padding)
68
#print(' default_square: ', default_square)
69
70
tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
71
tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
72
73
# 0) make the inner region a square
74
if default_square:
75
size_diff = max(tmp_crop_size) - tmp_crop_size
76
tmp_5pts += size_diff / 2
77
tmp_crop_size += size_diff
78
79
#print('---> default:')
80
#print(' crop_size = ', tmp_crop_size)
81
#print(' reference_5pts = ', tmp_5pts)
82
83
if (output_size and
84
output_size[0] == tmp_crop_size[0] and
85
output_size[1] == tmp_crop_size[1]):
86
#print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size))
87
return tmp_5pts
88
89
if (inner_padding_factor == 0 and
90
outer_padding == (0, 0)):
91
if output_size is None:
92
#print('No paddings to do: return default reference points')
93
return tmp_5pts
94
else:
95
raise FaceWarpException(
96
'No paddings to do, output_size must be None or {}'.format(tmp_crop_size))
97
98
# check output size
99
if not (0 <= inner_padding_factor <= 1.0):
100
raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)')
101
102
if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0)
103
and output_size is None):
104
output_size = tmp_crop_size * \
105
(1 + inner_padding_factor * 2).astype(np.int32)
106
output_size += np.array(outer_padding)
107
#print(' deduced from paddings, output_size = ', output_size)
108
109
if not (outer_padding[0] < output_size[0]
110
and outer_padding[1] < output_size[1]):
111
raise FaceWarpException('Not (outer_padding[0] < output_size[0]'
112
'and outer_padding[1] < output_size[1])')
113
114
# 1) pad the inner region according inner_padding_factor
115
#print('---> STEP1: pad the inner region according inner_padding_factor')
116
if inner_padding_factor > 0:
117
size_diff = tmp_crop_size * inner_padding_factor * 2
118
tmp_5pts += size_diff / 2
119
tmp_crop_size += np.round(size_diff).astype(np.int32)
120
121
#print(' crop_size = ', tmp_crop_size)
122
#print(' reference_5pts = ', tmp_5pts)
123
124
# 2) resize the padded inner region
125
#print('---> STEP2: resize the padded inner region')
126
size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2
127
#print(' crop_size = ', tmp_crop_size)
128
#print(' size_bf_outer_pad = ', size_bf_outer_pad)
129
130
if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]:
131
raise FaceWarpException('Must have (output_size - outer_padding)'
132
'= some_scale * (crop_size * (1.0 + inner_padding_factor)')
133
134
scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]
135
#print(' resize scale_factor = ', scale_factor)
136
tmp_5pts = tmp_5pts * scale_factor
137
# size_diff = tmp_crop_size * (scale_factor - min(scale_factor))
138
# tmp_5pts = tmp_5pts + size_diff / 2
139
tmp_crop_size = size_bf_outer_pad
140
#print(' crop_size = ', tmp_crop_size)
141
#print(' reference_5pts = ', tmp_5pts)
142
143
# 3) add outer_padding to make output_size
144
reference_5point = tmp_5pts + np.array(outer_padding)
145
tmp_crop_size = output_size
146
#print('---> STEP3: add outer_padding to make output_size')
147
#print(' crop_size = ', tmp_crop_size)
148
#print(' reference_5pts = ', tmp_5pts)
149
150
#print('===> end get_reference_facial_points\n')
151
152
return reference_5point
153
154
155
def get_affine_transform_matrix(src_pts, dst_pts):
156
"""
157
Function:
158
----------
159
get affine transform matrix 'tfm' from src_pts to dst_pts
160
Parameters:
161
----------
162
@src_pts: Kx2 np.array
163
source points matrix, each row is a pair of coordinates (x, y)
164
@dst_pts: Kx2 np.array
165
destination points matrix, each row is a pair of coordinates (x, y)
166
Returns:
167
----------
168
@tfm: 2x3 np.array
169
transform matrix from src_pts to dst_pts
170
"""
171
172
tfm = np.float32([[1, 0, 0], [0, 1, 0]])
173
n_pts = src_pts.shape[0]
174
ones = np.ones((n_pts, 1), src_pts.dtype)
175
src_pts_ = np.hstack([src_pts, ones])
176
dst_pts_ = np.hstack([dst_pts, ones])
177
178
# #print(('src_pts_:\n' + str(src_pts_))
179
# #print(('dst_pts_:\n' + str(dst_pts_))
180
181
A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)
182
183
# #print(('np.linalg.lstsq return A: \n' + str(A))
184
# #print(('np.linalg.lstsq return res: \n' + str(res))
185
# #print(('np.linalg.lstsq return rank: \n' + str(rank))
186
# #print(('np.linalg.lstsq return s: \n' + str(s))
187
188
if rank == 3:
189
tfm = np.float32([
190
[A[0, 0], A[1, 0], A[2, 0]],
191
[A[0, 1], A[1, 1], A[2, 1]]
192
])
193
elif rank == 2:
194
tfm = np.float32([
195
[A[0, 0], A[1, 0], 0],
196
[A[0, 1], A[1, 1], 0]
197
])
198
199
return tfm
200
201
202
def warp_and_crop_face(src_img,
203
facial_pts,
204
reference_pts = None,
205
crop_size=(96, 112),
206
align_type = 'smilarity'):
207
"""
208
Function:
209
----------
210
apply affine transform 'trans' to uv
211
Parameters:
212
----------
213
@src_img: 3x3 np.array
214
input image
215
@facial_pts: could be
216
1)a list of K coordinates (x,y)
217
or
218
2) Kx2 or 2xK np.array
219
each row or col is a pair of coordinates (x, y)
220
@reference_pts: could be
221
1) a list of K coordinates (x,y)
222
or
223
2) Kx2 or 2xK np.array
224
each row or col is a pair of coordinates (x, y)
225
or
226
3) None
227
if None, use default reference facial points
228
@crop_size: (w, h)
229
output face image size
230
@align_type: transform type, could be one of
231
1) 'similarity': use similarity transform
232
2) 'cv2_affine': use the first 3 points to do affine transform,
233
by calling cv2.getAffineTransform()
234
3) 'affine': use all points to do affine transform
235
Returns:
236
----------
237
@face_img: output face image with size (w, h) = @crop_size
238
"""
239
240
if reference_pts is None:
241
if crop_size[0] == 96 and crop_size[1] == 112:
242
reference_pts = REFERENCE_FACIAL_POINTS
243
else:
244
default_square = False
245
inner_padding_factor = 0
246
outer_padding = (0, 0)
247
output_size = crop_size
248
249
reference_pts = get_reference_facial_points(output_size,
250
inner_padding_factor,
251
outer_padding,
252
default_square)
253
254
ref_pts = np.float32(reference_pts)
255
ref_pts_shp = ref_pts.shape
256
if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:
257
raise FaceWarpException(
258
'reference_pts.shape must be (K,2) or (2,K) and K>2')
259
260
if ref_pts_shp[0] == 2:
261
ref_pts = ref_pts.T
262
263
src_pts = np.float32(facial_pts)
264
src_pts_shp = src_pts.shape
265
if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:
266
raise FaceWarpException(
267
'facial_pts.shape must be (K,2) or (2,K) and K>2')
268
269
if src_pts_shp[0] == 2:
270
src_pts = src_pts.T
271
272
# #print('--->src_pts:\n', src_pts
273
# #print('--->ref_pts\n', ref_pts
274
275
if src_pts.shape != ref_pts.shape:
276
raise FaceWarpException(
277
'facial_pts and reference_pts must have the same shape')
278
279
if align_type is 'cv2_affine':
280
tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])
281
# #print(('cv2.getAffineTransform() returns tfm=\n' + str(tfm))
282
elif align_type is 'affine':
283
tfm = get_affine_transform_matrix(src_pts, ref_pts)
284
# #print(('get_affine_transform_matrix() returns tfm=\n' + str(tfm))
285
else:
286
tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)
287
# #print(('get_similarity_transform_for_cv2() returns tfm=\n' + str(tfm))
288
289
# #print('--->Transform matrix: '
290
# #print(('type(tfm):' + str(type(tfm)))
291
# #print(('tfm.dtype:' + str(tfm.dtype))
292
# #print( tfm
293
294
face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))
295
296
return face_img
297