Reference for ultralytics/models/sam/predict.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/sam/predict.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.sam.predict.Predictor
Bases: BasePredictor
Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image segmentation tasks. It supports various input prompts like points, bounding boxes, and masks for fine-grained control over segmentation results.
Attributes:
Name | Type | Description |
---|---|---|
args |
SimpleNamespace
|
Configuration arguments for the predictor. |
model |
Module
|
The loaded SAM model. |
device |
device
|
The device (CPU or GPU) on which the model is loaded. |
im |
Tensor
|
The preprocessed input image. |
features |
Tensor
|
Extracted image features. |
prompts |
Dict
|
Dictionary to store various types of prompts (e.g., bboxes, points, masks). |
segment_all |
bool
|
Flag to indicate if full image segmentation should be performed. |
mean |
Tensor
|
Mean values for image normalization. |
std |
Tensor
|
Standard deviation values for image normalization. |
Methods:
Name | Description |
---|---|
preprocess |
Prepares input images for model inference. |
pre_transform |
Performs initial transformations on the input image. |
inference |
Performs segmentation inference based on input prompts. |
prompt_inference |
Internal function for prompt-based segmentation inference. |
generate |
Generates segmentation masks for an entire image. |
setup_model |
Initializes the SAM model for inference. |
get_model |
Builds and returns a SAM model. |
postprocess |
Post-processes model outputs to generate final results. |
setup_source |
Sets up the data source for inference. |
set_image |
Sets and preprocesses a single image for inference. |
get_im_features |
Extracts image features using the SAM image encoder. |
set_prompts |
Sets prompts for subsequent inference. |
reset_image |
Resets the current image and its features. |
remove_small_regions |
Removes small disconnected regions and holes from masks. |
Examples:
>>> predictor = Predictor()
>>> predictor.setup_model(model_path="sam_model.pt")
>>> predictor.set_image("image.jpg")
>>> bboxes = [[100, 100, 200, 200]]
>>> results = predictor(bboxes=bboxes)
Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True for optimal results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
Dict
|
Configuration dictionary containing default settings. |
DEFAULT_CFG
|
overrides
|
Dict | None
|
Dictionary of values to override default configuration. |
None
|
_callbacks
|
Dict | None
|
Dictionary of callback functions to customize behavior. |
None
|
Examples:
>>> predictor_example = Predictor(cfg=DEFAULT_CFG)
>>> predictor_example_with_imgsz = Predictor(overrides={"imgsz": 640})
>>> predictor_example_with_callback = Predictor(_callbacks={"on_predict_start": custom_callback})
Source code in ultralytics/models/sam/predict.py
_prepare_prompts
Prepares and transforms the input prompts for processing based on the destination shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dst_shape
|
tuple
|
The target shape (height, width) for the prompts. |
required |
bboxes
|
ndarray | List | None
|
Bounding boxes in XYXY format with shape (N, 4). |
None
|
points
|
ndarray | List | None
|
Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels. |
None
|
labels
|
ndarray | List | None
|
Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background. |
None
|
masks
|
(List | ndarray, Optional)
|
Masks for the objects, where each mask is a 2D array. |
None
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the number of points don't match the number of labels, in case labels were passed. |
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing transformed bounding boxes, points, labels, and masks. |
Source code in ultralytics/models/sam/predict.py
generate
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,
)
Perform image segmentation using the Segment Anything Model (SAM).
This method segments an entire image into constituent parts by leveraging SAM's advanced architecture and real-time performance capabilities. It can optionally work on image crops for finer segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
Input tensor representing the preprocessed image with shape (N, C, H, W). |
required |
crop_n_layers
|
int
|
Number of layers for additional mask predictions on image crops. |
0
|
crop_overlap_ratio
|
float
|
Overlap between crops, scaled down in subsequent layers. |
512 / 1500
|
crop_downscale_factor
|
int
|
Scaling factor for sampled points-per-side in each layer. |
1
|
point_grids
|
List[ndarray] | None
|
Custom grids for point sampling normalized to [0,1]. |
None
|
points_stride
|
int
|
Number of points to sample along each side of the image. |
32
|
points_batch_size
|
int
|
Batch size for the number of points processed simultaneously. |
64
|
conf_thres
|
float
|
Confidence threshold [0,1] for filtering based on mask quality prediction. |
0.88
|
stability_score_thresh
|
float
|
Stability threshold [0,1] for mask filtering based on stability. |
0.95
|
stability_score_offset
|
float
|
Offset value for calculating stability score. |
0.95
|
crop_nms_thresh
|
float
|
IoU cutoff for NMS to remove duplicate masks between crops. |
0.7
|
Returns:
Name | Type | Description |
---|---|---|
pred_masks |
Tensor
|
Segmented masks with shape (N, H, W). |
pred_scores |
Tensor
|
Confidence scores for each mask with shape (N,). |
pred_bboxes |
Tensor
|
Bounding boxes for each mask with shape (N, 4). |
Examples:
>>> predictor = Predictor()
>>> im = torch.rand(1, 3, 1024, 1024) # Example input image
>>> masks, scores, boxes = predictor.generate(im)
Source code in ultralytics/models/sam/predict.py
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 |
|
get_im_features
Extracts image features using the SAM model's image encoder for subsequent mask prediction.
Source code in ultralytics/models/sam/predict.py
get_model
inference
inference(
im,
bboxes=None,
points=None,
labels=None,
masks=None,
multimask_output=False,
*args,
**kwargs
)
Perform image segmentation inference based on the given input cues, using the currently loaded image.
This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and mask decoder for real-time and promptable segmentation tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
The preprocessed input image in tensor format, with shape (N, C, H, W). |
required |
bboxes
|
ndarray | List | None
|
Bounding boxes with shape (N, 4), in XYXY format. |
None
|
points
|
ndarray | List | None
|
Points indicating object locations with shape (N, 2), in pixels. |
None
|
labels
|
ndarray | List | None
|
Labels for point prompts, shape (N,). 1 = foreground, 0 = background. |
None
|
masks
|
ndarray | None
|
Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256. |
None
|
multimask_output
|
bool
|
Flag to return multiple masks. Helpful for ambiguous prompts. |
False
|
*args
|
Any
|
Additional positional arguments. |
()
|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Returns:
Type | Description |
---|---|
ndarray
|
The output masks in shape (C, H, W), where C is the number of generated masks. |
ndarray
|
An array of length C containing quality scores predicted by the model for each mask. |
ndarray
|
Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256. |
Examples:
>>> predictor = Predictor()
>>> predictor.setup_model(model_path="sam_model.pt")
>>> predictor.set_image("image.jpg")
>>> results = predictor(bboxes=[[0, 0, 100, 100]])
Source code in ultralytics/models/sam/predict.py
postprocess
Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.
This method scales masks and boxes to the original image size and applies a threshold to the mask predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
Tuple[Tensor]
|
The output from SAM model inference, containing: - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W). - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1). - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True. |
required |
img
|
Tensor
|
The processed input image tensor with shape (C, H, W). |
required |
orig_imgs
|
List[ndarray] | Tensor
|
The original, unprocessed images. |
required |
Returns:
Name | Type | Description |
---|---|---|
results |
List[Results]
|
List of Results objects containing detection masks, bounding boxes, and other metadata for each processed image. |
Examples:
>>> predictor = Predictor()
>>> preds = predictor.inference(img)
>>> results = predictor.postprocess(preds, img, orig_imgs)
Source code in ultralytics/models/sam/predict.py
pre_transform
Perform initial transformations on the input image for preprocessing.
This method applies transformations such as resizing to prepare the image for further preprocessing. Currently, batched inference is not supported; hence the list length should be 1.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
List[ndarray]
|
List containing a single image in HWC numpy array format. |
required |
Returns:
Type | Description |
---|---|
List[ndarray]
|
List containing the transformed image. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the input list contains more than one image. |
Examples:
>>> predictor = Predictor()
>>> image = np.random.rand(480, 640, 3) # Single HWC image
>>> transformed = predictor.pre_transform([image])
>>> print(len(transformed))
1
Source code in ultralytics/models/sam/predict.py
preprocess
Preprocess the input image for model inference.
This method prepares the input image by applying transformations and normalization. It supports both torch.Tensor and list of np.ndarray as input formats.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor | List[ndarray]
|
Input image(s) in BCHW tensor format or list of HWC numpy arrays. |
required |
Returns:
Name | Type | Description |
---|---|---|
im |
Tensor
|
The preprocessed image tensor, normalized and converted to the appropriate dtype. |
Examples:
>>> predictor = Predictor()
>>> image = torch.rand(1, 3, 640, 640)
>>> preprocessed_image = predictor.preprocess(image)
Source code in ultralytics/models/sam/predict.py
prompt_inference
Performs image segmentation inference based on input cues using SAM's specialized architecture.
This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation. It processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
Preprocessed input image tensor with shape (N, C, H, W). |
required |
bboxes
|
ndarray | List | None
|
Bounding boxes in XYXY format with shape (N, 4). |
None
|
points
|
ndarray | List | None
|
Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels. |
None
|
labels
|
ndarray | List | None
|
Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background. |
None
|
masks
|
ndarray | None
|
Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256. |
None
|
multimask_output
|
bool
|
Flag to return multiple masks for ambiguous prompts. |
False
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the number of points don't match the number of labels, in case labels were passed. |
Returns:
Type | Description |
---|---|
ndarray
|
Output masks with shape (C, H, W), where C is the number of generated masks. |
ndarray
|
Quality scores predicted by the model for each mask, with length C. |
Examples:
>>> predictor = Predictor()
>>> im = torch.rand(1, 3, 1024, 1024)
>>> bboxes = [[100, 100, 200, 200]]
>>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
Source code in ultralytics/models/sam/predict.py
remove_small_regions
staticmethod
Remove small disconnected regions and holes from segmentation masks.
This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM). It removes small disconnected regions and holes from the input masks, and then performs Non-Maximum Suppression (NMS) to eliminate any newly created duplicate boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks
|
Tensor
|
Segmentation masks to be processed, with shape (N, H, W) where N is the number of masks, H is height, and W is width. |
required |
min_area
|
int
|
Minimum area threshold for removing disconnected regions and holes. Regions smaller than this will be removed. |
0
|
nms_thresh
|
float
|
IoU threshold for the NMS algorithm to remove duplicate boxes. |
0.7
|
Returns:
Name | Type | Description |
---|---|---|
new_masks |
Tensor
|
Processed masks with small regions removed, shape (N, H, W). |
keep |
List[int]
|
Indices of remaining masks after NMS, for filtering corresponding boxes. |
Examples:
>>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks
>>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
>>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
>>> print(f"Indices of kept masks: {keep}")
Source code in ultralytics/models/sam/predict.py
reset_image
set_image
Preprocesses and sets a single image for inference.
This method prepares the model for inference on a single image by setting up the model if not already initialized, configuring the data source, and preprocessing the image for feature extraction. It ensures that only one image is set at a time and extracts image features for subsequent use.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
str | ndarray
|
Path to the image file as a string, or a numpy array representing an image read by cv2. |
required |
Raises:
Type | Description |
---|---|
AssertionError
|
If more than one image is attempted to be set. |
Examples:
>>> predictor = Predictor()
>>> predictor.set_image("path/to/image.jpg")
>>> predictor.set_image(cv2.imread("path/to/image.jpg"))
Notes
- This method should be called before performing inference on a new image.
- The extracted features are stored in the
self.features
attribute for later use.
Source code in ultralytics/models/sam/predict.py
set_prompts
setup_model
Initializes the Segment Anything Model (SAM) for inference.
This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary parameters for image normalization and other Ultralytics compatibility settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module | None
|
A pretrained SAM model. If None, a new model is built based on config. |
None
|
verbose
|
bool
|
If True, prints selected device information. |
True
|
Examples:
Source code in ultralytics/models/sam/predict.py
setup_source
Sets up the data source for inference.
This method configures the data source from which images will be fetched for inference. It supports various input types such as image files, directories, video files, and other compatible data sources.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str | Path | None
|
The path or identifier for the image data source. Can be a file path, directory path, URL, or other supported source types. |
required |
Examples:
>>> predictor = Predictor()
>>> predictor.setup_source("path/to/images")
>>> predictor.setup_source("video.mp4")
>>> predictor.setup_source(None) # Uses default source if available
Notes
- If source is None, the method may use a default source if configured.
- The method adapts to different source types and prepares them for subsequent inference steps.
- Supported source types may include local files, directories, URLs, and video streams.
Source code in ultralytics/models/sam/predict.py
ultralytics.models.sam.predict.SAM2Predictor
Bases: Predictor
SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
This class extends the base Predictor class to implement SAM2-specific functionality for image segmentation tasks. It provides methods for model initialization, feature extraction, and prompt-based inference.
Attributes:
Name | Type | Description |
---|---|---|
_bb_feat_sizes |
List[Tuple[int, int]]
|
Feature sizes for different backbone levels. |
model |
Module
|
The loaded SAM2 model. |
device |
device
|
The device (CPU or GPU) on which the model is loaded. |
features |
Dict[str, Tensor]
|
Cached image features for efficient inference. |
segment_all |
bool
|
Flag to indicate if all segments should be predicted. |
prompts |
Dict
|
Dictionary to store various types of prompts for inference. |
Methods:
Name | Description |
---|---|
get_model |
Retrieves and initializes the SAM2 model. |
prompt_inference |
Performs image segmentation inference based on various prompts. |
set_image |
Preprocesses and sets a single image for inference. |
get_im_features |
Extracts and processes image features using SAM2's image encoder. |
Examples:
>>> predictor = SAM2Predictor(cfg)
>>> predictor.set_image("path/to/image.jpg")
>>> bboxes = [[100, 100, 200, 200]]
>>> result = predictor(bboxes=bboxes)[0]
>>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
Source code in ultralytics/models/sam/predict.py
_prepare_prompts
Prepares and transforms the input prompts for processing based on the destination shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dst_shape
|
tuple
|
The target shape (height, width) for the prompts. |
required |
bboxes
|
ndarray | List | None
|
Bounding boxes in XYXY format with shape (N, 4). |
None
|
points
|
ndarray | List | None
|
Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels. |
None
|
labels
|
ndarray | List | None
|
Point prompt labels with shape (N,) or (N, num_points). 1 for foreground, 0 for background. |
None
|
masks
|
(List | ndarray, Optional)
|
Masks for the objects, where each mask is a 2D array. |
None
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the number of points don't match the number of labels, in case labels were passed. |
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing transformed points, labels, and masks. |
Source code in ultralytics/models/sam/predict.py
get_im_features
Extracts image features from the SAM image encoder for subsequent processing.
Source code in ultralytics/models/sam/predict.py
get_model
Retrieves and initializes the Segment Anything Model 2 (SAM2) for image segmentation tasks.
prompt_inference
prompt_inference(
im,
bboxes=None,
points=None,
labels=None,
masks=None,
multimask_output=False,
img_idx=-1,
)
Performs image segmentation inference based on various prompts using SAM2 architecture.
This method leverages the Segment Anything Model 2 (SAM2) to generate segmentation masks for input images based on provided prompts such as bounding boxes, points, or existing masks. It supports both single and multi-object prediction scenarios.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
Preprocessed input image tensor with shape (N, C, H, W). |
required |
bboxes
|
ndarray | List[List[float]] | None
|
Bounding boxes in XYXY format with shape (N, 4). |
None
|
points
|
ndarray | List[List[float]] | None
|
Object location points with shape (N, 2), in pixels. |
None
|
labels
|
ndarray | List[int] | None
|
Point prompt labels with shape (N,). 1 = foreground, 0 = background. |
None
|
masks
|
ndarray | None
|
Low-resolution masks from previous predictions with shape (N, H, W). |
None
|
multimask_output
|
bool
|
Flag to return multiple masks for ambiguous prompts. |
False
|
img_idx
|
int
|
Index of the image in the batch to process. |
-1
|
Returns:
Type | Description |
---|---|
ndarray
|
Output masks with shape (C, H, W), where C is the number of generated masks. |
ndarray
|
Quality scores for each mask, with length C. |
Examples:
>>> predictor = SAM2Predictor(cfg)
>>> image = torch.rand(1, 3, 640, 640)
>>> bboxes = [[100, 100, 200, 200]]
>>> result = predictor(image, bboxes=bboxes)[0]
>>> print(f"Generated {result.masks.shape[0]} masks with average score {result.boxes.conf.mean():.2f}")
Notes
- The method supports batched inference for multiple objects when points or bboxes are provided.
- Input prompts (bboxes, points) are automatically scaled to match the input image dimensions.
- When both bboxes and points are provided, they are merged into a single 'points' input for the model.
References
- SAM2 Paper: [Add link to SAM2 paper when available]
Source code in ultralytics/models/sam/predict.py
set_image
Preprocesses and sets a single image for inference using the SAM2 model.
This method initializes the model if not already done, configures the data source to the specified image, and preprocesses the image for feature extraction. It supports setting only one image at a time.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
str | ndarray
|
Path to the image file as a string, or a numpy array representing the image. |
required |
Raises:
Type | Description |
---|---|
AssertionError
|
If more than one image is attempted to be set. |
Examples:
>>> predictor = SAM2Predictor()
>>> predictor.set_image("path/to/image.jpg")
>>> predictor.set_image(np.array([...])) # Using a numpy array
Notes
- This method must be called before performing any inference on a new image.
- The method caches the extracted features for efficient subsequent inferences on the same image.
- Only one image can be set at a time. To process multiple images, call this method for each new image.
Source code in ultralytics/models/sam/predict.py
ultralytics.models.sam.predict.SAM2VideoPredictor
Bases: SAM2Predictor
SAM2VideoPredictor to handle user interactions with videos and manage inference states.
This class extends the functionality of SAM2Predictor to support video processing and maintains the state of inference operations. It includes configurations for managing non-overlapping masks, clearing memory for non-conditional inputs, and setting up callbacks for prediction events.
Attributes:
Name | Type | Description |
---|---|---|
inference_state |
Dict
|
A dictionary to store the current state of inference operations. |
non_overlap_masks |
bool
|
A flag indicating whether masks should be non-overlapping. |
clear_non_cond_mem_around_input |
bool
|
A flag to control clearing non-conditional memory around inputs. |
clear_non_cond_mem_for_multi_obj |
bool
|
A flag to control clearing non-conditional memory for multi-object scenarios. |
callbacks |
Dict
|
A dictionary of callbacks for various prediction lifecycle events. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
(Dict, Optional)
|
Configuration settings for the predictor. Defaults to DEFAULT_CFG. |
DEFAULT_CFG
|
overrides
|
(Dict, Optional)
|
Additional configuration overrides. Defaults to None. |
None
|
_callbacks
|
(List, Optional)
|
Custom callbacks to be added. Defaults to None. |
None
|
Note
The fill_hole_area
attribute is defined but not used in the current implementation.
This constructor initializes the SAM2VideoPredictor with a given configuration, applies any specified overrides, and sets up the inference state along with certain flags that control the behavior of the predictor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
Dict
|
Configuration dictionary containing default settings. |
DEFAULT_CFG
|
overrides
|
Dict | None
|
Dictionary of values to override default configuration. |
None
|
_callbacks
|
Dict | None
|
Dictionary of callback functions to customize behavior. |
None
|
Examples:
>>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
>>> predictor_example_with_imgsz = SAM2VideoPredictor(overrides={"imgsz": 640})
>>> predictor_example_with_callback = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
Source code in ultralytics/models/sam/predict.py
_add_output_per_object
Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
The resulting slices share the same tensor storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frame_idx
|
int
|
The index of the current frame. |
required |
current_out
|
Dict
|
The current output dictionary containing multi-object outputs. |
required |
storage_key
|
str
|
The key used to store the output in the per-object output dictionary. |
required |
Source code in ultralytics/models/sam/predict.py
_clear_non_cond_mem_around_input
Remove the non-conditioning memory around the input frame.
When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated object appearance information and could confuse the model. This method clears those non-conditioning memories surrounding the interacted frame to avoid giving the model both old and new information about the object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frame_idx
|
int
|
The index of the current frame where user interaction occurred. |
required |
Source code in ultralytics/models/sam/predict.py
_consolidate_temp_output_across_obj
Consolidates per-object temporary outputs into a single output for all objects.
This method combines the temporary outputs for each object on a given frame into a unified output. It fills in any missing objects either from the main output dictionary or leaves placeholders if they do not exist in the main output. Optionally, it can re-run the memory encoder after applying non-overlapping constraints to the object scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frame_idx
|
int
|
The index of the frame for which to consolidate outputs. |
required |
is_cond
|
(bool, Optional)
|
Indicates if the frame is considered a conditioning frame. Defaults to False. |
False
|
run_mem_encoder
|
(bool, Optional)
|
Specifies whether to run the memory encoder after consolidating the outputs. Defaults to False. |
False
|
Returns:
Name | Type | Description |
---|---|---|
consolidated_out |
dict
|
A consolidated output dictionary containing the combined results for all objects. |
Note
- The method initializes the consolidated output with placeholder values for missing objects.
- It searches for outputs in both the temporary and main output dictionaries.
- If
run_mem_encoder
is True, it applies non-overlapping constraints and re-runs the memory encoder. - The
maskmem_features
andmaskmem_pos_enc
are only populated whenrun_mem_encoder
is True.
Source code in ultralytics/models/sam/predict.py
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 |
|
_get_empty_mask_ptr
Get a dummy object pointer based on an empty mask on the current frame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
frame_idx
|
int
|
The index of the current frame for which to generate the dummy object pointer. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
A tensor representing the dummy object pointer generated from the empty mask. |
Source code in ultralytics/models/sam/predict.py
_get_maskmem_pos_enc
Caches and manages the positional encoding for mask memory across frames and objects.
This method optimizes storage by caching the positional encoding (maskmem_pos_enc
) for
mask memory, which is constant across frames and objects, thus reducing the amount of
redundant information stored during an inference session. It checks if the positional
encoding has already been cached; if not, it caches a slice of the provided encoding.
If the batch size is greater than one, it expands the cached positional encoding to match
the current batch size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
out_maskmem_pos_enc
|
List[Tensor] or None
|
The positional encoding for mask memory. Should be a list of tensors or None. |
required |
Returns:
Name | Type | Description |
---|---|---|
out_maskmem_pos_enc |
List[Tensor]
|
The positional encoding for mask memory, either cached or expanded. |
Note
- The method assumes that
out_maskmem_pos_enc
is a list of tensors or None. - Only a single object's slice is cached since the encoding is the same across objects.
- The method checks if the positional encoding has already been cached in the session's constants.
- If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
Source code in ultralytics/models/sam/predict.py
_obj_id_to_idx
Map client-side object id to model-side object index.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj_id
|
int
|
The unique identifier of the object provided by the client side. |
required |
Returns:
Name | Type | Description |
---|---|---|
obj_idx |
int
|
The index of the object on the model side. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If an attempt is made to add a new object after tracking has started. |
Note
- The method updates or retrieves mappings between object IDs and indices stored in
inference_state
. - It ensures that new objects can only be added before tracking commences.
- It maintains two-way mappings between IDs and indices (
obj_id_to_idx
andobj_idx_to_id
). - Additional data structures are initialized for the new object to store inputs and outputs.
Source code in ultralytics/models/sam/predict.py
_run_memory_encoder
Run the memory encoder on masks.
This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their memory also needs to be computed again with the memory encoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
The batch size for processing the frame. |
required |
high_res_masks
|
Tensor
|
High-resolution masks for which to compute the memory. |
required |
object_score_logits
|
Tensor
|
Logits representing the object scores. |
required |
is_mask_from_pts
|
bool
|
Indicates if the mask is derived from point interactions. |
required |
Returns:
Type | Description |
---|---|
tuple[Tensor, Tensor]
|
A tuple containing the encoded mask features and positional encoding. |
Source code in ultralytics/models/sam/predict.py
_run_single_frame_inference
_run_single_frame_inference(
output_dict,
frame_idx,
batch_size,
is_init_cond_frame,
point_inputs,
mask_inputs,
reverse,
run_mem_encoder,
prev_sam_mask_logits=None,
)
Run tracking on a single frame based on current inputs and previous memory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_dict
|
Dict
|
The dictionary containing the output states of the tracking process. |
required |
frame_idx
|
int
|
The index of the current frame. |
required |
batch_size
|
int
|
The batch size for processing the frame. |
required |
is_init_cond_frame
|
bool
|
Indicates if the current frame is an initial conditioning frame. |
required |
point_inputs
|
(Dict, Optional)
|
Input points and their labels. Defaults to None. |
required |
mask_inputs
|
(Tensor, Optional)
|
Input binary masks. Defaults to None. |
required |
reverse
|
bool
|
Indicates if the tracking should be performed in reverse order. |
required |
run_mem_encoder
|
bool
|
Indicates if the memory encoder should be executed. |
required |
prev_sam_mask_logits
|
(Tensor, Optional)
|
Previous mask logits for the current object. Defaults to None. |
None
|
Returns:
Name | Type | Description |
---|---|---|
current_out |
dict
|
A dictionary containing the output of the tracking step, including updated features and predictions. |
Raises:
Type | Description |
---|---|
AssertionError
|
If both |
Note
- The method assumes that
point_inputs
andmask_inputs
are mutually exclusive. - The method retrieves image features using the
get_im_features
method. - The
maskmem_pos_enc
is assumed to be constant across frames, hence only one copy is stored. - The
fill_holes_in_mask_scores
function is commented out and currently unsupported due to CUDA extension requirements.
Source code in ultralytics/models/sam/predict.py
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 |
|
add_new_prompts
Adds new points or masks to a specific frame for a given object ID.
This method updates the inference state with new prompts (points or masks) for a specified object and frame index. It ensures that the prompts are either points or masks, but not both, and updates the internal state accordingly. It also handles the generation of new segmentations based on the provided prompts and the existing state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj_id
|
int
|
The ID of the object to which the prompts are associated. |
required |
points
|
(Tensor, Optional)
|
The coordinates of the points of interest. Defaults to None. |
None
|
labels
|
(Tensor, Optional)
|
The labels corresponding to the points. Defaults to None. |
None
|
masks
|
Tensor
|
Binary masks for the object. Defaults to None. |
None
|
frame_idx
|
int
|
The index of the frame to which the prompts are applied. Defaults to 0. |
0
|
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing the flattened predicted masks and a tensor of ones indicating the number of objects. |
Raises:
Type | Description |
---|---|
AssertionError
|
If both |
Note
- Only one type of prompt (either points or masks) can be added per call.
- If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
- The method handles the consolidation of outputs and resizing of masks to the original video resolution.
Source code in ultralytics/models/sam/predict.py
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 |
|
get_im_features
Extracts and processes image features using SAM2's image encoder for subsequent segmentation tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
The input image tensor. |
required |
batch
|
int
|
The batch size for expanding features if there are multiple prompts. Defaults to 1. |
1
|
Returns:
Name | Type | Description |
---|---|---|
vis_feats |
Tensor
|
The visual features extracted from the image. |
vis_pos_embed |
Tensor
|
The positional embeddings for the visual features. |
feat_sizes |
List(Tuple[int])
|
A list containing the sizes of the extracted features. |
Note
- If
batch
is greater than 1, the features are expanded to fit the batch size. - The method leverages the model's
_prepare_backbone_features
method to prepare the backbone features.
Source code in ultralytics/models/sam/predict.py
get_model
Retrieves and configures the model with binarization enabled.
Note
This method overrides the base class implementation to set the binarize flag to True.
Source code in ultralytics/models/sam/predict.py
inference
Perform image segmentation inference based on the given input cues, using the currently loaded image. This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and mask decoder for real-time and promptable segmentation tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
The preprocessed input image in tensor format, with shape (N, C, H, W). |
required |
bboxes
|
ndarray | List
|
Bounding boxes with shape (N, 4), in XYXY format. |
None
|
points
|
ndarray | List
|
Points indicating object locations with shape (N, 2), in pixels. |
None
|
labels
|
ndarray | List
|
Labels for point prompts, shape (N, ). 1 = foreground, 0 = background. |
None
|
masks
|
ndarray
|
Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256. |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
The output masks in shape CxHxW, where C is the number of generated masks. |
ndarray
|
An array of length C containing quality scores predicted by the model for each mask. |
Source code in ultralytics/models/sam/predict.py
init_state
staticmethod
Initialize an inference state for the predictor.
This function sets up the initial state required for performing inference on video data. It includes initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata relevant to the tracking process.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictor
|
SAM2VideoPredictor
|
The predictor object for which to initialize the state. |
required |
Source code in ultralytics/models/sam/predict.py
postprocess
Post-processes the predictions to apply non-overlapping constraints if required.
This method extends the post-processing functionality by applying non-overlapping constraints
to the predicted masks if the non_overlap_masks
flag is set to True. This ensures that
the masks do not overlap, which can be useful for certain applications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
Tuple[Tensor]
|
The predictions from the model. |
required |
img
|
Tensor
|
The processed image tensor. |
required |
orig_imgs
|
List[ndarray]
|
The original images before processing. |
required |
Returns:
Name | Type | Description |
---|---|---|
results |
list
|
The post-processed predictions. |
Note
If non_overlap_masks
is True, the method applies constraints to ensure non-overlapping masks.
Source code in ultralytics/models/sam/predict.py
propagate_in_video_preflight
Prepare inference_state and consolidate temporary outputs before tracking.
This method marks the start of tracking, disallowing the addition of new objects until the session is reset.
It consolidates temporary outputs from temp_output_dict_per_obj
and merges them into output_dict
.
Additionally, it clears non-conditioning memory around input frames and ensures that the state is consistent
with the provided inputs.
Source code in ultralytics/models/sam/predict.py
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 |
|