Diff of /utils/segment/general.py [000000] .. [190ca4]

Switch to unified view

a b/utils/segment/general.py
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 [n, h, w] 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
    protos: [mask_dim, mask_h, mask_w]
29
    masks_in: [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 process_mask_native(protos, masks_in, bboxes, shape):
71
    """
72
    Crop after upsample.
73
    protos: [mask_dim, mask_h, mask_w]
74
    masks_in: [n, mask_dim], n is number of masks after nms
75
    bboxes: [n, 4], n is number of masks after nms
76
    shape: input_image_size, (h, w)
77
78
    return: h, w, n
79
    """
80
    c, mh, mw = protos.shape  # CHW
81
    masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
82
    gain = min(mh / shape[0], mw / shape[1])  # gain  = old / new
83
    pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2  # wh padding
84
    top, left = int(pad[1]), int(pad[0])  # y, x
85
    bottom, right = int(mh - pad[1]), int(mw - pad[0])
86
    masks = masks[:, top:bottom, left:right]
87
88
    masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW
89
    masks = crop_mask(masks, bboxes)  # CHW
90
    return masks.gt_(0.5)
91
92
93
def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):
94
    """
95
    img1_shape: model input shape, [h, w]
96
    img0_shape: origin pic shape, [h, w, 3]
97
    masks: [h, w, num]
98
    """
99
    # Rescale coordinates (xyxy) from im1_shape to im0_shape
100
    if ratio_pad is None:  # calculate from im0_shape
101
        gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1])  # gain  = old / new
102
        pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2  # wh padding
103
    else:
104
        pad = ratio_pad[1]
105
    top, left = int(pad[1]), int(pad[0])  # y, x
106
    bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])
107
108
    if len(masks.shape) < 2:
109
        raise ValueError(f'"len of masks shape" should be 2 or 3, but got {len(masks.shape)}')
110
    masks = masks[top:bottom, left:right]
111
    # masks = masks.permute(2, 0, 1).contiguous()
112
    # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]
113
    # masks = masks.permute(1, 2, 0).contiguous()
114
    masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))
115
116
    if len(masks.shape) == 2:
117
        masks = masks[:, :, None]
118
    return masks
119
120
121
def mask_iou(mask1, mask2, eps=1e-7):
122
    """
123
    mask1: [N, n] m1 means number of predicted objects
124
    mask2: [M, n] m2 means number of gt objects
125
    Note: n means image_w x image_h
126
127
    return: masks iou, [N, M]
128
    """
129
    intersection = torch.matmul(mask1, mask2.t()).clamp(0)
130
    union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection  # (area1 + area2) - intersection
131
    return intersection / (union + eps)
132
133
134
def masks_iou(mask1, mask2, eps=1e-7):
135
    """
136
    mask1: [N, n] m1 means number of predicted objects
137
    mask2: [N, n] m2 means number of gt objects
138
    Note: n means image_w x image_h
139
140
    return: masks iou, (N, )
141
    """
142
    intersection = (mask1 * mask2).sum(1).clamp(0)  # (N, )
143
    union = (mask1.sum(1) + mask2.sum(1))[None] - intersection  # (area1 + area2) - intersection
144
    return intersection / (union + eps)
145
146
147
def masks2segments(masks, strategy='largest'):
148
    # Convert masks(n,160,160) into segments(n,xy)
149
    segments = []
150
    for x in masks.int().cpu().numpy().astype('uint8'):
151
        c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
152
        if c:
153
            if strategy == 'concat':  # concatenate all segments
154
                c = np.concatenate([x.reshape(-1, 2) for x in c])
155
            elif strategy == 'largest':  # select largest segment
156
                c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)
157
        else:
158
            c = np.zeros((0, 2))  # no segments found
159
        segments.append(c.astype('float32'))
160
    return segments