AkashDataScience commited on
Commit
c567a1f
·
1 Parent(s): 9eb3c3e
Files changed (1) hide show
  1. utils/tal/anchor_generator.py +38 -0
utils/tal/anchor_generator.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from utils.general import check_version
4
+
5
+ TORCH_1_10 = check_version(torch.__version__, '1.10.0')
6
+
7
+
8
+ def make_anchors(feats, strides, grid_cell_offset=0.5):
9
+ """Generate anchors from features."""
10
+ anchor_points, stride_tensor = [], []
11
+ assert feats is not None
12
+ dtype, device = feats[0].dtype, feats[0].device
13
+ for i, stride in enumerate(strides):
14
+ _, _, h, w = feats[i].shape
15
+ sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset # shift x
16
+ sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset # shift y
17
+ sy, sx = torch.meshgrid(sy, sx, indexing='ij') if TORCH_1_10 else torch.meshgrid(sy, sx)
18
+ anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))
19
+ stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))
20
+ return torch.cat(anchor_points), torch.cat(stride_tensor)
21
+
22
+
23
+ def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
24
+ """Transform distance(ltrb) to box(xywh or xyxy)."""
25
+ lt, rb = torch.split(distance, 2, dim)
26
+ x1y1 = anchor_points - lt
27
+ x2y2 = anchor_points + rb
28
+ if xywh:
29
+ c_xy = (x1y1 + x2y2) / 2
30
+ wh = x2y2 - x1y1
31
+ return torch.cat((c_xy, wh), dim) # xywh bbox
32
+ return torch.cat((x1y1, x2y2), dim) # xyxy bbox
33
+
34
+
35
+ def bbox2dist(anchor_points, bbox, reg_max):
36
+ """Transform bbox(xyxy) to dist(ltrb)."""
37
+ x1y1, x2y2 = torch.split(bbox, 2, -1)
38
+ return torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1).clamp(0, reg_max - 0.01) # dist (lt, rb)