micro_sam.prompt_generators
Classes for generating prompts from ground-truth segmentation masks. For training or evaluation of prompt-based segmentation.
1""" 2Classes for generating prompts from ground-truth segmentation masks. 3For training or evaluation of prompt-based segmentation. 4""" 5 6from typing import List, Optional, Tuple 7 8import numpy as np 9from kornia import morphology 10from scipy.ndimage import distance_transform_edt, label as connected_components 11 12import torch 13 14 15class PromptGeneratorBase: 16 """PromptGeneratorBase is an interface to implement specific prompt generators. 17 """ 18 def __call__( 19 self, 20 segmentation: torch.Tensor, 21 prediction: Optional[torch.Tensor] = None, 22 bbox_coordinates: Optional[List[tuple]] = None, 23 center_coordinates: Optional[List[np.ndarray]] = None 24 ) -> Tuple[ 25 Optional[torch.Tensor], # the point coordinates 26 Optional[torch.Tensor], # the point labels 27 Optional[torch.Tensor], # the bounding boxes 28 Optional[torch.Tensor], # the mask prompts 29 ]: 30 """Return the point prompts given segmentation masks and optional other inputs. 31 32 Args: 33 segmentation: The object masks derived from instance segmentation groundtruth. 34 Expects a float tensor of shape NUM_OBJECTS x 1 x H x W. 35 The first axis corresponds to the binary object masks. 36 prediction: The predicted object masks corresponding to the segmentation. 37 Expects the same shape as the segmentation 38 bbox_coordinates: Precomputed bounding boxes for the segmentation. 39 Expects a list of length NUM_OBJECTS. 40 center_coordinates: Precomputed center coordinates for the segmentation. 41 Expects a list of length NUM_OBJECTS. 42 43 Returns: 44 The point prompt coordinates. Int tensor of shape NUM_OBJECTS x NUM_POINTS x 2. 45 The point coordinates are retuned in XY axis order. This means they are reversed compared 46 to the standard YX axis order used by numpy. 47 The point prompt labels. Int tensor of shape NUM_OBJECTS x NUM_POINTS. 48 The box prompts. Int tensor of shape NUM_OBJECTS x 4. 49 The box coordinates are retunred as MIN_X, MIN_Y, MAX_X, MAX_Y. 50 The mask prompts. Float tensor of shape NUM_OBJECTS x 1 x H' x W'. 51 With H' = W'= 256. 52 """ 53 raise NotImplementedError( 54 "PromptGeneratorBase is just a class template. " 55 "Use a child class that implements the specific generator instead" 56 ) 57 58 59class PointAndBoxPromptGenerator(PromptGeneratorBase): 60 """Generate point and/or box prompts from an instance segmentation. 61 62 You can use this class to derive prompts from an instance segmentation, either for 63 evaluation purposes or for training Segment Anything on custom data. 64 In order to use this generator you need to precompute the bounding boxes and center 65 coordiantes of the instance segmentation, using e.g. `util.get_centers_and_bounding_boxes`. 66 67 Here's an example for how to use this class: 68 ```python 69 # Initialize generator for 1 positive and 4 negative point prompts. 70 prompt_generator = PointAndBoxPromptGenerator(1, 4, dilation_strength=8) 71 72 # Precompute the bounding boxes for the given segmentation 73 bounding_boxes, _ = util.get_centers_and_bounding_boxes(segmentation) 74 75 # generate point prompts for the objects with ids 1, 2 and 3 76 seg_ids = (1, 2, 3) 77 object_mask = np.stack([segmentation == seg_id for seg_id in seg_ids])[:, None] 78 this_bounding_boxes = [bounding_boxes[seg_id] for seg_id in seg_ids] 79 point_coords, point_labels, _, _ = prompt_generator(object_mask, this_bounding_boxes) 80 ``` 81 82 Args: 83 n_positive_points: The number of positive point prompts to generate per mask. 84 n_negative_points: The number of negative point prompts to generate per mask. 85 dilation_strength: The factor by which the mask is dilated before generating prompts. 86 get_point_prompts: Whether to generate point prompts. By default, set to 'True'. 87 get_box_prompts: Whether to generate box prompts. By default, set to 'False'. 88 """ 89 def __init__( 90 self, 91 n_positive_points: int, 92 n_negative_points: int, 93 dilation_strength: int, 94 get_point_prompts: bool = True, 95 get_box_prompts: bool = False 96 ) -> None: 97 self.n_positive_points = n_positive_points 98 self.n_negative_points = n_negative_points 99 self.dilation_strength = dilation_strength 100 self.get_box_prompts = get_box_prompts 101 self.get_point_prompts = get_point_prompts 102 103 if self.get_point_prompts is False and self.get_box_prompts is False: 104 raise ValueError("You need to request box prompts, point prompts or both.") 105 106 def _sample_positive_points(self, object_mask, center_coordinates, coord_list, label_list): 107 if center_coordinates is not None: 108 # getting the center coordinate as the first positive point (OPTIONAL) 109 coord_list.append(tuple(map(int, center_coordinates))) # to get int coords instead of float 110 111 # getting the additional positive points by randomly sampling points 112 # from this mask except the center coordinate 113 n_positive_remaining = self.n_positive_points - 1 114 115 else: 116 # need to sample "self.n_positive_points" number of points 117 n_positive_remaining = self.n_positive_points 118 119 if n_positive_remaining > 0: 120 object_coordinates = torch.where(object_mask) 121 n_coordinates = len(object_coordinates[0]) 122 123 # randomly sampling n_positive_remaining_points from these coordinates 124 indices = np.random.choice( 125 n_coordinates, size=n_positive_remaining, 126 # Allow replacing if we can't sample enough coordinates otherwise 127 replace=True if n_positive_remaining > n_coordinates else False, 128 ) 129 coord_list.extend([ 130 [object_coordinates[0][idx], object_coordinates[1][idx]] for idx in indices 131 ]) 132 133 label_list.extend([1] * self.n_positive_points) 134 assert len(coord_list) == len(label_list) == self.n_positive_points 135 return coord_list, label_list 136 137 def _sample_negative_points(self, object_mask, bbox_coordinates, coord_list, label_list): 138 if self.n_negative_points == 0: 139 return coord_list, label_list 140 141 # getting the negative points 142 # for this we do the opposite and we set the mask to the bounding box - the object mask 143 # we need to dilate the object mask before doing this: we use kornia.morphology.dilation for this 144 dilated_object = object_mask[None, None] 145 for _ in range(self.dilation_strength): 146 dilated_object = morphology.dilation(dilated_object, torch.ones(3, 3), engine="convolution") 147 dilated_object = dilated_object.squeeze() 148 149 background_mask = torch.zeros(object_mask.shape, device=object_mask.device) 150 _ds = self.dilation_strength 151 background_mask[ 152 max(bbox_coordinates[0] - _ds, 0): min(bbox_coordinates[2] + _ds, object_mask.shape[-2]), 153 max(bbox_coordinates[1] - _ds, 0): min(bbox_coordinates[3] + _ds, object_mask.shape[-1]) 154 ] = 1 155 background_mask = torch.abs(background_mask - dilated_object) 156 157 # the valid background coordinates 158 background_coordinates = torch.where(background_mask) 159 n_coordinates = len(background_coordinates[0]) 160 161 # randomly sample the negative points from these coordinates 162 indices = np.random.choice( 163 n_coordinates, replace=False, 164 size=min(self.n_negative_points, n_coordinates) # handles the cases with insufficient bg pixels 165 ) 166 coord_list.extend([ 167 [background_coordinates[0][idx], background_coordinates[1][idx]] for idx in indices 168 ]) 169 label_list.extend([0] * len(indices)) 170 171 return coord_list, label_list 172 173 def _ensure_num_points(self, object_mask, coord_list, label_list): 174 num_points = self.n_positive_points + self.n_negative_points 175 176 # fill up to the necessary number of points if we did not sample enough of them 177 if len(coord_list) != num_points: 178 # to stay consistent, we add random points in the background of an object 179 # if there's no neg region around the object - usually happens with small rois 180 needed_points = num_points - len(coord_list) 181 more_neg_points = torch.where(object_mask == 0) 182 indices = np.random.choice(len(more_neg_points[0]), size=needed_points, replace=False) 183 184 coord_list.extend([ 185 (more_neg_points[0][idx], more_neg_points[1][idx]) for idx in indices 186 ]) 187 label_list.extend([0] * needed_points) 188 189 assert len(coord_list) == len(label_list) == num_points 190 return coord_list, label_list 191 192 # Can we batch this properly? 193 def _sample_points(self, segmentation, bbox_coordinates, center_coordinates): 194 all_coords, all_labels = [], [] 195 196 center_coordinates = [None] * len(segmentation) if center_coordinates is None else center_coordinates 197 for object_mask, bbox_coords, center_coords in zip(segmentation, bbox_coordinates, center_coordinates): 198 coord_list, label_list = [], [] 199 coord_list, label_list = self._sample_positive_points(object_mask[0], center_coords, coord_list, label_list) 200 coord_list, label_list = self._sample_negative_points(object_mask[0], bbox_coords, coord_list, label_list) 201 coord_list, label_list = self._ensure_num_points(object_mask[0], coord_list, label_list) 202 203 all_coords.append(coord_list) 204 all_labels.append(label_list) 205 206 return all_coords, all_labels 207 208 def __call__( 209 self, 210 segmentation: torch.Tensor, 211 bbox_coordinates: List[Tuple], 212 center_coordinates: Optional[List[np.ndarray]] = None, 213 **kwargs, 214 ) -> Tuple[ 215 Optional[torch.Tensor], 216 Optional[torch.Tensor], 217 Optional[torch.Tensor], 218 None 219 ]: 220 """Generate the prompts for one object in the segmentation. 221 222 Args: 223 The groundtruth segmentation. Expects a float tensor of shape NUM_OBJECTS x 1 x H x W. 224 bbox_coordinates: The precomputed bounding boxes of particular object in the segmentation. 225 center_coordinates: The precomputed center coordinates of particular object in the segmentation. 226 If passed, these coordinates will be used as the first positive point prompt. 227 If not passed a random point from within the object mask will be used. 228 229 Returns: 230 Coordinates of point prompts. Returns None, if get_point_prompts is false. 231 Point prompt labels. Returns None, if get_point_prompts is false. 232 Bounding box prompts. Returns None, if get_box_prompts is false. 233 """ 234 if self.get_point_prompts: 235 coord_list, label_list = self._sample_points(segmentation, bbox_coordinates, center_coordinates) 236 # change the axis convention of the point coordinates to match the expected coordinate order of SAM 237 coord_list = np.array(coord_list)[:, :, ::-1].copy() 238 coord_list = torch.from_numpy(coord_list) 239 label_list = torch.tensor(label_list) 240 else: 241 coord_list, label_list = None, None 242 243 if self.get_box_prompts: 244 # change the axis convention of the box coordinates to match the expected coordinate order of SAM 245 bbox_list = np.array(bbox_coordinates)[:, [1, 0, 3, 2]] 246 bbox_list = torch.from_numpy(bbox_list) 247 else: 248 bbox_list = None 249 250 return coord_list, label_list, bbox_list, None 251 252 253class IterativePromptGenerator(PromptGeneratorBase): 254 """Generate point prompts from an instance segmentation iteratively. 255 """ 256 def _get_positive_points(self, pos_region, overlap_region, is_3d): 257 positive_locations = [torch.where(pos_reg) for pos_reg in pos_region] 258 # we may have objects without a positive region (= missing true foreground) 259 # in this case we just sample a positive point where the model was already correct 260 positive_locations = [ 261 torch.where(ovlp_reg) if len(pos_loc[0]) == 0 else pos_loc 262 for pos_loc, ovlp_reg in zip(positive_locations, overlap_region) 263 ] 264 # we sample one positive location for each object in the batch 265 sampled_indices = [np.random.choice(len(pos_loc[0])) for pos_loc in positive_locations] 266 # get the corresponding coordinates (NOTE: we flip the axis order here due to the expected order of SAM) 267 if is_3d: 268 pos_coordinates = [ 269 [pos_loc[-1][idx], pos_loc[-2][idx], pos_loc[-3][idx]] 270 for pos_loc, idx in zip(positive_locations, sampled_indices) 271 ] 272 else: 273 pos_coordinates = [ 274 [pos_loc[-1][idx], pos_loc[-2][idx]] for pos_loc, idx in zip(positive_locations, sampled_indices) 275 ] 276 277 # make sure that we still have the correct batch size 278 assert len(pos_coordinates) == pos_region.shape[0] 279 pos_labels = [1] * len(pos_coordinates) 280 281 return pos_coordinates, pos_labels 282 283 def _get_negative_locations_in_obj_bbox(self, true_object, custom_df=3): 284 true_loc = torch.where(true_object) 285 bbox = torch.stack( 286 [torch.min(true_loc[1]), torch.min(true_loc[2]), torch.max(true_loc[1]) + 1, torch.max(true_loc[2]) + 1] 287 ) 288 289 # custom dilation factor to perform dilation by expanding the pixels of bbox 290 bbox_mask = torch.zeros_like(true_object).squeeze(0) 291 bbox_mask[ 292 max(bbox[0] - custom_df, 0): min(bbox[2] + custom_df, true_object.shape[-2]), 293 max(bbox[1] - custom_df, 0): min(bbox[3] + custom_df, true_object.shape[-1]) 294 ] = 1 295 bbox_mask = bbox_mask[None].to(true_object.device) 296 background_mask = torch.abs(bbox_mask - true_object) 297 return torch.where(background_mask) 298 299 def _get_negative_points(self, neg_region, true_object, is_3d): 300 # we have a valid negative region (i.e. a valid region where the model could not generate prediction) 301 negative_locations = [torch.where(neg_reg) for neg_reg in neg_region] 302 # we may have objects without a negative region (= no rectifications required) 303 # in this case we sample a negative point in outer periphery of the object inside the bounding box. 304 negative_locations = [ 305 self._get_negative_locations_in_obj_bbox(true_obj) if len(neg_loc[0]) == 0 else neg_loc 306 for neg_loc, true_obj in zip(negative_locations, true_object) 307 ] 308 # there is a chance that the object is small to not return a decent-sized bounding box 309 # hence we might not find points sometimes there as well. therefore, we sample points from true background. 310 negative_locations = [ 311 torch.where(true_obj == 0) if len(neg_loc[0]) == 0 else neg_loc 312 for neg_loc, true_obj in zip(negative_locations, true_object) 313 ] 314 # we sample one negative location for each object in the batch 315 sampled_indices = [np.random.choice(len(neg_loc[0])) for neg_loc in negative_locations] 316 # get the corresponding coordinates (NOTE: we flip the axis order here due to the expected order of SAM) 317 if is_3d: 318 neg_coordinates = [ 319 [neg_loc[-1][idx], neg_loc[-2][idx], neg_loc[-3][idx]] 320 for neg_loc, idx in zip(negative_locations, sampled_indices) 321 ] 322 else: 323 neg_coordinates = [ 324 [neg_loc[-1][idx], neg_loc[-2][idx]] for neg_loc, idx in zip(negative_locations, sampled_indices) 325 ] 326 327 # make sure that we still have the correct batch size 328 assert len(neg_coordinates) == neg_region.shape[0] 329 neg_labels = [0] * len(neg_coordinates) 330 331 return neg_coordinates, neg_labels 332 333 def __call__( 334 self, 335 segmentation: torch.Tensor, 336 prediction: torch.Tensor, 337 **kwargs, 338 ) -> Tuple[torch.Tensor, torch.Tensor, None, None]: 339 """Generate the prompts for each object iteratively in the segmentation. 340 341 Args: 342 segmentation: The groundtruth segmentation. 343 Expects a float tensor of shape (NUM_OBJECTS x 1 x H x W) or (NUM_OBJECTS x 1 x Z x H x W). 344 prediction: The predicted objects. Epects a float tensor of the same shape as the segmentation. 345 346 Returns: 347 The updated point prompt coordinates. 348 The updated point prompt labels. 349 """ 350 device = prediction.device 351 assert segmentation.shape == prediction.shape, \ 352 "The segmentation and prediction tensors should have the same shape." 353 354 if segmentation.ndim == 5: # masks in 3d must be tensors of shape NUM_OBJECTS x 1 x Z x H x W 355 is_3d = True 356 elif segmentation.ndim == 4: # masks in 2d must be tensors of shape NUM_OBJECTS x 1 x H x W 357 is_3d = False 358 else: 359 raise ValueError("The segmentation and prediction tensors should have either '4' or '5' dimensions.") 360 361 true_object = segmentation.to(device) 362 expected_diff = (prediction - true_object) 363 neg_region = (expected_diff == 1).to(torch.float32) 364 pos_region = (expected_diff == -1) 365 overlap_region = torch.logical_and(prediction == 1, true_object == 1).to(torch.float32) 366 367 pos_coordinates, pos_labels = self._get_positive_points(pos_region, overlap_region, is_3d) 368 neg_coordinates, neg_labels = self._get_negative_points(neg_region, true_object, is_3d) 369 assert len(pos_coordinates) == len(pos_labels) == len(neg_coordinates) == len(neg_labels) 370 371 pos_coordinates = torch.tensor(pos_coordinates)[:, None] 372 neg_coordinates = torch.tensor(neg_coordinates)[:, None] 373 pos_labels, neg_labels = torch.tensor(pos_labels)[:, None], torch.tensor(neg_labels)[:, None] 374 375 net_coords = torch.cat([pos_coordinates, neg_coordinates], dim=1) 376 net_labels = torch.cat([pos_labels, neg_labels], dim=1) 377 378 return net_coords, net_labels, None, None 379 380 381def _error_center(error): 382 regions, n_regions = connected_components(error) 383 if n_regions == 0: 384 return None 385 largest = regions == np.bincount(regions.ravel())[1:].argmax() + 1 386 distances = distance_transform_edt(np.pad(largest, 1))[1:-1, 1:-1] 387 y, x = np.unravel_index(distances.argmax(), distances.shape) 388 return [float(x), float(y)] 389 390 391def get_error_centers( 392 true_mask: np.ndarray, predicted_mask: np.ndarray 393) -> Tuple[Optional[List[float]], Optional[List[float]]]: 394 """Get the correction clicks of the 'center' protocol for one object in 2d. 395 396 The positive click is the center of the largest missed region and the negative click the center of the 397 largest added region, like the 'center' click sampling of RITM and SAM2. The center is the point with the 398 largest distance to the region border. 399 400 Args: 401 true_mask: The ground-truth mask of the object. 402 predicted_mask: The predicted mask of the object. 403 404 Returns: 405 The positive click as (x, y), or None if nothing is missed. 406 The negative click as (x, y), or None if nothing is added. 407 """ 408 # Both error regions lie within the bounding box of the object and its prediction, so only this crop is 409 # searched. The crop keeps the raster order of the pixels, so the centers are the same. 410 union = true_mask | predicted_mask 411 if not union.any(): 412 return None, None 413 rows, cols = np.where(union.any(axis=1))[0], np.where(union.any(axis=0))[0] 414 crop = np.s_[rows[0]:rows[-1] + 1, cols[0]:cols[-1] + 1] 415 true_crop, predicted_crop = true_mask[crop], predicted_mask[crop] 416 pos = _error_center(true_crop & ~predicted_crop) 417 neg = _error_center(predicted_crop & ~true_crop) 418 pos = None if pos is None else [pos[0] + cols[0], pos[1] + rows[0]] 419 neg = None if neg is None else [neg[0] + cols[0], neg[1] + rows[0]] 420 return pos, neg 421 422 423class CenterIterativePromptGenerator(PromptGeneratorBase): 424 """Generate point prompts at the centers of the prediction errors iteratively, for 2d evaluation. 425 426 Each object gets the clicks of `get_error_centers`. A missing error type gets a padding point with the 427 label -1, which the model ignores. 428 """ 429 430 def __call__( 431 self, 432 segmentation: torch.Tensor, 433 prediction: torch.Tensor, 434 **kwargs, 435 ) -> Tuple[torch.Tensor, torch.Tensor, None, None]: 436 """Generate the prompts for each object iteratively in the segmentation. 437 438 Args: 439 segmentation: The groundtruth segmentation. Expects a float tensor of shape (NUM_OBJECTS x 1 x H x W). 440 prediction: The predicted objects. Expects a float tensor of the same shape as the segmentation. 441 442 Returns: 443 The point prompt coordinates, of shape (NUM_OBJECTS x 2 x 2). 444 The point prompt labels, of shape (NUM_OBJECTS x 2). 445 """ 446 assert segmentation.shape == prediction.shape, \ 447 "The segmentation and prediction tensors should have the same shape." 448 if segmentation.ndim != 4: 449 raise ValueError("The segmentation and prediction tensors should have '4' dimensions.") 450 451 true_objects = segmentation.bool().cpu().numpy()[:, 0] 452 predicted_objects = prediction.bool().cpu().numpy()[:, 0] 453 coordinates, labels = [], [] 454 for true_object, predicted_object in zip(true_objects, predicted_objects): 455 pos, neg = get_error_centers(true_object, predicted_object) 456 coordinates.append([pos or [0.0, 0.0], neg or [0.0, 0.0]]) 457 labels.append([1 if pos else -1, 0 if neg else -1]) 458 459 return torch.tensor(coordinates), torch.tensor(labels), None, None
16class PromptGeneratorBase: 17 """PromptGeneratorBase is an interface to implement specific prompt generators. 18 """ 19 def __call__( 20 self, 21 segmentation: torch.Tensor, 22 prediction: Optional[torch.Tensor] = None, 23 bbox_coordinates: Optional[List[tuple]] = None, 24 center_coordinates: Optional[List[np.ndarray]] = None 25 ) -> Tuple[ 26 Optional[torch.Tensor], # the point coordinates 27 Optional[torch.Tensor], # the point labels 28 Optional[torch.Tensor], # the bounding boxes 29 Optional[torch.Tensor], # the mask prompts 30 ]: 31 """Return the point prompts given segmentation masks and optional other inputs. 32 33 Args: 34 segmentation: The object masks derived from instance segmentation groundtruth. 35 Expects a float tensor of shape NUM_OBJECTS x 1 x H x W. 36 The first axis corresponds to the binary object masks. 37 prediction: The predicted object masks corresponding to the segmentation. 38 Expects the same shape as the segmentation 39 bbox_coordinates: Precomputed bounding boxes for the segmentation. 40 Expects a list of length NUM_OBJECTS. 41 center_coordinates: Precomputed center coordinates for the segmentation. 42 Expects a list of length NUM_OBJECTS. 43 44 Returns: 45 The point prompt coordinates. Int tensor of shape NUM_OBJECTS x NUM_POINTS x 2. 46 The point coordinates are retuned in XY axis order. This means they are reversed compared 47 to the standard YX axis order used by numpy. 48 The point prompt labels. Int tensor of shape NUM_OBJECTS x NUM_POINTS. 49 The box prompts. Int tensor of shape NUM_OBJECTS x 4. 50 The box coordinates are retunred as MIN_X, MIN_Y, MAX_X, MAX_Y. 51 The mask prompts. Float tensor of shape NUM_OBJECTS x 1 x H' x W'. 52 With H' = W'= 256. 53 """ 54 raise NotImplementedError( 55 "PromptGeneratorBase is just a class template. " 56 "Use a child class that implements the specific generator instead" 57 )
PromptGeneratorBase is an interface to implement specific prompt generators.
60class PointAndBoxPromptGenerator(PromptGeneratorBase): 61 """Generate point and/or box prompts from an instance segmentation. 62 63 You can use this class to derive prompts from an instance segmentation, either for 64 evaluation purposes or for training Segment Anything on custom data. 65 In order to use this generator you need to precompute the bounding boxes and center 66 coordiantes of the instance segmentation, using e.g. `util.get_centers_and_bounding_boxes`. 67 68 Here's an example for how to use this class: 69 ```python 70 # Initialize generator for 1 positive and 4 negative point prompts. 71 prompt_generator = PointAndBoxPromptGenerator(1, 4, dilation_strength=8) 72 73 # Precompute the bounding boxes for the given segmentation 74 bounding_boxes, _ = util.get_centers_and_bounding_boxes(segmentation) 75 76 # generate point prompts for the objects with ids 1, 2 and 3 77 seg_ids = (1, 2, 3) 78 object_mask = np.stack([segmentation == seg_id for seg_id in seg_ids])[:, None] 79 this_bounding_boxes = [bounding_boxes[seg_id] for seg_id in seg_ids] 80 point_coords, point_labels, _, _ = prompt_generator(object_mask, this_bounding_boxes) 81 ``` 82 83 Args: 84 n_positive_points: The number of positive point prompts to generate per mask. 85 n_negative_points: The number of negative point prompts to generate per mask. 86 dilation_strength: The factor by which the mask is dilated before generating prompts. 87 get_point_prompts: Whether to generate point prompts. By default, set to 'True'. 88 get_box_prompts: Whether to generate box prompts. By default, set to 'False'. 89 """ 90 def __init__( 91 self, 92 n_positive_points: int, 93 n_negative_points: int, 94 dilation_strength: int, 95 get_point_prompts: bool = True, 96 get_box_prompts: bool = False 97 ) -> None: 98 self.n_positive_points = n_positive_points 99 self.n_negative_points = n_negative_points 100 self.dilation_strength = dilation_strength 101 self.get_box_prompts = get_box_prompts 102 self.get_point_prompts = get_point_prompts 103 104 if self.get_point_prompts is False and self.get_box_prompts is False: 105 raise ValueError("You need to request box prompts, point prompts or both.") 106 107 def _sample_positive_points(self, object_mask, center_coordinates, coord_list, label_list): 108 if center_coordinates is not None: 109 # getting the center coordinate as the first positive point (OPTIONAL) 110 coord_list.append(tuple(map(int, center_coordinates))) # to get int coords instead of float 111 112 # getting the additional positive points by randomly sampling points 113 # from this mask except the center coordinate 114 n_positive_remaining = self.n_positive_points - 1 115 116 else: 117 # need to sample "self.n_positive_points" number of points 118 n_positive_remaining = self.n_positive_points 119 120 if n_positive_remaining > 0: 121 object_coordinates = torch.where(object_mask) 122 n_coordinates = len(object_coordinates[0]) 123 124 # randomly sampling n_positive_remaining_points from these coordinates 125 indices = np.random.choice( 126 n_coordinates, size=n_positive_remaining, 127 # Allow replacing if we can't sample enough coordinates otherwise 128 replace=True if n_positive_remaining > n_coordinates else False, 129 ) 130 coord_list.extend([ 131 [object_coordinates[0][idx], object_coordinates[1][idx]] for idx in indices 132 ]) 133 134 label_list.extend([1] * self.n_positive_points) 135 assert len(coord_list) == len(label_list) == self.n_positive_points 136 return coord_list, label_list 137 138 def _sample_negative_points(self, object_mask, bbox_coordinates, coord_list, label_list): 139 if self.n_negative_points == 0: 140 return coord_list, label_list 141 142 # getting the negative points 143 # for this we do the opposite and we set the mask to the bounding box - the object mask 144 # we need to dilate the object mask before doing this: we use kornia.morphology.dilation for this 145 dilated_object = object_mask[None, None] 146 for _ in range(self.dilation_strength): 147 dilated_object = morphology.dilation(dilated_object, torch.ones(3, 3), engine="convolution") 148 dilated_object = dilated_object.squeeze() 149 150 background_mask = torch.zeros(object_mask.shape, device=object_mask.device) 151 _ds = self.dilation_strength 152 background_mask[ 153 max(bbox_coordinates[0] - _ds, 0): min(bbox_coordinates[2] + _ds, object_mask.shape[-2]), 154 max(bbox_coordinates[1] - _ds, 0): min(bbox_coordinates[3] + _ds, object_mask.shape[-1]) 155 ] = 1 156 background_mask = torch.abs(background_mask - dilated_object) 157 158 # the valid background coordinates 159 background_coordinates = torch.where(background_mask) 160 n_coordinates = len(background_coordinates[0]) 161 162 # randomly sample the negative points from these coordinates 163 indices = np.random.choice( 164 n_coordinates, replace=False, 165 size=min(self.n_negative_points, n_coordinates) # handles the cases with insufficient bg pixels 166 ) 167 coord_list.extend([ 168 [background_coordinates[0][idx], background_coordinates[1][idx]] for idx in indices 169 ]) 170 label_list.extend([0] * len(indices)) 171 172 return coord_list, label_list 173 174 def _ensure_num_points(self, object_mask, coord_list, label_list): 175 num_points = self.n_positive_points + self.n_negative_points 176 177 # fill up to the necessary number of points if we did not sample enough of them 178 if len(coord_list) != num_points: 179 # to stay consistent, we add random points in the background of an object 180 # if there's no neg region around the object - usually happens with small rois 181 needed_points = num_points - len(coord_list) 182 more_neg_points = torch.where(object_mask == 0) 183 indices = np.random.choice(len(more_neg_points[0]), size=needed_points, replace=False) 184 185 coord_list.extend([ 186 (more_neg_points[0][idx], more_neg_points[1][idx]) for idx in indices 187 ]) 188 label_list.extend([0] * needed_points) 189 190 assert len(coord_list) == len(label_list) == num_points 191 return coord_list, label_list 192 193 # Can we batch this properly? 194 def _sample_points(self, segmentation, bbox_coordinates, center_coordinates): 195 all_coords, all_labels = [], [] 196 197 center_coordinates = [None] * len(segmentation) if center_coordinates is None else center_coordinates 198 for object_mask, bbox_coords, center_coords in zip(segmentation, bbox_coordinates, center_coordinates): 199 coord_list, label_list = [], [] 200 coord_list, label_list = self._sample_positive_points(object_mask[0], center_coords, coord_list, label_list) 201 coord_list, label_list = self._sample_negative_points(object_mask[0], bbox_coords, coord_list, label_list) 202 coord_list, label_list = self._ensure_num_points(object_mask[0], coord_list, label_list) 203 204 all_coords.append(coord_list) 205 all_labels.append(label_list) 206 207 return all_coords, all_labels 208 209 def __call__( 210 self, 211 segmentation: torch.Tensor, 212 bbox_coordinates: List[Tuple], 213 center_coordinates: Optional[List[np.ndarray]] = None, 214 **kwargs, 215 ) -> Tuple[ 216 Optional[torch.Tensor], 217 Optional[torch.Tensor], 218 Optional[torch.Tensor], 219 None 220 ]: 221 """Generate the prompts for one object in the segmentation. 222 223 Args: 224 The groundtruth segmentation. Expects a float tensor of shape NUM_OBJECTS x 1 x H x W. 225 bbox_coordinates: The precomputed bounding boxes of particular object in the segmentation. 226 center_coordinates: The precomputed center coordinates of particular object in the segmentation. 227 If passed, these coordinates will be used as the first positive point prompt. 228 If not passed a random point from within the object mask will be used. 229 230 Returns: 231 Coordinates of point prompts. Returns None, if get_point_prompts is false. 232 Point prompt labels. Returns None, if get_point_prompts is false. 233 Bounding box prompts. Returns None, if get_box_prompts is false. 234 """ 235 if self.get_point_prompts: 236 coord_list, label_list = self._sample_points(segmentation, bbox_coordinates, center_coordinates) 237 # change the axis convention of the point coordinates to match the expected coordinate order of SAM 238 coord_list = np.array(coord_list)[:, :, ::-1].copy() 239 coord_list = torch.from_numpy(coord_list) 240 label_list = torch.tensor(label_list) 241 else: 242 coord_list, label_list = None, None 243 244 if self.get_box_prompts: 245 # change the axis convention of the box coordinates to match the expected coordinate order of SAM 246 bbox_list = np.array(bbox_coordinates)[:, [1, 0, 3, 2]] 247 bbox_list = torch.from_numpy(bbox_list) 248 else: 249 bbox_list = None 250 251 return coord_list, label_list, bbox_list, None
Generate point and/or box prompts from an instance segmentation.
You can use this class to derive prompts from an instance segmentation, either for
evaluation purposes or for training Segment Anything on custom data.
In order to use this generator you need to precompute the bounding boxes and center
coordiantes of the instance segmentation, using e.g. util.get_centers_and_bounding_boxes.
Here's an example for how to use this class:
# Initialize generator for 1 positive and 4 negative point prompts.
prompt_generator = PointAndBoxPromptGenerator(1, 4, dilation_strength=8)
# Precompute the bounding boxes for the given segmentation
bounding_boxes, _ = util.get_centers_and_bounding_boxes(segmentation)
# generate point prompts for the objects with ids 1, 2 and 3
seg_ids = (1, 2, 3)
object_mask = np.stack([segmentation == seg_id for seg_id in seg_ids])[:, None]
this_bounding_boxes = [bounding_boxes[seg_id] for seg_id in seg_ids]
point_coords, point_labels, _, _ = prompt_generator(object_mask, this_bounding_boxes)
Arguments:
- n_positive_points: The number of positive point prompts to generate per mask.
- n_negative_points: The number of negative point prompts to generate per mask.
- dilation_strength: The factor by which the mask is dilated before generating prompts.
- get_point_prompts: Whether to generate point prompts. By default, set to 'True'.
- get_box_prompts: Whether to generate box prompts. By default, set to 'False'.
90 def __init__( 91 self, 92 n_positive_points: int, 93 n_negative_points: int, 94 dilation_strength: int, 95 get_point_prompts: bool = True, 96 get_box_prompts: bool = False 97 ) -> None: 98 self.n_positive_points = n_positive_points 99 self.n_negative_points = n_negative_points 100 self.dilation_strength = dilation_strength 101 self.get_box_prompts = get_box_prompts 102 self.get_point_prompts = get_point_prompts 103 104 if self.get_point_prompts is False and self.get_box_prompts is False: 105 raise ValueError("You need to request box prompts, point prompts or both.")
254class IterativePromptGenerator(PromptGeneratorBase): 255 """Generate point prompts from an instance segmentation iteratively. 256 """ 257 def _get_positive_points(self, pos_region, overlap_region, is_3d): 258 positive_locations = [torch.where(pos_reg) for pos_reg in pos_region] 259 # we may have objects without a positive region (= missing true foreground) 260 # in this case we just sample a positive point where the model was already correct 261 positive_locations = [ 262 torch.where(ovlp_reg) if len(pos_loc[0]) == 0 else pos_loc 263 for pos_loc, ovlp_reg in zip(positive_locations, overlap_region) 264 ] 265 # we sample one positive location for each object in the batch 266 sampled_indices = [np.random.choice(len(pos_loc[0])) for pos_loc in positive_locations] 267 # get the corresponding coordinates (NOTE: we flip the axis order here due to the expected order of SAM) 268 if is_3d: 269 pos_coordinates = [ 270 [pos_loc[-1][idx], pos_loc[-2][idx], pos_loc[-3][idx]] 271 for pos_loc, idx in zip(positive_locations, sampled_indices) 272 ] 273 else: 274 pos_coordinates = [ 275 [pos_loc[-1][idx], pos_loc[-2][idx]] for pos_loc, idx in zip(positive_locations, sampled_indices) 276 ] 277 278 # make sure that we still have the correct batch size 279 assert len(pos_coordinates) == pos_region.shape[0] 280 pos_labels = [1] * len(pos_coordinates) 281 282 return pos_coordinates, pos_labels 283 284 def _get_negative_locations_in_obj_bbox(self, true_object, custom_df=3): 285 true_loc = torch.where(true_object) 286 bbox = torch.stack( 287 [torch.min(true_loc[1]), torch.min(true_loc[2]), torch.max(true_loc[1]) + 1, torch.max(true_loc[2]) + 1] 288 ) 289 290 # custom dilation factor to perform dilation by expanding the pixels of bbox 291 bbox_mask = torch.zeros_like(true_object).squeeze(0) 292 bbox_mask[ 293 max(bbox[0] - custom_df, 0): min(bbox[2] + custom_df, true_object.shape[-2]), 294 max(bbox[1] - custom_df, 0): min(bbox[3] + custom_df, true_object.shape[-1]) 295 ] = 1 296 bbox_mask = bbox_mask[None].to(true_object.device) 297 background_mask = torch.abs(bbox_mask - true_object) 298 return torch.where(background_mask) 299 300 def _get_negative_points(self, neg_region, true_object, is_3d): 301 # we have a valid negative region (i.e. a valid region where the model could not generate prediction) 302 negative_locations = [torch.where(neg_reg) for neg_reg in neg_region] 303 # we may have objects without a negative region (= no rectifications required) 304 # in this case we sample a negative point in outer periphery of the object inside the bounding box. 305 negative_locations = [ 306 self._get_negative_locations_in_obj_bbox(true_obj) if len(neg_loc[0]) == 0 else neg_loc 307 for neg_loc, true_obj in zip(negative_locations, true_object) 308 ] 309 # there is a chance that the object is small to not return a decent-sized bounding box 310 # hence we might not find points sometimes there as well. therefore, we sample points from true background. 311 negative_locations = [ 312 torch.where(true_obj == 0) if len(neg_loc[0]) == 0 else neg_loc 313 for neg_loc, true_obj in zip(negative_locations, true_object) 314 ] 315 # we sample one negative location for each object in the batch 316 sampled_indices = [np.random.choice(len(neg_loc[0])) for neg_loc in negative_locations] 317 # get the corresponding coordinates (NOTE: we flip the axis order here due to the expected order of SAM) 318 if is_3d: 319 neg_coordinates = [ 320 [neg_loc[-1][idx], neg_loc[-2][idx], neg_loc[-3][idx]] 321 for neg_loc, idx in zip(negative_locations, sampled_indices) 322 ] 323 else: 324 neg_coordinates = [ 325 [neg_loc[-1][idx], neg_loc[-2][idx]] for neg_loc, idx in zip(negative_locations, sampled_indices) 326 ] 327 328 # make sure that we still have the correct batch size 329 assert len(neg_coordinates) == neg_region.shape[0] 330 neg_labels = [0] * len(neg_coordinates) 331 332 return neg_coordinates, neg_labels 333 334 def __call__( 335 self, 336 segmentation: torch.Tensor, 337 prediction: torch.Tensor, 338 **kwargs, 339 ) -> Tuple[torch.Tensor, torch.Tensor, None, None]: 340 """Generate the prompts for each object iteratively in the segmentation. 341 342 Args: 343 segmentation: The groundtruth segmentation. 344 Expects a float tensor of shape (NUM_OBJECTS x 1 x H x W) or (NUM_OBJECTS x 1 x Z x H x W). 345 prediction: The predicted objects. Epects a float tensor of the same shape as the segmentation. 346 347 Returns: 348 The updated point prompt coordinates. 349 The updated point prompt labels. 350 """ 351 device = prediction.device 352 assert segmentation.shape == prediction.shape, \ 353 "The segmentation and prediction tensors should have the same shape." 354 355 if segmentation.ndim == 5: # masks in 3d must be tensors of shape NUM_OBJECTS x 1 x Z x H x W 356 is_3d = True 357 elif segmentation.ndim == 4: # masks in 2d must be tensors of shape NUM_OBJECTS x 1 x H x W 358 is_3d = False 359 else: 360 raise ValueError("The segmentation and prediction tensors should have either '4' or '5' dimensions.") 361 362 true_object = segmentation.to(device) 363 expected_diff = (prediction - true_object) 364 neg_region = (expected_diff == 1).to(torch.float32) 365 pos_region = (expected_diff == -1) 366 overlap_region = torch.logical_and(prediction == 1, true_object == 1).to(torch.float32) 367 368 pos_coordinates, pos_labels = self._get_positive_points(pos_region, overlap_region, is_3d) 369 neg_coordinates, neg_labels = self._get_negative_points(neg_region, true_object, is_3d) 370 assert len(pos_coordinates) == len(pos_labels) == len(neg_coordinates) == len(neg_labels) 371 372 pos_coordinates = torch.tensor(pos_coordinates)[:, None] 373 neg_coordinates = torch.tensor(neg_coordinates)[:, None] 374 pos_labels, neg_labels = torch.tensor(pos_labels)[:, None], torch.tensor(neg_labels)[:, None] 375 376 net_coords = torch.cat([pos_coordinates, neg_coordinates], dim=1) 377 net_labels = torch.cat([pos_labels, neg_labels], dim=1) 378 379 return net_coords, net_labels, None, None
Generate point prompts from an instance segmentation iteratively.
392def get_error_centers( 393 true_mask: np.ndarray, predicted_mask: np.ndarray 394) -> Tuple[Optional[List[float]], Optional[List[float]]]: 395 """Get the correction clicks of the 'center' protocol for one object in 2d. 396 397 The positive click is the center of the largest missed region and the negative click the center of the 398 largest added region, like the 'center' click sampling of RITM and SAM2. The center is the point with the 399 largest distance to the region border. 400 401 Args: 402 true_mask: The ground-truth mask of the object. 403 predicted_mask: The predicted mask of the object. 404 405 Returns: 406 The positive click as (x, y), or None if nothing is missed. 407 The negative click as (x, y), or None if nothing is added. 408 """ 409 # Both error regions lie within the bounding box of the object and its prediction, so only this crop is 410 # searched. The crop keeps the raster order of the pixels, so the centers are the same. 411 union = true_mask | predicted_mask 412 if not union.any(): 413 return None, None 414 rows, cols = np.where(union.any(axis=1))[0], np.where(union.any(axis=0))[0] 415 crop = np.s_[rows[0]:rows[-1] + 1, cols[0]:cols[-1] + 1] 416 true_crop, predicted_crop = true_mask[crop], predicted_mask[crop] 417 pos = _error_center(true_crop & ~predicted_crop) 418 neg = _error_center(predicted_crop & ~true_crop) 419 pos = None if pos is None else [pos[0] + cols[0], pos[1] + rows[0]] 420 neg = None if neg is None else [neg[0] + cols[0], neg[1] + rows[0]] 421 return pos, neg
Get the correction clicks of the 'center' protocol for one object in 2d.
The positive click is the center of the largest missed region and the negative click the center of the largest added region, like the 'center' click sampling of RITM and SAM2. The center is the point with the largest distance to the region border.
Arguments:
- true_mask: The ground-truth mask of the object.
- predicted_mask: The predicted mask of the object.
Returns:
The positive click as (x, y), or None if nothing is missed. The negative click as (x, y), or None if nothing is added.
424class CenterIterativePromptGenerator(PromptGeneratorBase): 425 """Generate point prompts at the centers of the prediction errors iteratively, for 2d evaluation. 426 427 Each object gets the clicks of `get_error_centers`. A missing error type gets a padding point with the 428 label -1, which the model ignores. 429 """ 430 431 def __call__( 432 self, 433 segmentation: torch.Tensor, 434 prediction: torch.Tensor, 435 **kwargs, 436 ) -> Tuple[torch.Tensor, torch.Tensor, None, None]: 437 """Generate the prompts for each object iteratively in the segmentation. 438 439 Args: 440 segmentation: The groundtruth segmentation. Expects a float tensor of shape (NUM_OBJECTS x 1 x H x W). 441 prediction: The predicted objects. Expects a float tensor of the same shape as the segmentation. 442 443 Returns: 444 The point prompt coordinates, of shape (NUM_OBJECTS x 2 x 2). 445 The point prompt labels, of shape (NUM_OBJECTS x 2). 446 """ 447 assert segmentation.shape == prediction.shape, \ 448 "The segmentation and prediction tensors should have the same shape." 449 if segmentation.ndim != 4: 450 raise ValueError("The segmentation and prediction tensors should have '4' dimensions.") 451 452 true_objects = segmentation.bool().cpu().numpy()[:, 0] 453 predicted_objects = prediction.bool().cpu().numpy()[:, 0] 454 coordinates, labels = [], [] 455 for true_object, predicted_object in zip(true_objects, predicted_objects): 456 pos, neg = get_error_centers(true_object, predicted_object) 457 coordinates.append([pos or [0.0, 0.0], neg or [0.0, 0.0]]) 458 labels.append([1 if pos else -1, 0 if neg else -1]) 459 460 return torch.tensor(coordinates), torch.tensor(labels), None, None
Generate point prompts at the centers of the prediction errors iteratively, for 2d evaluation.
Each object gets the clicks of get_error_centers. A missing error type gets a padding point with the
label -1, which the model ignores.