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

S3FDExtractor.py 11 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
  1. import operator
  2. from pathlib import Path
  3. import cv2
  4. import numpy as np
  5. from core.leras import nn
  6. class S3FDExtractor(object):
  7. def __init__(self, place_model_on_cpu=False):
  8. nn.initialize(data_format="NHWC")
  9. tf = nn.tf
  10. model_path = Path(__file__).parent / "S3FD.npy"
  11. if not model_path.exists():
  12. raise Exception("Unable to load S3FD.npy")
  13. class L2Norm(nn.LayerBase):
  14. def __init__(self, n_channels, **kwargs):
  15. self.n_channels = n_channels
  16. super().__init__(**kwargs)
  17. def build_weights(self):
  18. self.weight = tf.get_variable ("weight", (1, 1, 1, self.n_channels), dtype=nn.floatx, initializer=tf.initializers.ones )
  19. def get_weights(self):
  20. return [self.weight]
  21. def __call__(self, inputs):
  22. x = inputs
  23. x = x / (tf.sqrt( tf.reduce_sum( tf.pow(x, 2), axis=-1, keepdims=True ) ) + 1e-10) * self.weight
  24. return x
  25. class S3FD(nn.ModelBase):
  26. def __init__(self):
  27. super().__init__(name='S3FD')
  28. def on_build(self):
  29. self.minus = tf.constant([104,117,123], dtype=nn.floatx )
  30. self.conv1_1 = nn.Conv2D(3, 64, kernel_size=3, strides=1, padding='SAME')
  31. self.conv1_2 = nn.Conv2D(64, 64, kernel_size=3, strides=1, padding='SAME')
  32. self.conv2_1 = nn.Conv2D(64, 128, kernel_size=3, strides=1, padding='SAME')
  33. self.conv2_2 = nn.Conv2D(128, 128, kernel_size=3, strides=1, padding='SAME')
  34. self.conv3_1 = nn.Conv2D(128, 256, kernel_size=3, strides=1, padding='SAME')
  35. self.conv3_2 = nn.Conv2D(256, 256, kernel_size=3, strides=1, padding='SAME')
  36. self.conv3_3 = nn.Conv2D(256, 256, kernel_size=3, strides=1, padding='SAME')
  37. self.conv4_1 = nn.Conv2D(256, 512, kernel_size=3, strides=1, padding='SAME')
  38. self.conv4_2 = nn.Conv2D(512, 512, kernel_size=3, strides=1, padding='SAME')
  39. self.conv4_3 = nn.Conv2D(512, 512, kernel_size=3, strides=1, padding='SAME')
  40. self.conv5_1 = nn.Conv2D(512, 512, kernel_size=3, strides=1, padding='SAME')
  41. self.conv5_2 = nn.Conv2D(512, 512, kernel_size=3, strides=1, padding='SAME')
  42. self.conv5_3 = nn.Conv2D(512, 512, kernel_size=3, strides=1, padding='SAME')
  43. self.fc6 = nn.Conv2D(512, 1024, kernel_size=3, strides=1, padding=3)
  44. self.fc7 = nn.Conv2D(1024, 1024, kernel_size=1, strides=1, padding='SAME')
  45. self.conv6_1 = nn.Conv2D(1024, 256, kernel_size=1, strides=1, padding='SAME')
  46. self.conv6_2 = nn.Conv2D(256, 512, kernel_size=3, strides=2, padding='SAME')
  47. self.conv7_1 = nn.Conv2D(512, 128, kernel_size=1, strides=1, padding='SAME')
  48. self.conv7_2 = nn.Conv2D(128, 256, kernel_size=3, strides=2, padding='SAME')
  49. self.conv3_3_norm = L2Norm(256)
  50. self.conv4_3_norm = L2Norm(512)
  51. self.conv5_3_norm = L2Norm(512)
  52. self.conv3_3_norm_mbox_conf = nn.Conv2D(256, 4, kernel_size=3, strides=1, padding='SAME')
  53. self.conv3_3_norm_mbox_loc = nn.Conv2D(256, 4, kernel_size=3, strides=1, padding='SAME')
  54. self.conv4_3_norm_mbox_conf = nn.Conv2D(512, 2, kernel_size=3, strides=1, padding='SAME')
  55. self.conv4_3_norm_mbox_loc = nn.Conv2D(512, 4, kernel_size=3, strides=1, padding='SAME')
  56. self.conv5_3_norm_mbox_conf = nn.Conv2D(512, 2, kernel_size=3, strides=1, padding='SAME')
  57. self.conv5_3_norm_mbox_loc = nn.Conv2D(512, 4, kernel_size=3, strides=1, padding='SAME')
  58. self.fc7_mbox_conf = nn.Conv2D(1024, 2, kernel_size=3, strides=1, padding='SAME')
  59. self.fc7_mbox_loc = nn.Conv2D(1024, 4, kernel_size=3, strides=1, padding='SAME')
  60. self.conv6_2_mbox_conf = nn.Conv2D(512, 2, kernel_size=3, strides=1, padding='SAME')
  61. self.conv6_2_mbox_loc = nn.Conv2D(512, 4, kernel_size=3, strides=1, padding='SAME')
  62. self.conv7_2_mbox_conf = nn.Conv2D(256, 2, kernel_size=3, strides=1, padding='SAME')
  63. self.conv7_2_mbox_loc = nn.Conv2D(256, 4, kernel_size=3, strides=1, padding='SAME')
  64. def forward(self, inp):
  65. x, = inp
  66. x = x - self.minus
  67. x = tf.nn.relu(self.conv1_1(x))
  68. x = tf.nn.relu(self.conv1_2(x))
  69. x = tf.nn.max_pool(x, [1,2,2,1], [1,2,2,1], "VALID")
  70. x = tf.nn.relu(self.conv2_1(x))
  71. x = tf.nn.relu(self.conv2_2(x))
  72. x = tf.nn.max_pool(x, [1,2,2,1], [1,2,2,1], "VALID")
  73. x = tf.nn.relu(self.conv3_1(x))
  74. x = tf.nn.relu(self.conv3_2(x))
  75. x = tf.nn.relu(self.conv3_3(x))
  76. f3_3 = x
  77. x = tf.nn.max_pool(x, [1,2,2,1], [1,2,2,1], "VALID")
  78. x = tf.nn.relu(self.conv4_1(x))
  79. x = tf.nn.relu(self.conv4_2(x))
  80. x = tf.nn.relu(self.conv4_3(x))
  81. f4_3 = x
  82. x = tf.nn.max_pool(x, [1,2,2,1], [1,2,2,1], "VALID")
  83. x = tf.nn.relu(self.conv5_1(x))
  84. x = tf.nn.relu(self.conv5_2(x))
  85. x = tf.nn.relu(self.conv5_3(x))
  86. f5_3 = x
  87. x = tf.nn.max_pool(x, [1,2,2,1], [1,2,2,1], "VALID")
  88. x = tf.nn.relu(self.fc6(x))
  89. x = tf.nn.relu(self.fc7(x))
  90. ffc7 = x
  91. x = tf.nn.relu(self.conv6_1(x))
  92. x = tf.nn.relu(self.conv6_2(x))
  93. f6_2 = x
  94. x = tf.nn.relu(self.conv7_1(x))
  95. x = tf.nn.relu(self.conv7_2(x))
  96. f7_2 = x
  97. f3_3 = self.conv3_3_norm(f3_3)
  98. f4_3 = self.conv4_3_norm(f4_3)
  99. f5_3 = self.conv5_3_norm(f5_3)
  100. cls1 = self.conv3_3_norm_mbox_conf(f3_3)
  101. reg1 = self.conv3_3_norm_mbox_loc(f3_3)
  102. cls2 = tf.nn.softmax(self.conv4_3_norm_mbox_conf(f4_3))
  103. reg2 = self.conv4_3_norm_mbox_loc(f4_3)
  104. cls3 = tf.nn.softmax(self.conv5_3_norm_mbox_conf(f5_3))
  105. reg3 = self.conv5_3_norm_mbox_loc(f5_3)
  106. cls4 = tf.nn.softmax(self.fc7_mbox_conf(ffc7))
  107. reg4 = self.fc7_mbox_loc(ffc7)
  108. cls5 = tf.nn.softmax(self.conv6_2_mbox_conf(f6_2))
  109. reg5 = self.conv6_2_mbox_loc(f6_2)
  110. cls6 = tf.nn.softmax(self.conv7_2_mbox_conf(f7_2))
  111. reg6 = self.conv7_2_mbox_loc(f7_2)
  112. # max-out background label
  113. bmax = tf.maximum(tf.maximum(cls1[:,:,:,0:1], cls1[:,:,:,1:2]), cls1[:,:,:,2:3])
  114. cls1 = tf.concat ([bmax, cls1[:,:,:,3:4] ], axis=-1)
  115. cls1 = tf.nn.softmax(cls1)
  116. return [cls1, reg1, cls2, reg2, cls3, reg3, cls4, reg4, cls5, reg5, cls6, reg6]
  117. e = None
  118. if place_model_on_cpu:
  119. e = tf.device("/CPU:0")
  120. if e is not None: e.__enter__()
  121. self.model = S3FD()
  122. self.model.load_weights (model_path)
  123. if e is not None: e.__exit__(None,None,None)
  124. self.model.build_for_run ([ ( tf.float32, nn.get4Dshape (None,None,3) ) ])
  125. def __enter__(self):
  126. return self
  127. def __exit__(self, exc_type=None, exc_value=None, traceback=None):
  128. return False #pass exception between __enter__ and __exit__ to outter level
  129. def extract (self, input_image, is_bgr=True, is_remove_intersects=False):
  130. if is_bgr:
  131. input_image = input_image[:,:,::-1]
  132. is_bgr = False
  133. (h, w, ch) = input_image.shape
  134. d = max(w, h)
  135. scale_to = 640 if d >= 1280 else d / 2
  136. scale_to = max(64, scale_to)
  137. input_scale = d / scale_to
  138. input_image = cv2.resize (input_image, ( int(w/input_scale), int(h/input_scale) ), interpolation=cv2.INTER_LINEAR)
  139. olist = self.model.run ([ input_image[None,...] ] )
  140. detected_faces = []
  141. for ltrb in self.refine (olist):
  142. l,t,r,b = [ x*input_scale for x in ltrb]
  143. bt = b-t
  144. if min(r-l,bt) < 40: #filtering faces < 40pix by any side
  145. continue
  146. b += bt*0.1 #enlarging bottom line a bit for 2DFAN-4, because default is not enough covering a chin
  147. detected_faces.append ( [int(x) for x in (l,t,r,b) ] )
  148. #sort by largest area first
  149. detected_faces = [ [(l,t,r,b), (r-l)*(b-t) ] for (l,t,r,b) in detected_faces ]
  150. detected_faces = sorted(detected_faces, key=operator.itemgetter(1), reverse=True )
  151. detected_faces = [ x[0] for x in detected_faces]
  152. if is_remove_intersects:
  153. for i in range( len(detected_faces)-1, 0, -1):
  154. l1,t1,r1,b1 = detected_faces[i]
  155. l0,t0,r0,b0 = detected_faces[i-1]
  156. dx = min(r0, r1) - max(l0, l1)
  157. dy = min(b0, b1) - max(t0, t1)
  158. if (dx>=0) and (dy>=0):
  159. detected_faces.pop(i)
  160. return detected_faces
  161. def refine(self, olist):
  162. bboxlist = []
  163. for i, ((ocls,), (oreg,)) in enumerate ( zip ( olist[::2], olist[1::2] ) ):
  164. stride = 2**(i + 2) # 4,8,16,32,64,128
  165. s_d2 = stride / 2
  166. s_m4 = stride * 4
  167. for hindex, windex in zip(*np.where(ocls[...,1] > 0.05)):
  168. score = ocls[hindex, windex, 1]
  169. loc = oreg[hindex, windex, :]
  170. priors = np.array([windex * stride + s_d2, hindex * stride + s_d2, s_m4, s_m4])
  171. priors_2p = priors[2:]
  172. box = np.concatenate((priors[:2] + loc[:2] * 0.1 * priors_2p,
  173. priors_2p * np.exp(loc[2:] * 0.2)) )
  174. box[:2] -= box[2:] / 2
  175. box[2:] += box[:2]
  176. bboxlist.append([*box, score])
  177. bboxlist = np.array(bboxlist)
  178. if len(bboxlist) == 0:
  179. bboxlist = np.zeros((1, 5))
  180. bboxlist = bboxlist[self.refine_nms(bboxlist, 0.3), :]
  181. bboxlist = [ x[:-1].astype(np.int) for x in bboxlist if x[-1] >= 0.5]
  182. return bboxlist
  183. def refine_nms(self, dets, thresh):
  184. keep = list()
  185. if len(dets) == 0:
  186. return keep
  187. x_1, y_1, x_2, y_2, scores = dets[:, 0], dets[:, 1], dets[:, 2], dets[:, 3], dets[:, 4]
  188. areas = (x_2 - x_1 + 1) * (y_2 - y_1 + 1)
  189. order = scores.argsort()[::-1]
  190. keep = []
  191. while order.size > 0:
  192. i = order[0]
  193. keep.append(i)
  194. xx_1, yy_1 = np.maximum(x_1[i], x_1[order[1:]]), np.maximum(y_1[i], y_1[order[1:]])
  195. xx_2, yy_2 = np.minimum(x_2[i], x_2[order[1:]]), np.minimum(y_2[i], y_2[order[1:]])
  196. width, height = np.maximum(0.0, xx_2 - xx_1 + 1), np.maximum(0.0, yy_2 - yy_1 + 1)
  197. ovr = width * height / (areas[i] + areas[order[1:]] - width * height)
  198. inds = np.where(ovr <= thresh)[0]
  199. order = order[inds + 1]
  200. return keep
Tip!

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

Comments

Loading...