Reference for ultralytics/models/sam/predict.py
Note
Full source code for this file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/sam/predict.py. Help us fix any issues you see by submitting a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.sam.predict.Predictor
Bases: BasePredictor
Source code in ultralytics/models/sam/predict.py
19 20 21 22 23 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 51 52 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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 215 216 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
|
generate(im, crop_n_layers=0, crop_overlap_ratio=512 / 1500, crop_downscale_factor=1, point_grids=None, points_stride=32, points_batch_size=64, conf_thres=0.88, stability_score_thresh=0.95, stability_score_offset=0.95, crop_nms_thresh=0.7)
Segment the whole image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
Tensor
|
The preprocessed image, (N, C, H, W). |
required |
crop_n_layers |
int
|
If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. |
0
|
crop_overlap_ratio |
float
|
Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. |
512 / 1500
|
crop_downscale_factor |
int
|
The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. |
1
|
point_grids |
(list(ndarray), None)
|
A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. |
None
|
points_stride |
(int, None)
|
The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. |
32
|
points_batch_size |
int
|
Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. |
64
|
conf_thres |
float
|
A filtering threshold in [0,1], using the model's predicted mask quality. |
0.88
|
stability_score_thresh |
float
|
A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. |
0.95
|
stability_score_offset |
float
|
The amount to shift the cutoff when calculated the stability score. |
0.95
|
crop_nms_thresh |
float
|
The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. |
0.7
|
Source code in ultralytics/models/sam/predict.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 215 216 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
|
inference(im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs)
Predict masks for the given input prompts, using the currently set image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
Tensor
|
The preprocessed image, (N, C, H, W). |
required |
bboxes |
(ndarray | List, None)
|
(N, 4), in XYXY format. |
None
|
points |
(ndarray | List, None)
|
(N, 2), Each point is in (X,Y) in pixels. |
None
|
labels |
(ndarray | List, None)
|
(N, ), labels for the point prompts. 1 indicates a foreground point and 0 indicates a background point. |
None
|
masks |
(ndarray, None)
|
A low resolution mask input to the model, typically coming from a previous prediction iteration. Has form (N, H, W), where for SAM, H=W=256. |
None
|
multimask_output |
bool
|
If true, the model will return three masks. For ambiguous input prompts (such as a single click), this will often produce better masks than a single prediction. If only a single mask is needed, the model's predicted quality score can be used to select the best mask. For non-ambiguous prompts, such as multiple input prompts, multimask_output=False can give better results. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
The output masks in CxHxW format, where C is the number of masks, and (H, W) is the original image size. |
ndarray
|
An array of length C containing the model's predictions for the quality of each mask. |
ndarray
|
An array of shape CxHxW, where C is the number of masks and H=W=256. These low resolution logits can be passed to a subsequent iteration as mask input. |
Source code in ultralytics/models/sam/predict.py
postprocess(preds, img, orig_imgs)
Post-processes inference output predictions to create detection masks for objects.
Source code in ultralytics/models/sam/predict.py
pre_transform(im)
Pre-transform input image before inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
List(np.ndarray
|
(N, 3, h, w) for tensor, [(h, w, 3) x N] for list. |
required |
Returns:
Type | Description |
---|---|
list
|
A list of transformed images. |
Source code in ultralytics/models/sam/predict.py
preprocess(im)
Prepares input image before inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
torch.Tensor | List(np.ndarray
|
BCHW for tensor, [(HWC) x B] for list. |
required |
Source code in ultralytics/models/sam/predict.py
prompt_inference(im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False)
Predict masks for the given input prompts, using the currently set image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
Tensor
|
The preprocessed image, (N, C, H, W). |
required |
bboxes |
(ndarray | List, None)
|
(N, 4), in XYXY format. |
None
|
points |
(ndarray | List, None)
|
(N, 2), Each point is in (X,Y) in pixels. |
None
|
labels |
(ndarray | List, None)
|
(N, ), labels for the point prompts. 1 indicates a foreground point and 0 indicates a background point. |
None
|
masks |
(ndarray, None)
|
A low resolution mask input to the model, typically coming from a previous prediction iteration. Has form (N, H, W), where for SAM, H=W=256. |
None
|
multimask_output |
bool
|
If true, the model will return three masks. For ambiguous input prompts (such as a single click), this will often produce better masks than a single prediction. If only a single mask is needed, the model's predicted quality score can be used to select the best mask. For non-ambiguous prompts, such as multiple input prompts, multimask_output=False can give better results. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
The output masks in CxHxW format, where C is the number of masks, and (H, W) is the original image size. |
ndarray
|
An array of length C containing the model's predictions for the quality of each mask. |
ndarray
|
An array of shape CxHxW, where C is the number of masks and H=W=256. These low resolution logits can be passed to a subsequent iteration as mask input. |
Source code in ultralytics/models/sam/predict.py
remove_small_regions(masks, min_area=0, nms_thresh=0.7)
staticmethod
Removes small disconnected regions and holes in masks, then reruns box NMS to remove any new duplicates. Requires open-cv as a dependency.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks |
Tensor
|
Masks, (N, H, W). |
required |
min_area |
int
|
Minimum area threshold. |
0
|
nms_thresh |
float
|
NMS threshold. |
0.7
|
Returns: new_masks (torch.Tensor): New Masks, (N, H, W). keep (List[int]): The indices of the new masks, which can be used to filter the corresponding boxes.
Source code in ultralytics/models/sam/predict.py
set_image(image)
Set image in advance. Args:
image (str | np.ndarray): image file path or np.ndarray image by cv2.
Source code in ultralytics/models/sam/predict.py
set_prompts(prompts)
setup_model(model, verbose=True)
Set up YOLO model with specified thresholds and device.