forked from hjk9984/PIoU_YOLOV3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
449 lines (360 loc) · 16.8 KB
/
tools.py
File metadata and controls
449 lines (360 loc) · 16.8 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#coding=utf-8
import sys
sys.path.append("..")
import torch
import numpy as np
import cv2
import random
import config.yolov3_config_voc as cfg
import os
import math
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1:
print("initing {} ".format(m))
torch.nn.init.normal_(m.weight.data, 0.0, 0.01)
if m.bias is not None:
m.bias.data.zero_()
elif classname.find('BatchNorm2d') != -1:
print("initing {} ".format(m))
torch.nn.init.constant_(m.weight.data, 1.0)
torch.nn.init.constant_(m.bias.data, 0.0)
def xyxy2xywh(x):
# Convert bounding box format from [x1, y1, x2, y2] to [x, y, w, h]
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
y[:, 0] = (x[:, 0] + x[:, 2]) / 2.0
y[:, 1] = (x[:, 1] + x[:, 3]) / 2.0
y[:, 2] = x[:, 2] - x[:, 0]
y[:, 3] = x[:, 3] - x[:, 1]
return y
def xywh2xyxy(x):
# Convert bounding box format from [x, y, w, h] to [x1, y1, x2, y2]
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2
return y
def wh_iou(box1, box2):
# box1 shape : [2]
# box2 shape : [bs*N, 2]
box2 = box2.t()
# w, h = box1
w1, h1 = box1[0], box1[1]
w2, h2 = box2[0], box2[1]
# Intersection area
inter_area = torch.min(w1, w2) * torch.min(h1, h2)
# Union Area
union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area
return (inter_area / union_area) # iou shape : [bs*N]
def bbox_iou(box1, box2, mode="xyxy"):
"""
numpy version iou, and use for nms
"""
# Get the coordinates of bounding boxes
if mode == "xyxy":
# x1, y1, x2, y2 = box1
b1_x1, b1_y1, b1_x2, b1_y2 = box1[..., 0], box1[..., 1], box1[..., 2], box1[..., 3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[..., 0], box2[..., 1], box2[..., 2], box2[..., 3]
else:
# x, y, w, h = box1
b1_x1, b1_x2 = box1[..., 0] - box1[..., 2] / 2, box1[..., 0] + box1[..., 2] / 2
b1_y1, b1_y2 = box1[..., 1] - box1[..., 3] / 2, box1[..., 1] + box1[..., 3] / 2
b2_x1, b2_x2 = box2[..., 0] - box2[..., 2] / 2, box2[..., 0] + box2[..., 2] / 2
b2_y1, b2_y2 = box2[..., 1] - box2[..., 3] / 2, box2[..., 1] + box2[..., 3] / 2
# Intersection area
inter_area = np.maximum((np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)), 0.0) * \
np.maximum(np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1), 0.0)
# Union Area
union_area = ((b1_x2 - b1_x1) * (b1_y2 - b1_y1) + 1e-16) + \
(b2_x2 - b2_x1) * (b2_y2 - b2_y1) - inter_area
return inter_area / union_area # iou
def iou_xywh_numpy(boxes1, boxes2):
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = boxes1[..., 2] * boxes1[..., 3]
boxes2_area = boxes2[..., 2] * boxes2[..., 3]
boxes1 = np.concatenate([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], axis=-1)
boxes2 = np.concatenate([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], axis=-1)
left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])
right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])
inter_section = np.maximum(right_down - left_up, 0.0)
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
IOU = 1.0 * inter_area / union_area
return IOU
def iou_xyxy_numpy(boxes1, boxes2):
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])
right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])
inter_section = np.maximum(right_down - left_up, 0.0)
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
IOU = 1.0 * inter_area / union_area
return IOU
def iou_xyxy_torch(boxes1, boxes2):
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
left_up = torch.max(boxes1[..., :2], boxes2[..., :2])
right_down = torch.min(boxes1[..., 2:], boxes2[..., 2:])
inter_section = torch.max(right_down - left_up, torch.zeros_like(right_down))
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
IOU = 1.0 * inter_area / union_area
return IOU
def iou_xywh_torch(boxes1, boxes2):
boxes1_area = boxes1[..., 2] * boxes1[..., 3]
boxes2_area = boxes2[..., 2] * boxes2[..., 3]
boxes1 = torch.cat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], dim=-1)
boxes2 = torch.cat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], dim=-1)
left_up = torch.max(boxes1[..., :2], boxes2[..., :2])
right_down = torch.min(boxes1[..., 2:], boxes2[..., 2:])
inter_section = torch.max(right_down - left_up, torch.zeros_like(right_down))
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
IOU = 1.0 * inter_area / union_area
return IOU
def GIOU_xywh_torch(boxes1, boxes2):
"""
https://arxiv.org/abs/1902.09630
boxes1(boxes2)' shape is [..., (x,y,w,h)].The size is for original image.
"""
# xywh->xyxy
boxes1 = torch.cat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], dim=-1)
boxes2 = torch.cat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], dim=-1)
boxes1 = torch.cat([torch.min(boxes1[..., :2], boxes1[..., 2:]),
torch.max(boxes1[..., :2], boxes1[..., 2:])], dim=-1)
boxes2 = torch.cat([torch.min(boxes2[..., :2], boxes2[..., 2:]),
torch.max(boxes2[..., :2], boxes2[..., 2:])], dim=-1)
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
inter_left_up = torch.max(boxes1[..., :2], boxes2[..., :2])
inter_right_down = torch.min(boxes1[..., 2:], boxes2[..., 2:])
inter_section = torch.max(inter_right_down - inter_left_up, torch.zeros_like(inter_right_down))
inter_area = inter_section[..., 0] * inter_section[..., 1]
union_area = boxes1_area + boxes2_area - inter_area
IOU = 1.0 * inter_area / union_area
enclose_left_up = torch.min(boxes1[..., :2], boxes2[..., :2])
enclose_right_down = torch.max(boxes1[..., 2:], boxes2[..., 2:])
enclose_section = torch.max(enclose_right_down - enclose_left_up, torch.zeros_like(enclose_right_down))
enclose_area = enclose_section[..., 0] * enclose_section[..., 1]
GIOU = IOU - 1.0 * (enclose_area - union_area) / enclose_area
#print(GIOU.shape)
return GIOU
def perimeter_of(max_xy, min_xy):
result = torch.clamp(max_xy[..., :] - min_xy[..., :], min=0)
return result.sum(dim=-1) * 2
def PIOU_xywh_torch(boxes1, boxes2):
"""
https://arxiv.org/abs/1902.09630
boxes1(boxes2)' shape is [..., (x,y,w,h)].The size is for original image.
"""
# xywh->xyxy
boxes1 = torch.cat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], dim=-1)
boxes2 = torch.cat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], dim=-1)
boxes1 = torch.cat([torch.min(boxes1[..., :2], boxes1[..., 2:]),
torch.max(boxes1[..., :2], boxes1[..., 2:])], dim=-1)
boxes2 = torch.cat([torch.min(boxes2[..., :2], boxes2[..., 2:]),
torch.max(boxes2[..., :2], boxes2[..., 2:])], dim=-1)
alpha = 0.5
eps = 1e-5
rows = boxes1.shape[0]
cols = boxes2.shape[0]
pious = torch.zeros((rows, cols))
if rows * cols == 0:
return pious
exchange = False
if boxes1.shape[0] > boxes2.shape[0]:
boxes1, boxes2 = boxes2, boxes1
pious = torch.zeros((cols, rows))
exchange = True
out_max_xy = torch.max(boxes1[..., 2:], boxes2[..., 2:])
out_min_xy = torch.min(boxes1[..., :2], boxes2[..., :2])
pc = perimeter_of(out_max_xy, out_min_xy)
p1 = perimeter_of(boxes1[..., 2:], boxes1[..., :2])
p2 = perimeter_of(boxes2[..., 2:], boxes2[..., :2])
term1 = (pc - 0.5 * (p1 + p2)) / (pc + eps)
whc = out_max_xy - out_min_xy
wh1 = boxes1[..., 2:] - boxes1[..., :2]
wh2 = boxes2[..., 2:] - boxes2[..., :2]
l1 = whc - wh1
l2 = whc - wh2
term2 = (l1 - l2).abs().sum(dim=-1) / ((l1 + l2).sum(dim=-1) + eps)
area1 = (boxes1[..., 2] - boxes1[..., 0]) * (
boxes1[..., 3] - boxes1[..., 1])
area2 = (boxes2[..., 2] - boxes2[..., 0]) * (
boxes2[..., 3] - boxes2[..., 1])
inter_max_xy = torch.min(boxes1[..., 2:], boxes2[..., 2:])
inter_min_xy = torch.max(boxes1[..., :2], boxes2[..., :2])
inter = torch.clamp((inter_max_xy - inter_min_xy), min=0)
inter_area = inter[..., 0] * inter[..., 1]
union = area1 + area2 - inter_area
ious = inter_area / union
ious = torch.clamp(ious, min=0, max=1.0)
# khj
pious = ious - term1 # + term2
pious = torch.clamp(pious, min=-1.0, max=1.0)
if exchange:
pious = pious.T
return pious
def DIOU_xywh_torch(boxes1, boxes2):
boxes1 = torch.cat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], dim=-1)
boxes2 = torch.cat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], dim=-1)
bboxes1 = torch.cat([torch.min(boxes1[..., :2], boxes1[..., 2:]),
torch.max(boxes1[..., :2], boxes1[..., 2:])], dim=-1)
bboxes2 = torch.cat([torch.min(boxes2[..., :2], boxes2[..., 2:]),
torch.max(boxes2[..., :2], boxes2[..., 2:])], dim=-1)
rows = bboxes1.shape[0]
cols = bboxes2.shape[0]
dious = torch.zeros((rows, cols))
if rows * cols == 0:
return dious
exchange = False
if bboxes1.shape[0] > bboxes2.shape[0]:
bboxes1, bboxes2 = bboxes2, bboxes1
dious = torch.zeros((cols, rows))
exchange = True
w1 = bboxes1[..., 2] - bboxes1[..., 0]
h1 = bboxes1[..., 3] - bboxes1[..., 1]
w2 = bboxes2[..., 2] - bboxes2[..., 0]
h2 = bboxes2[..., 3] - bboxes2[..., 1]
area1 = w1 * h1
area2 = w2 * h2
center_x1 = (bboxes1[..., 2] + bboxes1[..., 0]) / 2
center_y1 = (bboxes1[..., 3] + bboxes1[..., 1]) / 2
center_x2 = (bboxes2[..., 2] + bboxes2[..., 0]) / 2
center_y2 = (bboxes2[..., 3] + bboxes2[..., 1]) / 2
inter_max_xy = torch.min(bboxes1[..., 2:],bboxes2[..., 2:])
inter_min_xy = torch.max(bboxes1[..., :2],bboxes2[..., :2])
out_max_xy = torch.max(bboxes1[..., 2:],bboxes2[..., 2:])
out_min_xy = torch.min(bboxes1[..., :2],bboxes2[..., :2])
inter = torch.clamp((inter_max_xy - inter_min_xy), min=0)
inter_area = inter[..., 0] * inter[..., 1]
inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2
outer = torch.clamp((out_max_xy - out_min_xy), min=0)
outer_diag = (outer[..., 0] ** 2) + (outer[..., 1] ** 2)
union = area1+area2-inter_area
dious = inter_area / union - (inter_diag) / outer_diag
dious = torch.clamp(dious,min=-1.0,max = 1.0)
if exchange:
dious = dious.T
return dious
def CIOU_xywh_torch(boxes1, boxes2):
"""
https://arxiv.org/abs/1902.09630
boxes1(boxes2)' shape is [..., (x,y,w,h)].The size is for original image.
"""
# xywh->xyxy
boxes1 = torch.cat([boxes1[..., :2] - boxes1[..., 2:] * 0.5,
boxes1[..., :2] + boxes1[..., 2:] * 0.5], dim=-1)
boxes2 = torch.cat([boxes2[..., :2] - boxes2[..., 2:] * 0.5,
boxes2[..., :2] + boxes2[..., 2:] * 0.5], dim=-1)
bboxes1 = torch.cat([torch.min(boxes1[..., :2], boxes1[..., 2:]),
torch.max(boxes1[..., :2], boxes1[..., 2:])], dim=-1)
bboxes2 = torch.cat([torch.min(boxes2[..., :2], boxes2[..., 2:]),
torch.max(boxes2[..., :2], boxes2[..., 2:])], dim=-1)
eps = 1e-5
rows = bboxes1.shape[0]
cols = bboxes2.shape[0]
cious = torch.zeros((rows, cols))
if rows * cols == 0:
return cious
exchange = False
if bboxes1.shape[0] > bboxes2.shape[0]:
bboxes1, bboxes2 = bboxes2, bboxes1
cious = torch.zeros((cols, rows))
exchange = True
w1 = bboxes1[..., 2] - bboxes1[..., 0]
h1 = bboxes1[..., 3] - bboxes1[..., 1]
w2 = bboxes2[..., 2] - bboxes2[..., 0]
h2 = bboxes2[..., 3] - bboxes2[..., 1]
area1 = w1 * h1
area2 = w2 * h2
center_x1 = (bboxes1[..., 2] + bboxes1[..., 0]) / 2
center_y1 = (bboxes1[..., 3] + bboxes1[..., 1]) / 2
center_x2 = (bboxes2[..., 2] + bboxes2[..., 0]) / 2
center_y2 = (bboxes2[..., 3] + bboxes2[..., 1]) / 2
inter_max_xy = torch.min(bboxes1[..., 2:],bboxes2[..., 2:])
inter_min_xy = torch.max(bboxes1[..., :2],bboxes2[..., :2])
out_max_xy = torch.max(bboxes1[..., 2:],bboxes2[..., 2:])
out_min_xy = torch.min(bboxes1[..., :2],bboxes2[..., :2])
inter = torch.clamp((inter_max_xy - inter_min_xy), min=0)
inter_area = inter[..., 0] * inter[..., 1]
inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2
outer = torch.clamp((out_max_xy - out_min_xy), min=0)
outer_diag = (outer[..., 0] ** 2) + (outer[..., 1] ** 2)
union = area1+area2-inter_area
u = (inter_diag) / (outer_diag + eps)
iou = inter_area / (union + eps)
v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(w2 / (h2+eps)) - torch.atan(w1 / (h1+eps))), 2)
with torch.no_grad():
S = 1 - iou
alpha = v / (S + v)
cious = iou - (u + alpha * v)
cious = torch.clamp(cious,min=-1.0,max = 1.0)
if exchange:
cious = cious.T
return cious
def nms(bboxes, score_threshold, iou_threshold, sigma=0.3, method='nms'):
classes_in_img = list(set(bboxes[:, 5].astype(np.int32)))
best_bboxes = []
for cls in classes_in_img:
cls_mask = (bboxes[:, 5].astype(np.int32) == cls)
cls_bboxes = bboxes[cls_mask]
while len(cls_bboxes) > 0:
max_ind = np.argmax(cls_bboxes[:, 4])
best_bbox = cls_bboxes[max_ind]
best_bboxes.append(best_bbox)
cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])
iou = iou_xyxy_numpy(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])
assert method in ['nms', 'soft-nms']
weight = np.ones((len(iou),), dtype=np.float32)
if method == 'nms':
iou_mask = iou > iou_threshold
weight[iou_mask] = 0.0
if method == 'soft-nms':
weight = np.exp(-(1.0 * iou ** 2 / sigma))
cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight
score_mask = cls_bboxes[:, 4] > score_threshold
cls_bboxes = cls_bboxes[score_mask]
return np.array(best_bboxes)
def init_seeds(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
def plot_box(bboxes, img, id = None, color=None, line_thickness=None):
img = img.permute(0,2,3,1).contiguous()[0].numpy() if isinstance(img, torch.Tensor) else img# [C,H,W] ---> [H,W,C]
img_size, _, _ = img.shape
bboxes[:, :4] = xywh2xyxy(bboxes[:, :4])
tl = line_thickness or round(0.002 * max(img.shape[0:2])) + 1 # line thickness
color = color or [random.randint(0, 255) for _ in range(3)]
for i, x in enumerate(bboxes):
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
cv2.rectangle(img, c1, c2, color, thickness=tl)
label = cfg.DATA["CLASSES"][int(x[4])]
if label:
tf = max(tl - 1, 1) # font thickness
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
cv2.rectangle(img, c1, c2, color, -1) # filled
cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [0, 0, 0], thickness=tf, lineType=cv2.LINE_AA)
# cv2.imshow("img-bbox", img[:, :, ::-1])
# cv2.waitKey(0)
img = cv2.cvtColor(img* 255.0, cv2.COLOR_RGB2BGR).astype(np.float32)
cv2.imwrite("../data/dataset{}.jpg".format(id), img)