Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

FANExtractor.py 10 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
  1. import os
  2. import traceback
  3. from pathlib import Path
  4. import cv2
  5. import numpy as np
  6. from numpy import linalg as npla
  7. from facelib import FaceType, LandmarksProcessor
  8. from core.leras import nn
  9. """
  10. ported from https://github.com/1adrianb/face-alignment
  11. """
  12. class FANExtractor(object):
  13. def __init__ (self, landmarks_3D=False, place_model_on_cpu=False):
  14. model_path = Path(__file__).parent / ( "2DFAN.npy" if not landmarks_3D else "3DFAN.npy")
  15. if not model_path.exists():
  16. raise Exception("Unable to load FANExtractor model")
  17. nn.initialize(data_format="NHWC")
  18. tf = nn.tf
  19. class ConvBlock(nn.ModelBase):
  20. def on_build(self, in_planes, out_planes):
  21. self.in_planes = in_planes
  22. self.out_planes = out_planes
  23. self.bn1 = nn.BatchNorm2D(in_planes)
  24. self.conv1 = nn.Conv2D (in_planes, out_planes//2, kernel_size=3, strides=1, padding='SAME', use_bias=False )
  25. self.bn2 = nn.BatchNorm2D(out_planes//2)
  26. self.conv2 = nn.Conv2D (out_planes//2, out_planes//4, kernel_size=3, strides=1, padding='SAME', use_bias=False )
  27. self.bn3 = nn.BatchNorm2D(out_planes//4)
  28. self.conv3 = nn.Conv2D (out_planes//4, out_planes//4, kernel_size=3, strides=1, padding='SAME', use_bias=False )
  29. if self.in_planes != self.out_planes:
  30. self.down_bn1 = nn.BatchNorm2D(in_planes)
  31. self.down_conv1 = nn.Conv2D (in_planes, out_planes, kernel_size=1, strides=1, padding='VALID', use_bias=False )
  32. else:
  33. self.down_bn1 = None
  34. self.down_conv1 = None
  35. def forward(self, input):
  36. x = input
  37. x = self.bn1(x)
  38. x = tf.nn.relu(x)
  39. x = out1 = self.conv1(x)
  40. x = self.bn2(x)
  41. x = tf.nn.relu(x)
  42. x = out2 = self.conv2(x)
  43. x = self.bn3(x)
  44. x = tf.nn.relu(x)
  45. x = out3 = self.conv3(x)
  46. x = tf.concat ([out1, out2, out3], axis=-1)
  47. if self.in_planes != self.out_planes:
  48. downsample = self.down_bn1(input)
  49. downsample = tf.nn.relu (downsample)
  50. downsample = self.down_conv1 (downsample)
  51. x = x + downsample
  52. else:
  53. x = x + input
  54. return x
  55. class HourGlass (nn.ModelBase):
  56. def on_build(self, in_planes, depth):
  57. self.b1 = ConvBlock (in_planes, 256)
  58. self.b2 = ConvBlock (in_planes, 256)
  59. if depth > 1:
  60. self.b2_plus = HourGlass(256, depth-1)
  61. else:
  62. self.b2_plus = ConvBlock(256, 256)
  63. self.b3 = ConvBlock(256, 256)
  64. def forward(self, input):
  65. up1 = self.b1(input)
  66. low1 = tf.nn.avg_pool(input, [1,2,2,1], [1,2,2,1], 'VALID')
  67. low1 = self.b2 (low1)
  68. low2 = self.b2_plus(low1)
  69. low3 = self.b3(low2)
  70. up2 = nn.upsample2d(low3)
  71. return up1+up2
  72. class FAN (nn.ModelBase):
  73. def __init__(self):
  74. super().__init__(name='FAN')
  75. def on_build(self):
  76. self.conv1 = nn.Conv2D (3, 64, kernel_size=7, strides=2, padding='SAME')
  77. self.bn1 = nn.BatchNorm2D(64)
  78. self.conv2 = ConvBlock(64, 128)
  79. self.conv3 = ConvBlock(128, 128)
  80. self.conv4 = ConvBlock(128, 256)
  81. self.m = []
  82. self.top_m = []
  83. self.conv_last = []
  84. self.bn_end = []
  85. self.l = []
  86. self.bl = []
  87. self.al = []
  88. for i in range(4):
  89. self.m += [ HourGlass(256, 4) ]
  90. self.top_m += [ ConvBlock(256, 256) ]
  91. self.conv_last += [ nn.Conv2D (256, 256, kernel_size=1, strides=1, padding='VALID') ]
  92. self.bn_end += [ nn.BatchNorm2D(256) ]
  93. self.l += [ nn.Conv2D (256, 68, kernel_size=1, strides=1, padding='VALID') ]
  94. if i < 4-1:
  95. self.bl += [ nn.Conv2D (256, 256, kernel_size=1, strides=1, padding='VALID') ]
  96. self.al += [ nn.Conv2D (68, 256, kernel_size=1, strides=1, padding='VALID') ]
  97. def forward(self, inp) :
  98. x, = inp
  99. x = self.conv1(x)
  100. x = self.bn1(x)
  101. x = tf.nn.relu(x)
  102. x = self.conv2(x)
  103. x = tf.nn.avg_pool(x, [1,2,2,1], [1,2,2,1], 'VALID')
  104. x = self.conv3(x)
  105. x = self.conv4(x)
  106. outputs = []
  107. previous = x
  108. for i in range(4):
  109. ll = self.m[i] (previous)
  110. ll = self.top_m[i] (ll)
  111. ll = self.conv_last[i] (ll)
  112. ll = self.bn_end[i] (ll)
  113. ll = tf.nn.relu(ll)
  114. tmp_out = self.l[i](ll)
  115. outputs.append(tmp_out)
  116. if i < 4 - 1:
  117. ll = self.bl[i](ll)
  118. previous = previous + ll + self.al[i](tmp_out)
  119. x = outputs[-1]
  120. x = tf.transpose(x, (0,3,1,2) )
  121. return x
  122. e = None
  123. if place_model_on_cpu:
  124. e = tf.device("/CPU:0")
  125. if e is not None: e.__enter__()
  126. self.model = FAN()
  127. self.model.load_weights(str(model_path))
  128. if e is not None: e.__exit__(None,None,None)
  129. self.model.build_for_run ([ ( tf.float32, (None,256,256,3) ) ])
  130. def extract (self, input_image, rects, second_pass_extractor=None, is_bgr=True, multi_sample=False):
  131. if len(rects) == 0:
  132. return []
  133. if is_bgr:
  134. input_image = input_image[:,:,::-1]
  135. is_bgr = False
  136. (h, w, ch) = input_image.shape
  137. landmarks = []
  138. for (left, top, right, bottom) in rects:
  139. scale = (right - left + bottom - top) / 195.0
  140. center = np.array( [ (left + right) / 2.0, (top + bottom) / 2.0] )
  141. centers = [ center ]
  142. if multi_sample:
  143. centers += [ center + [-1,-1],
  144. center + [1,-1],
  145. center + [1,1],
  146. center + [-1,1],
  147. ]
  148. images = []
  149. ptss = []
  150. try:
  151. for c in centers:
  152. images += [ self.crop(input_image, c, scale) ]
  153. images = np.stack (images)
  154. images = images.astype(np.float32) / 255.0
  155. predicted = []
  156. for i in range( len(images) ):
  157. predicted += [ self.model.run ( [ images[i][None,...] ] )[0] ]
  158. predicted = np.stack(predicted)
  159. for i, pred in enumerate(predicted):
  160. ptss += [ self.get_pts_from_predict ( pred, centers[i], scale) ]
  161. pts_img = np.mean ( np.array(ptss), 0 )
  162. landmarks.append (pts_img)
  163. except:
  164. landmarks.append (None)
  165. if second_pass_extractor is not None:
  166. for i, lmrks in enumerate(landmarks):
  167. try:
  168. if lmrks is not None:
  169. image_to_face_mat = LandmarksProcessor.get_transform_mat (lmrks, 256, FaceType.FULL)
  170. face_image = cv2.warpAffine(input_image, image_to_face_mat, (256, 256), cv2.INTER_CUBIC )
  171. rects2 = second_pass_extractor.extract(face_image, is_bgr=is_bgr)
  172. if len(rects2) == 1: #dont do second pass if faces != 1 detected in cropped image
  173. lmrks2 = self.extract (face_image, [ rects2[0] ], is_bgr=is_bgr, multi_sample=True)[0]
  174. landmarks[i] = LandmarksProcessor.transform_points (lmrks2, image_to_face_mat, True)
  175. except:
  176. pass
  177. return landmarks
  178. def transform(self, point, center, scale, resolution):
  179. pt = np.array ( [point[0], point[1], 1.0] )
  180. h = 200.0 * scale
  181. m = np.eye(3)
  182. m[0,0] = resolution / h
  183. m[1,1] = resolution / h
  184. m[0,2] = resolution * ( -center[0] / h + 0.5 )
  185. m[1,2] = resolution * ( -center[1] / h + 0.5 )
  186. m = np.linalg.inv(m)
  187. return np.matmul (m, pt)[0:2]
  188. def crop(self, image, center, scale, resolution=256.0):
  189. ul = self.transform([1, 1], center, scale, resolution).astype( np.int )
  190. br = self.transform([resolution, resolution], center, scale, resolution).astype( np.int )
  191. if image.ndim > 2:
  192. newDim = np.array([br[1] - ul[1], br[0] - ul[0], image.shape[2]], dtype=np.int32)
  193. newImg = np.zeros(newDim, dtype=np.uint8)
  194. else:
  195. newDim = np.array([br[1] - ul[1], br[0] - ul[0]], dtype=np.int)
  196. newImg = np.zeros(newDim, dtype=np.uint8)
  197. ht = image.shape[0]
  198. wd = image.shape[1]
  199. newX = np.array([max(1, -ul[0] + 1), min(br[0], wd) - ul[0]], dtype=np.int32)
  200. newY = np.array([max(1, -ul[1] + 1), min(br[1], ht) - ul[1]], dtype=np.int32)
  201. oldX = np.array([max(1, ul[0] + 1), min(br[0], wd)], dtype=np.int32)
  202. oldY = np.array([max(1, ul[1] + 1), min(br[1], ht)], dtype=np.int32)
  203. newImg[newY[0] - 1:newY[1], newX[0] - 1:newX[1] ] = image[oldY[0] - 1:oldY[1], oldX[0] - 1:oldX[1], :]
  204. newImg = cv2.resize(newImg, dsize=(int(resolution), int(resolution)), interpolation=cv2.INTER_LINEAR)
  205. return newImg
  206. def get_pts_from_predict(self, a, center, scale):
  207. a_ch, a_h, a_w = a.shape
  208. b = a.reshape ( (a_ch, a_h*a_w) )
  209. c = b.argmax(1).reshape ( (a_ch, 1) ).repeat(2, axis=1).astype(np.float)
  210. c[:,0] %= a_w
  211. c[:,1] = np.apply_along_axis ( lambda x: np.floor(x / a_w), 0, c[:,1] )
  212. for i in range(a_ch):
  213. pX, pY = int(c[i,0]), int(c[i,1])
  214. if pX > 0 and pX < 63 and pY > 0 and pY < 63:
  215. diff = np.array ( [a[i,pY,pX+1]-a[i,pY,pX-1], a[i,pY+1,pX]-a[i,pY-1,pX]] )
  216. c[i] += np.sign(diff)*0.25
  217. c += 0.5
  218. return np.array( [ self.transform (c[i], center, scale, a_w) for i in range(a_ch) ] )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...