Ii
commited on
Delete scrfd.py
Browse files
scrfd.py
DELETED
@@ -1,329 +0,0 @@
|
|
1 |
-
|
2 |
-
from __future__ import division
|
3 |
-
import datetime
|
4 |
-
import numpy as np
|
5 |
-
#import onnx
|
6 |
-
import onnxruntime
|
7 |
-
import os
|
8 |
-
import os.path as osp
|
9 |
-
import cv2
|
10 |
-
import sys
|
11 |
-
|
12 |
-
def softmax(z):
|
13 |
-
assert len(z.shape) == 2
|
14 |
-
s = np.max(z, axis=1)
|
15 |
-
s = s[:, np.newaxis] # necessary step to do broadcasting
|
16 |
-
e_x = np.exp(z - s)
|
17 |
-
div = np.sum(e_x, axis=1)
|
18 |
-
div = div[:, np.newaxis] # dito
|
19 |
-
return e_x / div
|
20 |
-
|
21 |
-
def distance2bbox(points, distance, max_shape=None):
|
22 |
-
"""Decode distance prediction to bounding box.
|
23 |
-
|
24 |
-
Args:
|
25 |
-
points (Tensor): Shape (n, 2), [x, y].
|
26 |
-
distance (Tensor): Distance from the given point to 4
|
27 |
-
boundaries (left, top, right, bottom).
|
28 |
-
max_shape (tuple): Shape of the image.
|
29 |
-
|
30 |
-
Returns:
|
31 |
-
Tensor: Decoded bboxes.
|
32 |
-
"""
|
33 |
-
x1 = points[:, 0] - distance[:, 0]
|
34 |
-
y1 = points[:, 1] - distance[:, 1]
|
35 |
-
x2 = points[:, 0] + distance[:, 2]
|
36 |
-
y2 = points[:, 1] + distance[:, 3]
|
37 |
-
if max_shape is not None:
|
38 |
-
x1 = x1.clamp(min=0, max=max_shape[1])
|
39 |
-
y1 = y1.clamp(min=0, max=max_shape[0])
|
40 |
-
x2 = x2.clamp(min=0, max=max_shape[1])
|
41 |
-
y2 = y2.clamp(min=0, max=max_shape[0])
|
42 |
-
return np.stack([x1, y1, x2, y2], axis=-1)
|
43 |
-
|
44 |
-
def distance2kps(points, distance, max_shape=None):
|
45 |
-
"""Decode distance prediction to bounding box.
|
46 |
-
|
47 |
-
Args:
|
48 |
-
points (Tensor): Shape (n, 2), [x, y].
|
49 |
-
distance (Tensor): Distance from the given point to 4
|
50 |
-
boundaries (left, top, right, bottom).
|
51 |
-
max_shape (tuple): Shape of the image.
|
52 |
-
|
53 |
-
Returns:
|
54 |
-
Tensor: Decoded bboxes.
|
55 |
-
"""
|
56 |
-
preds = []
|
57 |
-
for i in range(0, distance.shape[1], 2):
|
58 |
-
px = points[:, i%2] + distance[:, i]
|
59 |
-
py = points[:, i%2+1] + distance[:, i+1]
|
60 |
-
if max_shape is not None:
|
61 |
-
px = px.clamp(min=0, max=max_shape[1])
|
62 |
-
py = py.clamp(min=0, max=max_shape[0])
|
63 |
-
preds.append(px)
|
64 |
-
preds.append(py)
|
65 |
-
return np.stack(preds, axis=-1)
|
66 |
-
|
67 |
-
class SCRFD:
|
68 |
-
def __init__(self, model_file=None, session=None):
|
69 |
-
import onnxruntime
|
70 |
-
self.model_file = model_file
|
71 |
-
self.session = session
|
72 |
-
self.taskname = 'detection'
|
73 |
-
self.batched = False
|
74 |
-
if self.session is None:
|
75 |
-
assert self.model_file is not None
|
76 |
-
assert osp.exists(self.model_file)
|
77 |
-
self.session = onnxruntime.InferenceSession(self.model_file, providers=['CoreMLExecutionProvider','CUDAExecutionProvider'])
|
78 |
-
self.center_cache = {}
|
79 |
-
self.nms_thresh = 0.4
|
80 |
-
self.det_thresh = 0.5
|
81 |
-
self._init_vars()
|
82 |
-
|
83 |
-
def _init_vars(self):
|
84 |
-
input_cfg = self.session.get_inputs()[0]
|
85 |
-
input_shape = input_cfg.shape
|
86 |
-
#print(input_shape)
|
87 |
-
if isinstance(input_shape[2], str):
|
88 |
-
self.input_size = None
|
89 |
-
else:
|
90 |
-
self.input_size = tuple(input_shape[2:4][::-1])
|
91 |
-
#print('image_size:', self.image_size)
|
92 |
-
input_name = input_cfg.name
|
93 |
-
self.input_shape = input_shape
|
94 |
-
outputs = self.session.get_outputs()
|
95 |
-
if len(outputs[0].shape) == 3:
|
96 |
-
self.batched = True
|
97 |
-
output_names = []
|
98 |
-
for o in outputs:
|
99 |
-
output_names.append(o.name)
|
100 |
-
self.input_name = input_name
|
101 |
-
self.output_names = output_names
|
102 |
-
self.input_mean = 127.5
|
103 |
-
self.input_std = 128.0
|
104 |
-
#print(self.output_names)
|
105 |
-
#assert len(outputs)==10 or len(outputs)==15
|
106 |
-
self.use_kps = False
|
107 |
-
self._anchor_ratio = 1.0
|
108 |
-
self._num_anchors = 1
|
109 |
-
if len(outputs)==6:
|
110 |
-
self.fmc = 3
|
111 |
-
self._feat_stride_fpn = [8, 16, 32]
|
112 |
-
self._num_anchors = 2
|
113 |
-
elif len(outputs)==9:
|
114 |
-
self.fmc = 3
|
115 |
-
self._feat_stride_fpn = [8, 16, 32]
|
116 |
-
self._num_anchors = 2
|
117 |
-
self.use_kps = True
|
118 |
-
elif len(outputs)==10:
|
119 |
-
self.fmc = 5
|
120 |
-
self._feat_stride_fpn = [8, 16, 32, 64, 128]
|
121 |
-
self._num_anchors = 1
|
122 |
-
elif len(outputs)==15:
|
123 |
-
self.fmc = 5
|
124 |
-
self._feat_stride_fpn = [8, 16, 32, 64, 128]
|
125 |
-
self._num_anchors = 1
|
126 |
-
self.use_kps = True
|
127 |
-
|
128 |
-
def prepare(self, ctx_id, **kwargs):
|
129 |
-
if ctx_id<0:
|
130 |
-
self.session.set_providers(['CPUExecutionProvider'])
|
131 |
-
nms_thresh = kwargs.get('nms_thresh', None)
|
132 |
-
if nms_thresh is not None:
|
133 |
-
self.nms_thresh = nms_thresh
|
134 |
-
det_thresh = kwargs.get('det_thresh', None)
|
135 |
-
if det_thresh is not None:
|
136 |
-
self.det_thresh = det_thresh
|
137 |
-
input_size = kwargs.get('input_size', None)
|
138 |
-
if input_size is not None:
|
139 |
-
if self.input_size is not None:
|
140 |
-
print('warning: det_size is already set in scrfd model, ignore')
|
141 |
-
else:
|
142 |
-
self.input_size = input_size
|
143 |
-
|
144 |
-
def forward(self, img, threshold):
|
145 |
-
scores_list = []
|
146 |
-
bboxes_list = []
|
147 |
-
kpss_list = []
|
148 |
-
input_size = tuple(img.shape[0:2][::-1])
|
149 |
-
blob = cv2.dnn.blobFromImage(img, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True)
|
150 |
-
net_outs = self.session.run(self.output_names, {self.input_name : blob})
|
151 |
-
|
152 |
-
input_height = blob.shape[2]
|
153 |
-
input_width = blob.shape[3]
|
154 |
-
fmc = self.fmc
|
155 |
-
for idx, stride in enumerate(self._feat_stride_fpn):
|
156 |
-
# If model support batch dim, take first output
|
157 |
-
if self.batched:
|
158 |
-
scores = net_outs[idx][0]
|
159 |
-
bbox_preds = net_outs[idx + fmc][0]
|
160 |
-
bbox_preds = bbox_preds * stride
|
161 |
-
if self.use_kps:
|
162 |
-
kps_preds = net_outs[idx + fmc * 2][0] * stride
|
163 |
-
# If model doesn't support batching take output as is
|
164 |
-
else:
|
165 |
-
scores = net_outs[idx]
|
166 |
-
bbox_preds = net_outs[idx + fmc]
|
167 |
-
bbox_preds = bbox_preds * stride
|
168 |
-
if self.use_kps:
|
169 |
-
kps_preds = net_outs[idx + fmc * 2] * stride
|
170 |
-
|
171 |
-
height = input_height // stride
|
172 |
-
width = input_width // stride
|
173 |
-
K = height * width
|
174 |
-
key = (height, width, stride)
|
175 |
-
if key in self.center_cache:
|
176 |
-
anchor_centers = self.center_cache[key]
|
177 |
-
else:
|
178 |
-
#solution-1, c style:
|
179 |
-
#anchor_centers = np.zeros( (height, width, 2), dtype=np.float32 )
|
180 |
-
#for i in range(height):
|
181 |
-
# anchor_centers[i, :, 1] = i
|
182 |
-
#for i in range(width):
|
183 |
-
# anchor_centers[:, i, 0] = i
|
184 |
-
|
185 |
-
#solution-2:
|
186 |
-
#ax = np.arange(width, dtype=np.float32)
|
187 |
-
#ay = np.arange(height, dtype=np.float32)
|
188 |
-
#xv, yv = np.meshgrid(np.arange(width), np.arange(height))
|
189 |
-
#anchor_centers = np.stack([xv, yv], axis=-1).astype(np.float32)
|
190 |
-
|
191 |
-
#solution-3:
|
192 |
-
anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32)
|
193 |
-
#print(anchor_centers.shape)
|
194 |
-
|
195 |
-
anchor_centers = (anchor_centers * stride).reshape( (-1, 2) )
|
196 |
-
if self._num_anchors>1:
|
197 |
-
anchor_centers = np.stack([anchor_centers]*self._num_anchors, axis=1).reshape( (-1,2) )
|
198 |
-
if len(self.center_cache)<100:
|
199 |
-
self.center_cache[key] = anchor_centers
|
200 |
-
|
201 |
-
pos_inds = np.where(scores>=threshold)[0]
|
202 |
-
bboxes = distance2bbox(anchor_centers, bbox_preds)
|
203 |
-
pos_scores = scores[pos_inds]
|
204 |
-
pos_bboxes = bboxes[pos_inds]
|
205 |
-
scores_list.append(pos_scores)
|
206 |
-
bboxes_list.append(pos_bboxes)
|
207 |
-
if self.use_kps:
|
208 |
-
kpss = distance2kps(anchor_centers, kps_preds)
|
209 |
-
#kpss = kps_preds
|
210 |
-
kpss = kpss.reshape( (kpss.shape[0], -1, 2) )
|
211 |
-
pos_kpss = kpss[pos_inds]
|
212 |
-
kpss_list.append(pos_kpss)
|
213 |
-
return scores_list, bboxes_list, kpss_list
|
214 |
-
|
215 |
-
def detect(self, img, input_size = None, thresh=None, max_num=0, metric='default'):
|
216 |
-
assert input_size is not None or self.input_size is not None
|
217 |
-
input_size = self.input_size if input_size is None else input_size
|
218 |
-
|
219 |
-
im_ratio = float(img.shape[0]) / img.shape[1]
|
220 |
-
model_ratio = float(input_size[1]) / input_size[0]
|
221 |
-
if im_ratio>model_ratio:
|
222 |
-
new_height = input_size[1]
|
223 |
-
new_width = int(new_height / im_ratio)
|
224 |
-
else:
|
225 |
-
new_width = input_size[0]
|
226 |
-
new_height = int(new_width * im_ratio)
|
227 |
-
det_scale = float(new_height) / img.shape[0]
|
228 |
-
resized_img = cv2.resize(img, (new_width, new_height))
|
229 |
-
det_img = np.zeros( (input_size[1], input_size[0], 3), dtype=np.uint8 )
|
230 |
-
det_img[:new_height, :new_width, :] = resized_img
|
231 |
-
det_thresh = thresh if thresh is not None else self.det_thresh
|
232 |
-
|
233 |
-
scores_list, bboxes_list, kpss_list = self.forward(det_img, det_thresh)
|
234 |
-
|
235 |
-
scores = np.vstack(scores_list)
|
236 |
-
scores_ravel = scores.ravel()
|
237 |
-
order = scores_ravel.argsort()[::-1]
|
238 |
-
bboxes = np.vstack(bboxes_list) / det_scale
|
239 |
-
if self.use_kps:
|
240 |
-
kpss = np.vstack(kpss_list) / det_scale
|
241 |
-
pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False)
|
242 |
-
pre_det = pre_det[order, :]
|
243 |
-
keep = self.nms(pre_det)
|
244 |
-
det = pre_det[keep, :]
|
245 |
-
if self.use_kps:
|
246 |
-
kpss = kpss[order,:,:]
|
247 |
-
kpss = kpss[keep,:,:]
|
248 |
-
else:
|
249 |
-
kpss = None
|
250 |
-
if max_num > 0 and det.shape[0] > max_num:
|
251 |
-
area = (det[:, 2] - det[:, 0]) * (det[:, 3] -
|
252 |
-
det[:, 1])
|
253 |
-
img_center = img.shape[0] // 2, img.shape[1] // 2
|
254 |
-
offsets = np.vstack([
|
255 |
-
(det[:, 0] + det[:, 2]) / 2 - img_center[1],
|
256 |
-
(det[:, 1] + det[:, 3]) / 2 - img_center[0]
|
257 |
-
])
|
258 |
-
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
259 |
-
if metric=='max':
|
260 |
-
values = area
|
261 |
-
else:
|
262 |
-
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
263 |
-
bindex = np.argsort(
|
264 |
-
values)[::-1] # some extra weight on the centering
|
265 |
-
bindex = bindex[0:max_num]
|
266 |
-
det = det[bindex, :]
|
267 |
-
if kpss is not None:
|
268 |
-
kpss = kpss[bindex, :]
|
269 |
-
return det, kpss
|
270 |
-
|
271 |
-
def autodetect(self, img, max_num=0, metric='max'):
|
272 |
-
bboxes, kpss = self.detect(img, input_size=(640, 640), thresh=0.5)
|
273 |
-
bboxes2, kpss2 = self.detect(img, input_size=(128, 128), thresh=0.5)
|
274 |
-
bboxes_all = np.concatenate([bboxes, bboxes2], axis=0)
|
275 |
-
kpss_all = np.concatenate([kpss, kpss2], axis=0)
|
276 |
-
keep = self.nms(bboxes_all)
|
277 |
-
det = bboxes_all[keep,:]
|
278 |
-
kpss = kpss_all[keep,:]
|
279 |
-
if max_num > 0 and det.shape[0] > max_num:
|
280 |
-
area = (det[:, 2] - det[:, 0]) * (det[:, 3] -
|
281 |
-
det[:, 1])
|
282 |
-
img_center = img.shape[0] // 2, img.shape[1] // 2
|
283 |
-
offsets = np.vstack([
|
284 |
-
(det[:, 0] + det[:, 2]) / 2 - img_center[1],
|
285 |
-
(det[:, 1] + det[:, 3]) / 2 - img_center[0]
|
286 |
-
])
|
287 |
-
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
|
288 |
-
if metric=='max':
|
289 |
-
values = area
|
290 |
-
else:
|
291 |
-
values = area - offset_dist_squared * 2.0 # some extra weight on the centering
|
292 |
-
bindex = np.argsort(
|
293 |
-
values)[::-1] # some extra weight on the centering
|
294 |
-
bindex = bindex[0:max_num]
|
295 |
-
det = det[bindex, :]
|
296 |
-
if kpss is not None:
|
297 |
-
kpss = kpss[bindex, :]
|
298 |
-
return det, kpss
|
299 |
-
|
300 |
-
def nms(self, dets):
|
301 |
-
thresh = self.nms_thresh
|
302 |
-
x1 = dets[:, 0]
|
303 |
-
y1 = dets[:, 1]
|
304 |
-
x2 = dets[:, 2]
|
305 |
-
y2 = dets[:, 3]
|
306 |
-
scores = dets[:, 4]
|
307 |
-
|
308 |
-
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
309 |
-
order = scores.argsort()[::-1]
|
310 |
-
|
311 |
-
keep = []
|
312 |
-
while order.size > 0:
|
313 |
-
i = order[0]
|
314 |
-
keep.append(i)
|
315 |
-
xx1 = np.maximum(x1[i], x1[order[1:]])
|
316 |
-
yy1 = np.maximum(y1[i], y1[order[1:]])
|
317 |
-
xx2 = np.minimum(x2[i], x2[order[1:]])
|
318 |
-
yy2 = np.minimum(y2[i], y2[order[1:]])
|
319 |
-
|
320 |
-
w = np.maximum(0.0, xx2 - xx1 + 1)
|
321 |
-
h = np.maximum(0.0, yy2 - yy1 + 1)
|
322 |
-
inter = w * h
|
323 |
-
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
324 |
-
|
325 |
-
inds = np.where(ovr <= thresh)[0]
|
326 |
-
order = order[inds + 1]
|
327 |
-
|
328 |
-
return keep
|
329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|