segment-everything 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. segment_everything/__init__.py +5 -0
  2. segment_everything/augmentation/albumentations_helper.py +0 -0
  3. segment_everything/detect_and_segment.py +131 -0
  4. segment_everything/napari_helper.py +15 -0
  5. segment_everything/prompt_generator.py +188 -0
  6. segment_everything/py.typed +5 -0
  7. segment_everything/stacked_label_dataset.py +113 -0
  8. segment_everything/stacked_labels.py +428 -0
  9. segment_everything/vendored/PromptGuidedDecoder/Prompt_guided_Mask_Decoder.pt +0 -0
  10. segment_everything/vendored/__init__.py +5 -0
  11. segment_everything/vendored/dice.py +158 -0
  12. segment_everything/vendored/efficientvit/__init__.py +0 -0
  13. segment_everything/vendored/efficientvit/apps/__init__.py +0 -0
  14. segment_everything/vendored/efficientvit/apps/data_provider/__init__.py +7 -0
  15. segment_everything/vendored/efficientvit/apps/data_provider/augment/__init__.py +6 -0
  16. segment_everything/vendored/efficientvit/apps/data_provider/augment/bbox.py +30 -0
  17. segment_everything/vendored/efficientvit/apps/data_provider/augment/color_aug.py +78 -0
  18. segment_everything/vendored/efficientvit/apps/data_provider/base.py +254 -0
  19. segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/__init__.py +6 -0
  20. segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/_data_loader.py +1538 -0
  21. segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/_data_worker.py +357 -0
  22. segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/controller.py +100 -0
  23. segment_everything/vendored/efficientvit/apps/setup.py +150 -0
  24. segment_everything/vendored/efficientvit/apps/trainer/__init__.py +6 -0
  25. segment_everything/vendored/efficientvit/apps/trainer/base.py +318 -0
  26. segment_everything/vendored/efficientvit/apps/trainer/run_config.py +129 -0
  27. segment_everything/vendored/efficientvit/apps/utils/__init__.py +12 -0
  28. segment_everything/vendored/efficientvit/apps/utils/dist.py +32 -0
  29. segment_everything/vendored/efficientvit/apps/utils/ema.py +52 -0
  30. segment_everything/vendored/efficientvit/apps/utils/export.py +45 -0
  31. segment_everything/vendored/efficientvit/apps/utils/init.py +66 -0
  32. segment_everything/vendored/efficientvit/apps/utils/lr.py +52 -0
  33. segment_everything/vendored/efficientvit/apps/utils/metric.py +43 -0
  34. segment_everything/vendored/efficientvit/apps/utils/misc.py +101 -0
  35. segment_everything/vendored/efficientvit/apps/utils/opt.py +28 -0
  36. segment_everything/vendored/efficientvit/cls_model_zoo.py +79 -0
  37. segment_everything/vendored/efficientvit/clscore/__init__.py +0 -0
  38. segment_everything/vendored/efficientvit/clscore/data_provider/__init__.py +5 -0
  39. segment_everything/vendored/efficientvit/clscore/data_provider/imagenet.py +142 -0
  40. segment_everything/vendored/efficientvit/clscore/trainer/__init__.py +6 -0
  41. segment_everything/vendored/efficientvit/clscore/trainer/cls_run_config.py +18 -0
  42. segment_everything/vendored/efficientvit/clscore/trainer/cls_trainer.py +265 -0
  43. segment_everything/vendored/efficientvit/clscore/trainer/utils/__init__.py +7 -0
  44. segment_everything/vendored/efficientvit/clscore/trainer/utils/label_smooth.py +18 -0
  45. segment_everything/vendored/efficientvit/clscore/trainer/utils/metric.py +23 -0
  46. segment_everything/vendored/efficientvit/clscore/trainer/utils/mixup.py +67 -0
  47. segment_everything/vendored/efficientvit/models/__init__.py +0 -0
  48. segment_everything/vendored/efficientvit/models/efficientvit/__init__.py +8 -0
  49. segment_everything/vendored/efficientvit/models/efficientvit/backbone.py +380 -0
  50. segment_everything/vendored/efficientvit/models/efficientvit/cls.py +188 -0
  51. segment_everything/vendored/efficientvit/models/efficientvit/sam.py +181 -0
  52. segment_everything/vendored/efficientvit/models/efficientvit/seg.py +373 -0
  53. segment_everything/vendored/efficientvit/models/nn/__init__.py +8 -0
  54. segment_everything/vendored/efficientvit/models/nn/act.py +30 -0
  55. segment_everything/vendored/efficientvit/models/nn/drop.py +104 -0
  56. segment_everything/vendored/efficientvit/models/nn/norm.py +164 -0
  57. segment_everything/vendored/efficientvit/models/nn/ops.py +597 -0
  58. segment_everything/vendored/efficientvit/models/utils/__init__.py +7 -0
  59. segment_everything/vendored/efficientvit/models/utils/list.py +53 -0
  60. segment_everything/vendored/efficientvit/models/utils/network.py +73 -0
  61. segment_everything/vendored/efficientvit/models/utils/random.py +65 -0
  62. segment_everything/vendored/efficientvit/sam_model_zoo.py +45 -0
  63. segment_everything/vendored/efficientvit/seg_model_zoo.py +70 -0
  64. segment_everything/vendored/get_object_aware.py +26 -0
  65. segment_everything/vendored/mobilesamv2/__init__.py +16 -0
  66. segment_everything/vendored/mobilesamv2/automatic_mask_generator.py +415 -0
  67. segment_everything/vendored/mobilesamv2/build_sam.py +246 -0
  68. segment_everything/vendored/mobilesamv2/modeling/__init__.py +11 -0
  69. segment_everything/vendored/mobilesamv2/modeling/common.py +43 -0
  70. segment_everything/vendored/mobilesamv2/modeling/image_encoder.py +394 -0
  71. segment_everything/vendored/mobilesamv2/modeling/mask_decoder.py +213 -0
  72. segment_everything/vendored/mobilesamv2/modeling/prompt_encoder.py +217 -0
  73. segment_everything/vendored/mobilesamv2/modeling/sam.py +203 -0
  74. segment_everything/vendored/mobilesamv2/modeling/transformer.py +240 -0
  75. segment_everything/vendored/mobilesamv2/predictor.py +384 -0
  76. segment_everything/vendored/mobilesamv2/utils/__init__.py +5 -0
  77. segment_everything/vendored/mobilesamv2/utils/amg.py +347 -0
  78. segment_everything/vendored/mobilesamv2/utils/onnx.py +144 -0
  79. segment_everything/vendored/mobilesamv2/utils/transforms.py +103 -0
  80. segment_everything/vendored/object_detection/__init__.py +0 -0
  81. segment_everything/vendored/object_detection/ultralytics/__init__.py +5 -0
  82. segment_everything/vendored/object_detection/ultralytics/nn/__init__.py +9 -0
  83. segment_everything/vendored/object_detection/ultralytics/nn/autobackend.py +658 -0
  84. segment_everything/vendored/object_detection/ultralytics/nn/autoshape.py +397 -0
  85. segment_everything/vendored/object_detection/ultralytics/nn/modules/__init__.py +110 -0
  86. segment_everything/vendored/object_detection/ultralytics/nn/modules/block.py +304 -0
  87. segment_everything/vendored/object_detection/ultralytics/nn/modules/conv.py +297 -0
  88. segment_everything/vendored/object_detection/ultralytics/nn/modules/head.py +468 -0
  89. segment_everything/vendored/object_detection/ultralytics/nn/modules/transformer.py +378 -0
  90. segment_everything/vendored/object_detection/ultralytics/nn/modules/utils.py +78 -0
  91. segment_everything/vendored/object_detection/ultralytics/nn/tasks.py +1049 -0
  92. segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/__init__.py +6 -0
  93. segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/model.py +104 -0
  94. segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/predict.py +95 -0
  95. segment_everything/vendored/object_detection/ultralytics/yolo/__init__.py +5 -0
  96. segment_everything/vendored/object_detection/ultralytics/yolo/cfg/__init__.py +588 -0
  97. segment_everything/vendored/object_detection/ultralytics/yolo/cfg/default.yaml +117 -0
  98. segment_everything/vendored/object_detection/ultralytics/yolo/data/__init__.py +9 -0
  99. segment_everything/vendored/object_detection/ultralytics/yolo/data/annotator.py +53 -0
  100. segment_everything/vendored/object_detection/ultralytics/yolo/data/augment.py +899 -0
  101. segment_everything/vendored/object_detection/ultralytics/yolo/data/base.py +286 -0
  102. segment_everything/vendored/object_detection/ultralytics/yolo/data/build.py +213 -0
  103. segment_everything/vendored/object_detection/ultralytics/yolo/data/converter.py +358 -0
  104. segment_everything/vendored/object_detection/ultralytics/yolo/data/dataloaders/__init__.py +0 -0
  105. segment_everything/vendored/object_detection/ultralytics/yolo/data/dataloaders/stream_loaders.py +459 -0
  106. segment_everything/vendored/object_detection/ultralytics/yolo/data/dataset.py +274 -0
  107. segment_everything/vendored/object_detection/ultralytics/yolo/data/dataset_wrappers.py +53 -0
  108. segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/download_weights.sh +18 -0
  109. segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_coco.sh +60 -0
  110. segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_coco128.sh +17 -0
  111. segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_imagenet.sh +51 -0
  112. segment_everything/vendored/object_detection/ultralytics/yolo/data/utils.py +716 -0
  113. segment_everything/vendored/object_detection/ultralytics/yolo/engine/__init__.py +0 -0
  114. segment_everything/vendored/object_detection/ultralytics/yolo/engine/exporter.py +1214 -0
  115. segment_everything/vendored/object_detection/ultralytics/yolo/engine/model.py +641 -0
  116. segment_everything/vendored/object_detection/ultralytics/yolo/engine/predictor.py +461 -0
  117. segment_everything/vendored/object_detection/ultralytics/yolo/engine/results.py +741 -0
  118. segment_everything/vendored/object_detection/ultralytics/yolo/utils/__init__.py +893 -0
  119. segment_everything/vendored/object_detection/ultralytics/yolo/utils/autobatch.py +108 -0
  120. segment_everything/vendored/object_detection/ultralytics/yolo/utils/callbacks/__init__.py +5 -0
  121. segment_everything/vendored/object_detection/ultralytics/yolo/utils/callbacks/base.py +212 -0
  122. segment_everything/vendored/object_detection/ultralytics/yolo/utils/checks.py +547 -0
  123. segment_everything/vendored/object_detection/ultralytics/yolo/utils/dist.py +67 -0
  124. segment_everything/vendored/object_detection/ultralytics/yolo/utils/downloads.py +353 -0
  125. segment_everything/vendored/object_detection/ultralytics/yolo/utils/errors.py +12 -0
  126. segment_everything/vendored/object_detection/ultralytics/yolo/utils/files.py +100 -0
  127. segment_everything/vendored/object_detection/ultralytics/yolo/utils/instance.py +391 -0
  128. segment_everything/vendored/object_detection/ultralytics/yolo/utils/loss.py +579 -0
  129. segment_everything/vendored/object_detection/ultralytics/yolo/utils/metrics.py +1189 -0
  130. segment_everything/vendored/object_detection/ultralytics/yolo/utils/ops.py +870 -0
  131. segment_everything/vendored/object_detection/ultralytics/yolo/utils/patches.py +45 -0
  132. segment_everything/vendored/object_detection/ultralytics/yolo/utils/plotting.py +767 -0
  133. segment_everything/vendored/object_detection/ultralytics/yolo/utils/tal.py +276 -0
  134. segment_everything/vendored/object_detection/ultralytics/yolo/utils/torch_utils.py +684 -0
  135. segment_everything/vendored/object_detection/ultralytics/yolo/utils/tuner.py +54 -0
  136. segment_everything/vendored/object_detection/ultralytics/yolo/v8/__init__.py +5 -0
  137. segment_everything/vendored/object_detection/ultralytics/yolo/v8/detect/__init__.py +5 -0
  138. segment_everything/vendored/object_detection/ultralytics/yolo/v8/detect/predict.py +69 -0
  139. segment_everything/vendored/tinyvit/__init__.py +2 -0
  140. segment_everything/vendored/tinyvit/tiny_vit.py +867 -0
  141. segment_everything/weights_helper.py +124 -0
  142. segment_everything-0.1.0.dist-info/METADATA +53 -0
  143. segment_everything-0.1.0.dist-info/RECORD +145 -0
  144. segment_everything-0.1.0.dist-info/WHEEL +4 -0
  145. segment_everything-0.1.0.dist-info/licenses/LICENSE +28 -0
@@ -0,0 +1,870 @@
1
+ # Ultralytics YOLO 🚀, AGPL-3.0 license
2
+
3
+ import contextlib
4
+ import math
5
+ import re
6
+ import time
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torchvision
13
+
14
+ from ..utils import LOGGER
15
+
16
+ from .metrics import box_iou
17
+
18
+
19
+ class Profile(contextlib.ContextDecorator):
20
+ """
21
+ YOLOv8 Profile class.
22
+ Usage: as a decorator with @Profile() or as a context manager with 'with Profile():'
23
+ """
24
+
25
+ def __init__(self, t=0.0):
26
+ """
27
+ Initialize the Profile class.
28
+
29
+ Args:
30
+ t (float): Initial time. Defaults to 0.0.
31
+ """
32
+ self.t = t
33
+ self.cuda = torch.cuda.is_available()
34
+
35
+ def __enter__(self):
36
+ """
37
+ Start timing.
38
+ """
39
+ self.start = self.time()
40
+ return self
41
+
42
+ def __exit__(self, type, value, traceback):
43
+ """
44
+ Stop timing.
45
+ """
46
+ self.dt = self.time() - self.start # delta-time
47
+ self.t += self.dt # accumulate dt
48
+
49
+ def time(self):
50
+ """
51
+ Get current time.
52
+ """
53
+ if self.cuda:
54
+ torch.cuda.synchronize()
55
+ return time.time()
56
+
57
+
58
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
59
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
60
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
61
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
62
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
63
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
64
+ return [
65
+ 1,
66
+ 2,
67
+ 3,
68
+ 4,
69
+ 5,
70
+ 6,
71
+ 7,
72
+ 8,
73
+ 9,
74
+ 10,
75
+ 11,
76
+ 13,
77
+ 14,
78
+ 15,
79
+ 16,
80
+ 17,
81
+ 18,
82
+ 19,
83
+ 20,
84
+ 21,
85
+ 22,
86
+ 23,
87
+ 24,
88
+ 25,
89
+ 27,
90
+ 28,
91
+ 31,
92
+ 32,
93
+ 33,
94
+ 34,
95
+ 35,
96
+ 36,
97
+ 37,
98
+ 38,
99
+ 39,
100
+ 40,
101
+ 41,
102
+ 42,
103
+ 43,
104
+ 44,
105
+ 46,
106
+ 47,
107
+ 48,
108
+ 49,
109
+ 50,
110
+ 51,
111
+ 52,
112
+ 53,
113
+ 54,
114
+ 55,
115
+ 56,
116
+ 57,
117
+ 58,
118
+ 59,
119
+ 60,
120
+ 61,
121
+ 62,
122
+ 63,
123
+ 64,
124
+ 65,
125
+ 67,
126
+ 70,
127
+ 72,
128
+ 73,
129
+ 74,
130
+ 75,
131
+ 76,
132
+ 77,
133
+ 78,
134
+ 79,
135
+ 80,
136
+ 81,
137
+ 82,
138
+ 84,
139
+ 85,
140
+ 86,
141
+ 87,
142
+ 88,
143
+ 89,
144
+ 90,
145
+ ]
146
+
147
+
148
+ def segment2box(segment, width=640, height=640):
149
+ """
150
+ Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
151
+
152
+ Args:
153
+ segment (torch.Tensor): the segment label
154
+ width (int): the width of the image. Defaults to 640
155
+ height (int): The height of the image. Defaults to 640
156
+
157
+ Returns:
158
+ (np.ndarray): the minimum and maximum x and y values of the segment.
159
+ """
160
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
161
+ x, y = segment.T # segment xy
162
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
163
+ (
164
+ x,
165
+ y,
166
+ ) = (
167
+ x[inside],
168
+ y[inside],
169
+ )
170
+ return (
171
+ np.array([x.min(), y.min(), x.max(), y.max()], dtype=segment.dtype)
172
+ if any(x)
173
+ else np.zeros(4, dtype=segment.dtype)
174
+ ) # xyxy
175
+
176
+
177
+ def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
178
+ """
179
+ Rescales bounding boxes (in the format of xyxy) from the shape of the image they were originally specified in
180
+ (img1_shape) to the shape of a different image (img0_shape).
181
+
182
+ Args:
183
+ img1_shape (tuple): The shape of the image that the bounding boxes are for, in the format of (height, width).
184
+ boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)
185
+ img0_shape (tuple): the shape of the target image, in the format of (height, width).
186
+ ratio_pad (tuple): a tuple of (ratio, pad) for scaling the boxes. If not provided, the ratio and pad will be
187
+ calculated based on the size difference between the two images.
188
+
189
+ Returns:
190
+ boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)
191
+ """
192
+ if ratio_pad is None: # calculate from img0_shape
193
+ gain = min(
194
+ img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]
195
+ ) # gain = old / new
196
+ pad = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1), round(
197
+ (img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1
198
+ ) # wh padding
199
+ else:
200
+ gain = ratio_pad[0][0]
201
+ pad = ratio_pad[1]
202
+
203
+ boxes[..., [0, 2]] -= pad[0] # x padding
204
+ boxes[..., [1, 3]] -= pad[1] # y padding
205
+ boxes[..., :4] /= gain
206
+ clip_boxes(boxes, img0_shape)
207
+ return boxes
208
+
209
+
210
+ def make_divisible(x, divisor):
211
+ """
212
+ Returns the nearest number that is divisible by the given divisor.
213
+
214
+ Args:
215
+ x (int): The number to make divisible.
216
+ divisor (int | torch.Tensor): The divisor.
217
+
218
+ Returns:
219
+ (int): The nearest number divisible by the divisor.
220
+ """
221
+ if isinstance(divisor, torch.Tensor):
222
+ divisor = int(divisor.max()) # to int
223
+ return math.ceil(x / divisor) * divisor
224
+
225
+
226
+ def non_max_suppression(
227
+ prediction,
228
+ conf_thres=0.25,
229
+ iou_thres=0.45,
230
+ classes=None,
231
+ agnostic=False,
232
+ multi_label=False,
233
+ labels=(),
234
+ max_det=300,
235
+ nc=0, # number of classes (optional)
236
+ max_time_img=0.05,
237
+ max_nms=30000,
238
+ max_wh=7680,
239
+ ):
240
+ """
241
+ Perform non-maximum suppression (NMS) on a set of boxes, with support for masks and multiple labels per box.
242
+
243
+ Arguments:
244
+ prediction (torch.Tensor): A tensor of shape (batch_size, num_classes + 4 + num_masks, num_boxes)
245
+ containing the predicted boxes, classes, and masks. The tensor should be in the format
246
+ output by a model, such as YOLO.
247
+ conf_thres (float): The confidence threshold below which boxes will be filtered out.
248
+ Valid values are between 0.0 and 1.0.
249
+ iou_thres (float): The IoU threshold below which boxes will be filtered out during NMS.
250
+ Valid values are between 0.0 and 1.0.
251
+ classes (List[int]): A list of class indices to consider. If None, all classes will be considered.
252
+ agnostic (bool): If True, the model is agnostic to the number of classes, and all
253
+ classes will be considered as one.
254
+ multi_label (bool): If True, each box may have multiple labels.
255
+ labels (List[List[Union[int, float, torch.Tensor]]]): A list of lists, where each inner
256
+ list contains the apriori labels for a given image. The list should be in the format
257
+ output by a dataloader, with each label being a tuple of (class_index, x1, y1, x2, y2).
258
+ max_det (int): The maximum number of boxes to keep after NMS.
259
+ nc (int, optional): The number of classes output by the model. Any indices after this will be considered masks.
260
+ max_time_img (float): The maximum time (seconds) for processing one image.
261
+ max_nms (int): The maximum number of boxes into torchvision.ops.nms().
262
+ max_wh (int): The maximum box width and height in pixels
263
+
264
+ Returns:
265
+ (List[torch.Tensor]): A list of length batch_size, where each element is a tensor of
266
+ shape (num_boxes, 6 + num_masks) containing the kept boxes, with columns
267
+ (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).
268
+ """
269
+
270
+ # Checks
271
+ assert (
272
+ 0 <= conf_thres <= 1
273
+ ), f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0"
274
+ assert (
275
+ 0 <= iou_thres <= 1
276
+ ), f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0"
277
+ if isinstance(
278
+ prediction, (list, tuple)
279
+ ): # YOLOv8 model in validation model, output = (inference_out, loss_out)
280
+ prediction = prediction[0] # select only inference output
281
+
282
+ device = prediction.device
283
+ mps = "mps" in device.type # Apple MPS
284
+ if mps: # MPS not fully supported yet, convert tensors to CPU before NMS
285
+ prediction = prediction.cpu()
286
+ bs = prediction.shape[0] # batch size
287
+ nc = nc or (prediction.shape[1] - 4) # number of classes
288
+ nm = prediction.shape[1] - nc - 4
289
+ mi = 4 + nc # mask start index
290
+ xc = prediction[:, 4:mi].amax(1) > conf_thres # candidates
291
+
292
+ # Settings
293
+ # min_wh = 2 # (pixels) minimum box width and height
294
+ time_limit = 0.5 + max_time_img * bs # seconds to quit after
295
+ redundant = True # require redundant detections
296
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
297
+ merge = False # use merge-NMS
298
+
299
+ t = time.time()
300
+ output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs
301
+ for xi, x in enumerate(prediction): # image index, image inference
302
+ # Apply constraints
303
+ # x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0 # width-height
304
+ x = x.transpose(0, -1)[xc[xi]] # confidence
305
+
306
+ # Cat apriori labels if autolabelling
307
+ if labels and len(labels[xi]):
308
+ lb = labels[xi]
309
+ v = torch.zeros((len(lb), nc + nm + 5), device=x.device)
310
+ v[:, :4] = lb[:, 1:5] # box
311
+ v[range(len(lb)), lb[:, 0].long() + 4] = 1.0 # cls
312
+ x = torch.cat((x, v), 0)
313
+
314
+ # If none remain process next image
315
+ if not x.shape[0]:
316
+ continue
317
+
318
+ # Detections matrix nx6 (xyxy, conf, cls)
319
+ box, cls, mask = x.split((4, nc, nm), 1)
320
+ box = xywh2xyxy(
321
+ box
322
+ ) # center_x, center_y, width, height) to (x1, y1, x2, y2)
323
+ if multi_label:
324
+ i, j = (cls > conf_thres).nonzero(as_tuple=False).T
325
+ x = torch.cat(
326
+ (box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1
327
+ )
328
+ else: # best class only
329
+ conf, j = cls.max(1, keepdim=True)
330
+ x = torch.cat((box, conf, j.float(), mask), 1)[
331
+ conf.view(-1) > conf_thres
332
+ ]
333
+
334
+ # Filter by class
335
+ if classes is not None:
336
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
337
+
338
+ # Apply finite constraint
339
+ # if not torch.isfinite(x).all():
340
+ # x = x[torch.isfinite(x).all(1)]
341
+
342
+ # Check shape
343
+ n = x.shape[0] # number of boxes
344
+ if not n: # no boxes
345
+ continue
346
+ x = x[
347
+ x[:, 4].argsort(descending=True)[:max_nms]
348
+ ] # sort by confidence and remove excess boxes
349
+
350
+ # Batched NMS
351
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
352
+ boxes, scores = (
353
+ x[:, :4] + c,
354
+ x[:, 4],
355
+ ) # boxes (offset by class), scores
356
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
357
+ i = i[:max_det] # limit detections
358
+ if merge and (
359
+ 1 < n < 3e3
360
+ ): # Merge NMS (boxes merged using weighted mean)
361
+ # Update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
362
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
363
+ weights = iou * scores[None] # box weights
364
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(
365
+ 1, keepdim=True
366
+ ) # merged boxes
367
+ if redundant:
368
+ i = i[iou.sum(1) > 1] # require redundancy
369
+
370
+ output[xi] = x[i]
371
+ if mps:
372
+ output[xi] = output[xi].to(device)
373
+ if (time.time() - t) > time_limit:
374
+ LOGGER.warning(
375
+ f"WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded"
376
+ )
377
+ break # time limit exceeded
378
+
379
+ return output
380
+
381
+
382
+ def clip_boxes(boxes, shape):
383
+ """
384
+ It takes a list of bounding boxes and a shape (height, width) and clips the bounding boxes to the
385
+ shape
386
+
387
+ Args:
388
+ boxes (torch.Tensor): the bounding boxes to clip
389
+ shape (tuple): the shape of the image
390
+ """
391
+ if isinstance(boxes, torch.Tensor): # faster individually
392
+ boxes[..., 0].clamp_(0, shape[1]) # x1
393
+ boxes[..., 1].clamp_(0, shape[0]) # y1
394
+ boxes[..., 2].clamp_(0, shape[1]) # x2
395
+ boxes[..., 3].clamp_(0, shape[0]) # y2
396
+ else: # np.array (faster grouped)
397
+ boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1]) # x1, x2
398
+ boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0]) # y1, y2
399
+
400
+
401
+ def clip_coords(coords, shape):
402
+ """
403
+ Clip line coordinates to the image boundaries.
404
+
405
+ Args:
406
+ coords (torch.Tensor | numpy.ndarray): A list of line coordinates.
407
+ shape (tuple): A tuple of integers representing the size of the image in the format (height, width).
408
+
409
+ Returns:
410
+ (None): The function modifies the input `coordinates` in place, by clipping each coordinate to the image boundaries.
411
+ """
412
+ if isinstance(coords, torch.Tensor): # faster individually
413
+ coords[..., 0].clamp_(0, shape[1]) # x
414
+ coords[..., 1].clamp_(0, shape[0]) # y
415
+ else: # np.array (faster grouped)
416
+ coords[..., 0] = coords[..., 0].clip(0, shape[1]) # x
417
+ coords[..., 1] = coords[..., 1].clip(0, shape[0]) # y
418
+
419
+
420
+ def scale_image(masks, im0_shape, ratio_pad=None):
421
+ """
422
+ Takes a mask, and resizes it to the original image size
423
+
424
+ Args:
425
+ masks (torch.Tensor): resized and padded masks/images, [h, w, num]/[h, w, 3].
426
+ im0_shape (tuple): the original image shape
427
+ ratio_pad (tuple): the ratio of the padding to the original image.
428
+
429
+ Returns:
430
+ masks (torch.Tensor): The masks that are being returned.
431
+ """
432
+ # Rescale coordinates (xyxy) from im1_shape to im0_shape
433
+ im1_shape = masks.shape
434
+ if im1_shape[:2] == im0_shape[:2]:
435
+ return masks
436
+ if ratio_pad is None: # calculate from im0_shape
437
+ gain = min(
438
+ im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]
439
+ ) # gain = old / new
440
+ pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (
441
+ im1_shape[0] - im0_shape[0] * gain
442
+ ) / 2 # wh padding
443
+ else:
444
+ gain = ratio_pad[0][0]
445
+ pad = ratio_pad[1]
446
+ top, left = int(pad[1]), int(pad[0]) # y, x
447
+ bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])
448
+
449
+ if len(masks.shape) < 2:
450
+ raise ValueError(
451
+ f'"len of masks shape" should be 2 or 3, but got {len(masks.shape)}'
452
+ )
453
+ masks = masks[top:bottom, left:right]
454
+ # masks = masks.permute(2, 0, 1).contiguous()
455
+ # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]
456
+ # masks = masks.permute(1, 2, 0).contiguous()
457
+ cv_limit = 512
458
+ if masks.shape[2] <= cv_limit:
459
+ masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))
460
+ else:
461
+ # split masks array on batches with max size 512 along channel axis, resize and merge them back
462
+ masks = np.concatenate(
463
+ [
464
+ cv2.resize(
465
+ masks[:, :, i : min(i + cv_limit, masks.shape[2])],
466
+ (im0_shape[1], im0_shape[0]),
467
+ )
468
+ for i in range(0, masks.shape[2], cv_limit)
469
+ ],
470
+ axis=2,
471
+ )
472
+ if len(masks.shape) == 2:
473
+ masks = masks[:, :, None]
474
+
475
+ return masks
476
+
477
+
478
+ def xyxy2xywh(x):
479
+ """
480
+ Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format.
481
+
482
+ Args:
483
+ x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.
484
+ Returns:
485
+ y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height) format.
486
+ """
487
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
488
+ y[..., 0] = (x[..., 0] + x[..., 2]) / 2 # x center
489
+ y[..., 1] = (x[..., 1] + x[..., 3]) / 2 # y center
490
+ y[..., 2] = x[..., 2] - x[..., 0] # width
491
+ y[..., 3] = x[..., 3] - x[..., 1] # height
492
+ return y
493
+
494
+
495
+ def xywh2xyxy(x):
496
+ """
497
+ Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is the
498
+ top-left corner and (x2, y2) is the bottom-right corner.
499
+
500
+ Args:
501
+ x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x, y, width, height) format.
502
+ Returns:
503
+ y (np.ndarray | torch.Tensor): The bounding box coordinates in (x1, y1, x2, y2) format.
504
+ """
505
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
506
+ y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
507
+ y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
508
+ y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x
509
+ y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y
510
+ return y
511
+
512
+
513
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
514
+ """
515
+ Convert normalized bounding box coordinates to pixel coordinates.
516
+
517
+ Args:
518
+ x (np.ndarray | torch.Tensor): The bounding box coordinates.
519
+ w (int): Width of the image. Defaults to 640
520
+ h (int): Height of the image. Defaults to 640
521
+ padw (int): Padding width. Defaults to 0
522
+ padh (int): Padding height. Defaults to 0
523
+ Returns:
524
+ y (np.ndarray | torch.Tensor): The coordinates of the bounding box in the format [x1, y1, x2, y2] where
525
+ x1,y1 is the top-left corner, x2,y2 is the bottom-right corner of the bounding box.
526
+ """
527
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
528
+ y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw # top left x
529
+ y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh # top left y
530
+ y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw # bottom right x
531
+ y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh # bottom right y
532
+ return y
533
+
534
+
535
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
536
+ """
537
+ Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height, normalized) format.
538
+ x, y, width and height are normalized to image dimensions
539
+
540
+ Args:
541
+ x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.
542
+ w (int): The width of the image. Defaults to 640
543
+ h (int): The height of the image. Defaults to 640
544
+ clip (bool): If True, the boxes will be clipped to the image boundaries. Defaults to False
545
+ eps (float): The minimum value of the box's width and height. Defaults to 0.0
546
+ Returns:
547
+ y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height, normalized) format
548
+ """
549
+ if clip:
550
+ clip_boxes(x, (h - eps, w - eps)) # warning: inplace clip
551
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
552
+ y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w # x center
553
+ y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h # y center
554
+ y[..., 2] = (x[..., 2] - x[..., 0]) / w # width
555
+ y[..., 3] = (x[..., 3] - x[..., 1]) / h # height
556
+ return y
557
+
558
+
559
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
560
+ """
561
+ Convert normalized coordinates to pixel coordinates of shape (n,2)
562
+
563
+ Args:
564
+ x (np.ndarray | torch.Tensor): The input tensor of normalized bounding box coordinates
565
+ w (int): The width of the image. Defaults to 640
566
+ h (int): The height of the image. Defaults to 640
567
+ padw (int): The width of the padding. Defaults to 0
568
+ padh (int): The height of the padding. Defaults to 0
569
+ Returns:
570
+ y (np.ndarray | torch.Tensor): The x and y coordinates of the top left corner of the bounding box
571
+ """
572
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
573
+ y[..., 0] = w * x[..., 0] + padw # top left x
574
+ y[..., 1] = h * x[..., 1] + padh # top left y
575
+ return y
576
+
577
+
578
+ def xywh2ltwh(x):
579
+ """
580
+ Convert the bounding box format from [x, y, w, h] to [x1, y1, w, h], where x1, y1 are the top-left coordinates.
581
+
582
+ Args:
583
+ x (np.ndarray | torch.Tensor): The input tensor with the bounding box coordinates in the xywh format
584
+ Returns:
585
+ y (np.ndarray | torch.Tensor): The bounding box coordinates in the xyltwh format
586
+ """
587
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
588
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
589
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
590
+ return y
591
+
592
+
593
+ def xyxy2ltwh(x):
594
+ """
595
+ Convert nx4 bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h], where xy1=top-left, xy2=bottom-right
596
+
597
+ Args:
598
+ x (np.ndarray | torch.Tensor): The input tensor with the bounding boxes coordinates in the xyxy format
599
+ Returns:
600
+ y (np.ndarray | torch.Tensor): The bounding box coordinates in the xyltwh format.
601
+ """
602
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
603
+ y[:, 2] = x[:, 2] - x[:, 0] # width
604
+ y[:, 3] = x[:, 3] - x[:, 1] # height
605
+ return y
606
+
607
+
608
+ def ltwh2xywh(x):
609
+ """
610
+ Convert nx4 boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center
611
+
612
+ Args:
613
+ x (torch.Tensor): the input tensor
614
+ """
615
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
616
+ y[:, 0] = x[:, 0] + x[:, 2] / 2 # center x
617
+ y[:, 1] = x[:, 1] + x[:, 3] / 2 # center y
618
+ return y
619
+
620
+
621
+ def ltwh2xyxy(x):
622
+ """
623
+ It converts the bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
624
+
625
+ Args:
626
+ x (np.ndarray | torch.Tensor): the input image
627
+
628
+ Returns:
629
+ y (np.ndarray | torch.Tensor): the xyxy coordinates of the bounding boxes.
630
+ """
631
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
632
+ y[:, 2] = x[:, 2] + x[:, 0] # width
633
+ y[:, 3] = x[:, 3] + x[:, 1] # height
634
+ return y
635
+
636
+
637
+ def segments2boxes(segments):
638
+ """
639
+ It converts segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
640
+
641
+ Args:
642
+ segments (list): list of segments, each segment is a list of points, each point is a list of x, y coordinates
643
+
644
+ Returns:
645
+ (np.ndarray): the xywh coordinates of the bounding boxes.
646
+ """
647
+ boxes = []
648
+ for s in segments:
649
+ x, y = s.T # segment xy
650
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
651
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
652
+
653
+
654
+ def resample_segments(segments, n=1000):
655
+ """
656
+ Inputs a list of segments (n,2) and returns a list of segments (n,2) up-sampled to n points each.
657
+
658
+ Args:
659
+ segments (list): a list of (n,2) arrays, where n is the number of points in the segment.
660
+ n (int): number of points to resample the segment to. Defaults to 1000
661
+
662
+ Returns:
663
+ segments (list): the resampled segments.
664
+ """
665
+ for i, s in enumerate(segments):
666
+ s = np.concatenate((s, s[0:1, :]), axis=0)
667
+ x = np.linspace(0, len(s) - 1, n)
668
+ xp = np.arange(len(s))
669
+ segments[i] = (
670
+ np.concatenate(
671
+ [np.interp(x, xp, s[:, i]) for i in range(2)], dtype=np.float32
672
+ )
673
+ .reshape(2, -1)
674
+ .T
675
+ ) # segment xy
676
+ return segments
677
+
678
+
679
+ def crop_mask(masks, boxes):
680
+ """
681
+ It takes a mask and a bounding box, and returns a mask that is cropped to the bounding box
682
+
683
+ Args:
684
+ masks (torch.Tensor): [h, w, n] tensor of masks
685
+ boxes (torch.Tensor): [n, 4] tensor of bbox coordinates in relative point form
686
+
687
+ Returns:
688
+ (torch.Tensor): The masks are being cropped to the bounding box.
689
+ """
690
+ n, h, w = masks.shape
691
+ x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(n,1,1)
692
+ r = torch.arange(w, device=masks.device, dtype=x1.dtype)[
693
+ None, None, :
694
+ ] # rows shape(1,1,w)
695
+ c = torch.arange(h, device=masks.device, dtype=x1.dtype)[
696
+ None, :, None
697
+ ] # cols shape(1,h,1)
698
+
699
+ return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))
700
+
701
+
702
+ def process_mask_upsample(protos, masks_in, bboxes, shape):
703
+ """
704
+ It takes the output of the mask head, and applies the mask to the bounding boxes. This produces masks of higher
705
+ quality but is slower.
706
+
707
+ Args:
708
+ protos (torch.Tensor): [mask_dim, mask_h, mask_w]
709
+ masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms
710
+ bboxes (torch.Tensor): [n, 4], n is number of masks after nms
711
+ shape (tuple): the size of the input image (h,w)
712
+
713
+ Returns:
714
+ (torch.Tensor): The upsampled masks.
715
+ """
716
+ c, mh, mw = protos.shape # CHW
717
+ masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
718
+ masks = F.interpolate(
719
+ masks[None], shape, mode="bilinear", align_corners=False
720
+ )[
721
+ 0
722
+ ] # CHW
723
+ masks = crop_mask(masks, bboxes) # CHW
724
+ return masks.gt_(0.5)
725
+
726
+
727
+ def process_mask(protos, masks_in, bboxes, shape, upsample=False):
728
+ """
729
+ Apply masks to bounding boxes using the output of the mask head.
730
+
731
+ Args:
732
+ protos (torch.Tensor): A tensor of shape [mask_dim, mask_h, mask_w].
733
+ masks_in (torch.Tensor): A tensor of shape [n, mask_dim], where n is the number of masks after NMS.
734
+ bboxes (torch.Tensor): A tensor of shape [n, 4], where n is the number of masks after NMS.
735
+ shape (tuple): A tuple of integers representing the size of the input image in the format (h, w).
736
+ upsample (bool): A flag to indicate whether to upsample the mask to the original image size. Default is False.
737
+
738
+ Returns:
739
+ (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS, and h and w
740
+ are the height and width of the input image. The mask is applied to the bounding boxes.
741
+ """
742
+
743
+ c, mh, mw = protos.shape # CHW
744
+ ih, iw = shape
745
+ masks = (
746
+ (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
747
+ ) # CHW
748
+
749
+ downsampled_bboxes = bboxes.clone()
750
+ downsampled_bboxes[:, 0] *= mw / iw
751
+ downsampled_bboxes[:, 2] *= mw / iw
752
+ downsampled_bboxes[:, 3] *= mh / ih
753
+ downsampled_bboxes[:, 1] *= mh / ih
754
+
755
+ masks = crop_mask(masks, downsampled_bboxes) # CHW
756
+ if upsample:
757
+ masks = F.interpolate(
758
+ masks[None], shape, mode="bilinear", align_corners=False
759
+ )[
760
+ 0
761
+ ] # CHW
762
+ return masks.gt_(0.5)
763
+
764
+
765
+ def process_mask_native(protos, masks_in, bboxes, shape):
766
+ """
767
+ It takes the output of the mask head, and crops it after upsampling to the bounding boxes.
768
+
769
+ Args:
770
+ protos (torch.Tensor): [mask_dim, mask_h, mask_w]
771
+ masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms
772
+ bboxes (torch.Tensor): [n, 4], n is number of masks after nms
773
+ shape (tuple): the size of the input image (h,w)
774
+
775
+ Returns:
776
+ masks (torch.Tensor): The returned masks with dimensions [h, w, n]
777
+ """
778
+ c, mh, mw = protos.shape # CHW
779
+ masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
780
+ gain = min(mh / shape[0], mw / shape[1]) # gain = old / new
781
+ pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding
782
+ top, left = int(pad[1]), int(pad[0]) # y, x
783
+ bottom, right = int(mh - pad[1]), int(mw - pad[0])
784
+ masks = masks[:, top:bottom, left:right]
785
+
786
+ masks = F.interpolate(
787
+ masks[None], shape, mode="bilinear", align_corners=False
788
+ )[
789
+ 0
790
+ ] # CHW
791
+ masks = crop_mask(masks, bboxes) # CHW
792
+ return masks.gt_(0.5)
793
+
794
+
795
+ def scale_coords(
796
+ img1_shape, coords, img0_shape, ratio_pad=None, normalize=False
797
+ ):
798
+ """
799
+ Rescale segment coordinates (xyxy) from img1_shape to img0_shape
800
+
801
+ Args:
802
+ img1_shape (tuple): The shape of the image that the coords are from.
803
+ coords (torch.Tensor): the coords to be scaled
804
+ img0_shape (tuple): the shape of the image that the segmentation is being applied to
805
+ ratio_pad (tuple): the ratio of the image size to the padded image size.
806
+ normalize (bool): If True, the coordinates will be normalized to the range [0, 1]. Defaults to False
807
+
808
+ Returns:
809
+ coords (torch.Tensor): the segmented image.
810
+ """
811
+ if ratio_pad is None: # calculate from img0_shape
812
+ gain = min(
813
+ img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]
814
+ ) # gain = old / new
815
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (
816
+ img1_shape[0] - img0_shape[0] * gain
817
+ ) / 2 # wh padding
818
+ else:
819
+ gain = ratio_pad[0][0]
820
+ pad = ratio_pad[1]
821
+
822
+ coords[..., 0] -= pad[0] # x padding
823
+ coords[..., 1] -= pad[1] # y padding
824
+ coords[..., 0] /= gain
825
+ coords[..., 1] /= gain
826
+ clip_coords(coords, img0_shape)
827
+ if normalize:
828
+ coords[..., 0] /= img0_shape[1] # width
829
+ coords[..., 1] /= img0_shape[0] # height
830
+ return coords
831
+
832
+
833
+ def masks2segments(masks, strategy="largest"):
834
+ """
835
+ It takes a list of masks(n,h,w) and returns a list of segments(n,xy)
836
+
837
+ Args:
838
+ masks (torch.Tensor): the output of the model, which is a tensor of shape (batch_size, 160, 160)
839
+ strategy (str): 'concat' or 'largest'. Defaults to largest
840
+
841
+ Returns:
842
+ segments (List): list of segment masks
843
+ """
844
+ segments = []
845
+ for x in masks.int().cpu().numpy().astype("uint8"):
846
+ c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
847
+ if c:
848
+ if strategy == "concat": # concatenate all segments
849
+ c = np.concatenate([x.reshape(-1, 2) for x in c])
850
+ elif strategy == "largest": # select largest segment
851
+ c = np.array(
852
+ c[np.array([len(x) for x in c]).argmax()]
853
+ ).reshape(-1, 2)
854
+ else:
855
+ c = np.zeros((0, 2)) # no segments found
856
+ segments.append(c.astype("float32"))
857
+ return segments
858
+
859
+
860
+ def clean_str(s):
861
+ """
862
+ Cleans a string by replacing special characters with underscore _
863
+
864
+ Args:
865
+ s (str): a string needing special characters replaced
866
+
867
+ Returns:
868
+ (str): a string with special characters replaced by an underscore _
869
+ """
870
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)