AkashDataScience commited on
Commit
cd5db6b
·
1 Parent(s): 6b1f333

Minor changes

Browse files
Files changed (1) hide show
  1. utils/segment/general.py +137 -0
utils/segment/general.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ def crop_mask(masks, boxes):
8
+ """
9
+ "Crop" predicted masks by zeroing out everything not in the predicted bbox.
10
+ Vectorized by Chong (thanks Chong).
11
+
12
+ Args:
13
+ - masks should be a size [h, w, n] tensor of masks
14
+ - boxes should be a size [n, 4] tensor of bbox coords in relative point form
15
+ """
16
+
17
+ n, h, w = masks.shape
18
+ x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(1,1,n)
19
+ r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :] # rows shape(1,w,1)
20
+ c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None] # cols shape(h,1,1)
21
+
22
+ return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))
23
+
24
+
25
+ def process_mask_upsample(protos, masks_in, bboxes, shape):
26
+ """
27
+ Crop after upsample.
28
+ proto_out: [mask_dim, mask_h, mask_w]
29
+ out_masks: [n, mask_dim], n is number of masks after nms
30
+ bboxes: [n, 4], n is number of masks after nms
31
+ shape:input_image_size, (h, w)
32
+
33
+ return: h, w, n
34
+ """
35
+
36
+ c, mh, mw = protos.shape # CHW
37
+ masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
38
+ masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW
39
+ masks = crop_mask(masks, bboxes) # CHW
40
+ return masks.gt_(0.5)
41
+
42
+
43
+ def process_mask(protos, masks_in, bboxes, shape, upsample=False):
44
+ """
45
+ Crop before upsample.
46
+ proto_out: [mask_dim, mask_h, mask_w]
47
+ out_masks: [n, mask_dim], n is number of masks after nms
48
+ bboxes: [n, 4], n is number of masks after nms
49
+ shape:input_image_size, (h, w)
50
+
51
+ return: h, w, n
52
+ """
53
+
54
+ c, mh, mw = protos.shape # CHW
55
+ ih, iw = shape
56
+ masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw) # CHW
57
+
58
+ downsampled_bboxes = bboxes.clone()
59
+ downsampled_bboxes[:, 0] *= mw / iw
60
+ downsampled_bboxes[:, 2] *= mw / iw
61
+ downsampled_bboxes[:, 3] *= mh / ih
62
+ downsampled_bboxes[:, 1] *= mh / ih
63
+
64
+ masks = crop_mask(masks, downsampled_bboxes) # CHW
65
+ if upsample:
66
+ masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW
67
+ return masks.gt_(0.5)
68
+
69
+
70
+ def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):
71
+ """
72
+ img1_shape: model input shape, [h, w]
73
+ img0_shape: origin pic shape, [h, w, 3]
74
+ masks: [h, w, num]
75
+ """
76
+ # Rescale coordinates (xyxy) from im1_shape to im0_shape
77
+ if ratio_pad is None: # calculate from im0_shape
78
+ gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]) # gain = old / new
79
+ pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2 # wh padding
80
+ else:
81
+ pad = ratio_pad[1]
82
+ top, left = int(pad[1]), int(pad[0]) # y, x
83
+ bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])
84
+
85
+ if len(masks.shape) < 2:
86
+ raise ValueError(f'"len of masks shape" should be 2 or 3, but got {len(masks.shape)}')
87
+ masks = masks[top:bottom, left:right]
88
+ # masks = masks.permute(2, 0, 1).contiguous()
89
+ # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]
90
+ # masks = masks.permute(1, 2, 0).contiguous()
91
+ masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))
92
+
93
+ if len(masks.shape) == 2:
94
+ masks = masks[:, :, None]
95
+ return masks
96
+
97
+
98
+ def mask_iou(mask1, mask2, eps=1e-7):
99
+ """
100
+ mask1: [N, n] m1 means number of predicted objects
101
+ mask2: [M, n] m2 means number of gt objects
102
+ Note: n means image_w x image_h
103
+
104
+ return: masks iou, [N, M]
105
+ """
106
+ intersection = torch.matmul(mask1, mask2.t()).clamp(0)
107
+ union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
108
+ return intersection / (union + eps)
109
+
110
+
111
+ def masks_iou(mask1, mask2, eps=1e-7):
112
+ """
113
+ mask1: [N, n] m1 means number of predicted objects
114
+ mask2: [N, n] m2 means number of gt objects
115
+ Note: n means image_w x image_h
116
+
117
+ return: masks iou, (N, )
118
+ """
119
+ intersection = (mask1 * mask2).sum(1).clamp(0) # (N, )
120
+ union = (mask1.sum(1) + mask2.sum(1))[None] - intersection # (area1 + area2) - intersection
121
+ return intersection / (union + eps)
122
+
123
+
124
+ def masks2segments(masks, strategy='largest'):
125
+ # Convert masks(n,160,160) into segments(n,xy)
126
+ segments = []
127
+ for x in masks.int().cpu().numpy().astype('uint8'):
128
+ c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
129
+ if c:
130
+ if strategy == 'concat': # concatenate all segments
131
+ c = np.concatenate([x.reshape(-1, 2) for x in c])
132
+ elif strategy == 'largest': # select largest segment
133
+ c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)
134
+ else:
135
+ c = np.zeros((0, 2)) # no segments found
136
+ segments.append(c.astype('float32'))
137
+ return segments