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

S3FD.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
  1. import operator
  2. from pathlib import Path
  3. import numpy as np
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from xlib import math as lib_math
  8. from xlib.file import SplittedFile
  9. from xlib.image import ImageProcessor
  10. from xlib.torch import TorchDeviceInfo, get_cpu_device_info
  11. class S3FD:
  12. def __init__(self, device_info : TorchDeviceInfo = None ):
  13. if device_info is None:
  14. device_info = get_cpu_device_info()
  15. self.device_info = device_info
  16. path = Path(__file__).parent / 'S3FD.pth'
  17. SplittedFile.merge(path, delete_parts=False)
  18. net = self.net = S3FDNet()
  19. net.load_state_dict( torch.load(str(path) ))
  20. net.eval()
  21. if not device_info.is_cpu():
  22. net.cuda(device_info.get_index())
  23. def extract(self, img : np.ndarray, fixed_window, min_face_size=40):
  24. """
  25. """
  26. ip = ImageProcessor(img)
  27. if fixed_window != 0:
  28. fixed_window = max(64, max(1, fixed_window // 32) * 32 )
  29. img_scale = ip.fit_in(fixed_window, fixed_window, pad_to_target=True, allow_upscale=False)
  30. else:
  31. ip.pad_to_next_divisor(64, 64)
  32. img_scale = 1.0
  33. img = ip.ch(3).as_float32().apply( lambda img: img - [104,117,123]).get_image('NCHW')
  34. tensor = torch.from_numpy(img)
  35. if not self.device_info.is_cpu():
  36. tensor = tensor.cuda(self.device_info.get_index())
  37. batches_bbox = [x.data.cpu().numpy() for x in self.net(tensor)]
  38. faces_per_batch = []
  39. for batch in range(img.shape[0]):
  40. bbox = self.refine( [ x[batch] for x in batches_bbox ] )
  41. faces = []
  42. for l,t,r,b,c in bbox:
  43. if img_scale != 1.0:
  44. l,t,r,b = l/img_scale, t/img_scale, r/img_scale, b/img_scale
  45. bt = b-t
  46. if min(r-l,bt) < min_face_size:
  47. continue
  48. b += bt*0.1
  49. faces.append ( (l,t,r,b) )
  50. #sort by largest area first
  51. faces = [ [(l,t,r,b), (r-l)*(b-t) ] for (l,t,r,b) in faces ]
  52. faces = sorted(faces, key=operator.itemgetter(1), reverse=True )
  53. faces = [ x[0] for x in faces]
  54. faces_per_batch.append(faces)
  55. return faces_per_batch
  56. def refine(self, olist):
  57. bboxlist = []
  58. variances = [0.1, 0.2]
  59. for i in range(len(olist) // 2):
  60. ocls, oreg = olist[i * 2], olist[i * 2 + 1]
  61. stride = 2**(i + 2) # 4,8,16,32,64,128
  62. for hindex, windex in [*zip(*np.where(ocls[1, :, :] > 0.05))]:
  63. axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride
  64. score = ocls[1, hindex, windex]
  65. loc = np.ascontiguousarray(oreg[:, hindex, windex]).reshape((1, 4))
  66. priors = np.array([[axc, ayc, stride * 4, stride * 4]])
  67. bbox = np.concatenate((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
  68. priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])), 1)
  69. bbox[:, :2] -= bbox[:, 2:] / 2
  70. bbox[:, 2:] += bbox[:, :2]
  71. x1, y1, x2, y2 = bbox[0]
  72. bboxlist.append([x1, y1, x2, y2, score])
  73. if len(bboxlist) != 0:
  74. bboxlist = np.array(bboxlist)
  75. bboxlist = bboxlist[ lib_math.nms(bboxlist[:,0], bboxlist[:,1], bboxlist[:,2], bboxlist[:,3], bboxlist[:,4], 0.3), : ]
  76. bboxlist = [x for x in bboxlist if x[-1] >= 0.5]
  77. return bboxlist
  78. @staticmethod
  79. def save_as_onnx(onnx_filepath):
  80. s3fd = S3FD()
  81. torch.onnx.export(s3fd.net,
  82. torch.from_numpy( np.zeros( (1,3,640,640), dtype=np.float32)),
  83. str(onnx_filepath),
  84. verbose=True,
  85. training=torch.onnx.TrainingMode.EVAL,
  86. opset_version=9,
  87. do_constant_folding=True,
  88. input_names=['in'],
  89. output_names=['cls1', 'reg1', 'cls2', 'reg2', 'cls3', 'reg3', 'cls4', 'reg4', 'cls5', 'reg5', 'cls6', 'reg6'],
  90. dynamic_axes={'in' : {0:'batch_size',2:'height',3:'width'},
  91. 'cls1' : {2:'height',3:'width'},
  92. 'reg1' : {2:'height',3:'width'},
  93. 'cls2' : {2:'height',3:'width'},
  94. 'reg2' : {2:'height',3:'width'},
  95. 'cls3' : {2:'height',3:'width'},
  96. 'reg3' : {2:'height',3:'width'},
  97. 'cls4' : {2:'height',3:'width'},
  98. 'reg4' : {2:'height',3:'width'},
  99. 'cls5' : {2:'height',3:'width'},
  100. 'reg5' : {2:'height',3:'width'},
  101. 'cls6' : {2:'height',3:'width'},
  102. 'reg6' : {2:'height',3:'width'},
  103. },
  104. )
  105. class L2Norm(nn.Module):
  106. def __init__(self, n_channels, scale=1.0):
  107. super().__init__()
  108. self.n_channels = n_channels
  109. self.scale = scale
  110. self.eps = 1e-10
  111. self.weight = nn.Parameter(torch.Tensor(self.n_channels))
  112. self.weight.data *= 0.0
  113. self.weight.data += self.scale
  114. def forward(self, x):
  115. norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps
  116. x = x / norm * self.weight.view(1, -1, 1, 1)
  117. return x
  118. class S3FDNet(nn.Module):
  119. def __init__(self):
  120. super().__init__()
  121. self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
  122. self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
  123. self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
  124. self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
  125. self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)
  126. self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  127. self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  128. self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1)
  129. self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
  130. self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
  131. self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
  132. self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
  133. self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
  134. self.fc6 = nn.Conv2d(512, 1024, kernel_size=3, stride=1, padding=3)
  135. self.fc7 = nn.Conv2d(1024, 1024, kernel_size=1, stride=1, padding=0)
  136. self.conv6_1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0)
  137. self.conv6_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)
  138. self.conv7_1 = nn.Conv2d(512, 128, kernel_size=1, stride=1, padding=0)
  139. self.conv7_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)
  140. self.conv3_3_norm = L2Norm(256, scale=10)
  141. self.conv4_3_norm = L2Norm(512, scale=8)
  142. self.conv5_3_norm = L2Norm(512, scale=5)
  143. self.conv3_3_norm_mbox_conf = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1)
  144. self.conv3_3_norm_mbox_loc = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1)
  145. self.conv4_3_norm_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1)
  146. self.conv4_3_norm_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1)
  147. self.conv5_3_norm_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1)
  148. self.conv5_3_norm_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1)
  149. self.fc7_mbox_conf = nn.Conv2d(1024, 2, kernel_size=3, stride=1, padding=1)
  150. self.fc7_mbox_loc = nn.Conv2d(1024, 4, kernel_size=3, stride=1, padding=1)
  151. self.conv6_2_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1)
  152. self.conv6_2_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1)
  153. self.conv7_2_mbox_conf = nn.Conv2d(256, 2, kernel_size=3, stride=1, padding=1)
  154. self.conv7_2_mbox_loc = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1)
  155. def forward(self, x):
  156. h = F.relu(self.conv1_1(x))
  157. h = F.relu(self.conv1_2(h))
  158. h = F.max_pool2d(h, 2, 2)
  159. h = F.relu(self.conv2_1(h))
  160. h = F.relu(self.conv2_2(h))
  161. h = F.max_pool2d(h, 2, 2)
  162. h = F.relu(self.conv3_1(h))
  163. h = F.relu(self.conv3_2(h))
  164. h = F.relu(self.conv3_3(h))
  165. f3_3 = h
  166. h = F.max_pool2d(h, 2, 2)
  167. h = F.relu(self.conv4_1(h))
  168. h = F.relu(self.conv4_2(h))
  169. h = F.relu(self.conv4_3(h))
  170. f4_3 = h
  171. h = F.max_pool2d(h, 2, 2)
  172. h = F.relu(self.conv5_1(h))
  173. h = F.relu(self.conv5_2(h))
  174. h = F.relu(self.conv5_3(h))
  175. f5_3 = h
  176. h = F.max_pool2d(h, 2, 2)
  177. h = F.relu(self.fc6(h))
  178. h = F.relu(self.fc7(h))
  179. ffc7 = h
  180. h = F.relu(self.conv6_1(h))
  181. h = F.relu(self.conv6_2(h))
  182. f6_2 = h
  183. h = F.relu(self.conv7_1(h))
  184. h = F.relu(self.conv7_2(h))
  185. f7_2 = h
  186. f3_3 = self.conv3_3_norm(f3_3)
  187. f4_3 = self.conv4_3_norm(f4_3)
  188. f5_3 = self.conv5_3_norm(f5_3)
  189. cls1 = self.conv3_3_norm_mbox_conf(f3_3)
  190. reg1 = self.conv3_3_norm_mbox_loc(f3_3)
  191. cls2 = self.conv4_3_norm_mbox_conf(f4_3)
  192. reg2 = self.conv4_3_norm_mbox_loc(f4_3)
  193. cls3 = self.conv5_3_norm_mbox_conf(f5_3)
  194. reg3 = self.conv5_3_norm_mbox_loc(f5_3)
  195. cls4 = self.fc7_mbox_conf(ffc7)
  196. reg4 = self.fc7_mbox_loc(ffc7)
  197. cls5 = self.conv6_2_mbox_conf(f6_2)
  198. reg5 = self.conv6_2_mbox_loc(f6_2)
  199. cls6 = self.conv7_2_mbox_conf(f7_2)
  200. reg6 = self.conv7_2_mbox_loc(f7_2)
  201. # max-out background label
  202. chunk = torch.chunk(cls1, 4, 1)
  203. bmax = torch.max(torch.max(chunk[0], chunk[1]), chunk[2])
  204. cls1 = torch.cat ([bmax,chunk[3]], dim=1)
  205. cls1, cls2, cls3, cls4, cls5, cls6 = [ F.softmax(x, dim=1) for x in [cls1, cls2, cls3, cls4, cls5, cls6] ]
  206. return [cls1, reg1, cls2, reg2, cls3, reg3, cls4, reg4, cls5, reg5, cls6, reg6]
Tip!

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

Comments

Loading...