Reference for ultralytics/models/sam/amg.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/sam/amg.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.sam.amg.is_box_near_crop_edge
is_box_near_crop_edge(
boxes: Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
) -> torch.Tensor
Determines if bounding boxes are near the edge of a cropped image region using a specified tolerance.
Source code in ultralytics/models/sam/amg.py
11 12 13 14 15 16 17 18 19 20 21 |
|
ultralytics.models.sam.amg.batch_iterator
batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]
Yield batches of data from input arguments with specified batch size for efficient processing.
This function takes a batch size and any number of iterables, then yields batches of elements from those iterables. All input iterables must have the same length.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
Size of each batch to yield. |
required |
*args
|
Any
|
Variable length input iterables to batch. All iterables must have the same length. |
()
|
Yields:
Type | Description |
---|---|
List[Any]
|
A list of batched elements from each input iterable. |
Examples:
>>> data = [1, 2, 3, 4, 5]
>>> labels = ["a", "b", "c", "d", "e"]
>>> for batch in batch_iterator(2, data, labels):
... print(batch)
[[1, 2], ['a', 'b']]
[[3, 4], ['c', 'd']]
[[5], ['e']]
Source code in ultralytics/models/sam/amg.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
ultralytics.models.sam.amg.calculate_stability_score
calculate_stability_score(
masks: Tensor, mask_threshold: float, threshold_offset: float
) -> torch.Tensor
Computes the stability score for a batch of masks.
The stability score is the IoU between binary masks obtained by thresholding the predicted mask logits at high and low values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks
|
Tensor
|
Batch of predicted mask logits. |
required |
mask_threshold
|
float
|
Threshold value for creating binary masks. |
required |
threshold_offset
|
float
|
Offset applied to the threshold for creating high and low binary masks. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Stability scores for each mask in the batch. |
Notes
- One mask is always contained inside the other.
- Memory is saved by preventing unnecessary cast to torch.int64.
Examples:
>>> masks = torch.rand(10, 256, 256) # Batch of 10 masks
>>> mask_threshold = 0.5
>>> threshold_offset = 0.1
>>> stability_scores = calculate_stability_score(masks, mask_threshold, threshold_offset)
Source code in ultralytics/models/sam/amg.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
ultralytics.models.sam.amg.build_point_grid
build_point_grid(n_per_side: int) -> np.ndarray
Generate a 2D grid of evenly spaced points in the range [0,1]x[0,1] for image segmentation tasks.
Source code in ultralytics/models/sam/amg.py
83 84 85 86 87 88 89 |
|
ultralytics.models.sam.amg.build_all_layer_point_grids
build_all_layer_point_grids(
n_per_side: int, n_layers: int, scale_per_layer: int
) -> List[np.ndarray]
Generates point grids for multiple crop layers with varying scales and densities.
Source code in ultralytics/models/sam/amg.py
92 93 94 |
|
ultralytics.models.sam.amg.generate_crop_boxes
generate_crop_boxes(
im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
) -> Tuple[List[List[int]], List[int]]
Generates crop boxes of varying sizes for multiscale image processing, with layered overlapping regions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im_size
|
Tuple[int, ...]
|
Height and width of the input image. |
required |
n_layers
|
int
|
Number of layers to generate crop boxes for. |
required |
overlap_ratio
|
float
|
Ratio of overlap between adjacent crop boxes. |
required |
Returns:
Type | Description |
---|---|
List[List[int]]
|
List of crop boxes in [x0, y0, x1, y1] format. |
List[int]
|
List of layer indices corresponding to each crop box. |
Examples:
>>> im_size = (800, 1200) # Height, width
>>> n_layers = 3
>>> overlap_ratio = 0.25
>>> crop_boxes, layer_idxs = generate_crop_boxes(im_size, n_layers, overlap_ratio)
Source code in ultralytics/models/sam/amg.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
|
ultralytics.models.sam.amg.uncrop_boxes_xyxy
uncrop_boxes_xyxy(boxes: Tensor, crop_box: List[int]) -> torch.Tensor
Uncrop bounding boxes by adding the crop box offset to their coordinates.
Source code in ultralytics/models/sam/amg.py
149 150 151 152 153 154 155 156 |
|
ultralytics.models.sam.amg.uncrop_points
uncrop_points(points: Tensor, crop_box: List[int]) -> torch.Tensor
Uncrop points by adding the crop box offset to their coordinates.
Source code in ultralytics/models/sam/amg.py
159 160 161 162 163 164 165 166 |
|
ultralytics.models.sam.amg.uncrop_masks
uncrop_masks(
masks: Tensor, crop_box: List[int], orig_h: int, orig_w: int
) -> torch.Tensor
Uncrop masks by padding them to the original image size, handling coordinate transformations.
Source code in ultralytics/models/sam/amg.py
169 170 171 172 173 174 175 176 177 |
|
ultralytics.models.sam.amg.remove_small_regions
remove_small_regions(
mask: ndarray, area_thresh: float, mode: str
) -> Tuple[np.ndarray, bool]
Removes small disconnected regions or holes in a mask based on area threshold and mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mask
|
ndarray
|
Binary mask to process. |
required |
area_thresh
|
float
|
Area threshold below which regions will be removed. |
required |
mode
|
str
|
Processing mode, either 'holes' to fill small holes or 'islands' to remove small disconnected regions. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
Processed binary mask with small regions removed. |
bool
|
Whether any regions were modified. |
Examples:
>>> mask = np.zeros((100, 100), dtype=np.bool_)
>>> mask[40:60, 40:60] = True # Create a square
>>> mask[45:55, 45:55] = False # Create a hole
>>> processed_mask, modified = remove_small_regions(mask, 50, "holes")
Source code in ultralytics/models/sam/amg.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
|
ultralytics.models.sam.amg.batched_mask_to_box
batched_mask_to_box(masks: Tensor) -> torch.Tensor
Calculates bounding boxes in XYXY format around binary masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks
|
Tensor
|
Binary masks with shape (B, H, W) or (B, C, H, W). |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Bounding boxes in XYXY format with shape (B, 4) or (B, C, 4). |
Notes
- Handles empty masks by returning zero boxes.
- Preserves input tensor dimensions in the output.
Source code in ultralytics/models/sam/amg.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
|