ultralytics 8.1.28__py3-none-any.whl → 8.3.62__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +122 -0
- tests/test_cuda.py +155 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +216 -0
- tests/test_integrations.py +150 -0
- tests/test_python.py +615 -0
- tests/test_solutions.py +94 -0
- ultralytics/__init__.py +11 -8
- ultralytics/cfg/__init__.py +569 -131
- ultralytics/cfg/datasets/Argoverse.yaml +2 -1
- ultralytics/cfg/datasets/DOTAv1.5.yaml +3 -2
- ultralytics/cfg/datasets/DOTAv1.yaml +3 -2
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +3 -2
- ultralytics/cfg/datasets/ImageNet.yaml +2 -1
- ultralytics/cfg/datasets/Objects365.yaml +5 -4
- ultralytics/cfg/datasets/SKU-110K.yaml +2 -1
- ultralytics/cfg/datasets/VOC.yaml +3 -2
- ultralytics/cfg/datasets/VisDrone.yaml +6 -5
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco-pose.yaml +7 -6
- ultralytics/cfg/datasets/coco.yaml +3 -2
- ultralytics/cfg/datasets/coco128-seg.yaml +4 -3
- ultralytics/cfg/datasets/coco128.yaml +4 -3
- ultralytics/cfg/datasets/coco8-pose.yaml +3 -2
- ultralytics/cfg/datasets/coco8-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco8.yaml +3 -2
- ultralytics/cfg/datasets/crack-seg.yaml +3 -2
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8.yaml +3 -2
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1236 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +2 -1
- ultralytics/cfg/datasets/package-seg.yaml +5 -4
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +3 -2
- ultralytics/cfg/datasets/xView.yaml +2 -1
- ultralytics/cfg/default.yaml +14 -11
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +24 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +5 -2
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5-p6.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5.yaml +5 -2
- ultralytics/cfg/models/v6/yolov6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p6.yaml +10 -7
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-pose.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-world.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8.yaml +5 -2
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +30 -25
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +46 -42
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/solutions/default.yaml +24 -0
- ultralytics/cfg/trackers/botsort.yaml +8 -5
- ultralytics/cfg/trackers/bytetrack.yaml +8 -5
- ultralytics/data/__init__.py +14 -3
- ultralytics/data/annotator.py +37 -15
- ultralytics/data/augment.py +1783 -289
- ultralytics/data/base.py +62 -27
- ultralytics/data/build.py +36 -8
- ultralytics/data/converter.py +196 -36
- ultralytics/data/dataset.py +233 -94
- ultralytics/data/loaders.py +199 -96
- ultralytics/data/split_dota.py +39 -29
- ultralytics/data/utils.py +110 -40
- ultralytics/engine/__init__.py +1 -1
- ultralytics/engine/exporter.py +569 -242
- ultralytics/engine/model.py +604 -252
- ultralytics/engine/predictor.py +22 -11
- ultralytics/engine/results.py +1228 -218
- ultralytics/engine/trainer.py +190 -129
- ultralytics/engine/tuner.py +18 -18
- ultralytics/engine/validator.py +18 -15
- ultralytics/hub/__init__.py +31 -13
- ultralytics/hub/auth.py +11 -7
- ultralytics/hub/google/__init__.py +159 -0
- ultralytics/hub/session.py +128 -94
- ultralytics/hub/utils.py +20 -21
- ultralytics/models/__init__.py +4 -2
- ultralytics/models/fastsam/__init__.py +2 -3
- ultralytics/models/fastsam/model.py +26 -4
- ultralytics/models/fastsam/predict.py +127 -63
- ultralytics/models/fastsam/utils.py +1 -44
- ultralytics/models/fastsam/val.py +1 -1
- ultralytics/models/nas/__init__.py +1 -1
- ultralytics/models/nas/model.py +21 -10
- ultralytics/models/nas/predict.py +3 -6
- ultralytics/models/nas/val.py +4 -4
- ultralytics/models/rtdetr/__init__.py +1 -1
- ultralytics/models/rtdetr/model.py +1 -1
- ultralytics/models/rtdetr/predict.py +6 -8
- ultralytics/models/rtdetr/train.py +6 -2
- ultralytics/models/rtdetr/val.py +3 -3
- ultralytics/models/sam/__init__.py +3 -3
- ultralytics/models/sam/amg.py +29 -23
- ultralytics/models/sam/build.py +211 -13
- ultralytics/models/sam/model.py +91 -30
- ultralytics/models/sam/modules/__init__.py +1 -1
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +381 -53
- ultralytics/models/sam/modules/encoders.py +515 -324
- ultralytics/models/sam/modules/memory_attention.py +237 -0
- ultralytics/models/sam/modules/sam.py +969 -21
- ultralytics/models/sam/modules/tiny_encoder.py +425 -154
- ultralytics/models/sam/modules/transformer.py +159 -60
- ultralytics/models/sam/modules/utils.py +293 -0
- ultralytics/models/sam/predict.py +1263 -132
- ultralytics/models/utils/__init__.py +1 -1
- ultralytics/models/utils/loss.py +36 -24
- ultralytics/models/utils/ops.py +3 -7
- ultralytics/models/yolo/__init__.py +3 -3
- ultralytics/models/yolo/classify/__init__.py +1 -1
- ultralytics/models/yolo/classify/predict.py +7 -8
- ultralytics/models/yolo/classify/train.py +17 -22
- ultralytics/models/yolo/classify/val.py +8 -4
- ultralytics/models/yolo/detect/__init__.py +1 -1
- ultralytics/models/yolo/detect/predict.py +3 -5
- ultralytics/models/yolo/detect/train.py +11 -4
- ultralytics/models/yolo/detect/val.py +90 -52
- ultralytics/models/yolo/model.py +14 -9
- ultralytics/models/yolo/obb/__init__.py +1 -1
- ultralytics/models/yolo/obb/predict.py +2 -2
- ultralytics/models/yolo/obb/train.py +5 -3
- ultralytics/models/yolo/obb/val.py +41 -23
- ultralytics/models/yolo/pose/__init__.py +1 -1
- ultralytics/models/yolo/pose/predict.py +3 -5
- ultralytics/models/yolo/pose/train.py +2 -2
- ultralytics/models/yolo/pose/val.py +51 -17
- ultralytics/models/yolo/segment/__init__.py +1 -1
- ultralytics/models/yolo/segment/predict.py +3 -5
- ultralytics/models/yolo/segment/train.py +2 -2
- ultralytics/models/yolo/segment/val.py +60 -19
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +92 -0
- ultralytics/models/yolo/world/train_world.py +109 -0
- ultralytics/nn/__init__.py +1 -1
- ultralytics/nn/autobackend.py +228 -93
- ultralytics/nn/modules/__init__.py +39 -14
- ultralytics/nn/modules/activation.py +21 -0
- ultralytics/nn/modules/block.py +527 -67
- ultralytics/nn/modules/conv.py +24 -7
- ultralytics/nn/modules/head.py +177 -34
- ultralytics/nn/modules/transformer.py +6 -5
- ultralytics/nn/modules/utils.py +1 -2
- ultralytics/nn/tasks.py +225 -77
- ultralytics/solutions/__init__.py +30 -1
- ultralytics/solutions/ai_gym.py +96 -143
- ultralytics/solutions/analytics.py +247 -0
- ultralytics/solutions/distance_calculation.py +78 -135
- ultralytics/solutions/heatmap.py +93 -247
- ultralytics/solutions/object_counter.py +184 -259
- ultralytics/solutions/parking_management.py +246 -0
- ultralytics/solutions/queue_management.py +112 -0
- ultralytics/solutions/region_counter.py +116 -0
- ultralytics/solutions/security_alarm.py +144 -0
- ultralytics/solutions/solutions.py +178 -0
- ultralytics/solutions/speed_estimation.py +86 -174
- ultralytics/solutions/streamlit_inference.py +190 -0
- ultralytics/solutions/trackzone.py +68 -0
- ultralytics/trackers/__init__.py +1 -1
- ultralytics/trackers/basetrack.py +32 -13
- ultralytics/trackers/bot_sort.py +61 -28
- ultralytics/trackers/byte_tracker.py +83 -51
- ultralytics/trackers/track.py +21 -6
- ultralytics/trackers/utils/__init__.py +1 -1
- ultralytics/trackers/utils/gmc.py +62 -48
- ultralytics/trackers/utils/kalman_filter.py +166 -35
- ultralytics/trackers/utils/matching.py +40 -21
- ultralytics/utils/__init__.py +511 -239
- ultralytics/utils/autobatch.py +40 -22
- ultralytics/utils/benchmarks.py +266 -85
- ultralytics/utils/callbacks/__init__.py +1 -1
- ultralytics/utils/callbacks/base.py +1 -3
- ultralytics/utils/callbacks/clearml.py +7 -6
- ultralytics/utils/callbacks/comet.py +39 -17
- ultralytics/utils/callbacks/dvc.py +1 -1
- ultralytics/utils/callbacks/hub.py +16 -16
- ultralytics/utils/callbacks/mlflow.py +28 -24
- ultralytics/utils/callbacks/neptune.py +6 -2
- ultralytics/utils/callbacks/raytune.py +3 -4
- ultralytics/utils/callbacks/tensorboard.py +18 -18
- ultralytics/utils/callbacks/wb.py +27 -20
- ultralytics/utils/checks.py +160 -100
- ultralytics/utils/dist.py +2 -1
- ultralytics/utils/downloads.py +44 -37
- ultralytics/utils/errors.py +1 -1
- ultralytics/utils/files.py +72 -38
- ultralytics/utils/instance.py +41 -19
- ultralytics/utils/loss.py +84 -56
- ultralytics/utils/metrics.py +61 -56
- ultralytics/utils/ops.py +94 -89
- ultralytics/utils/patches.py +30 -14
- ultralytics/utils/plotting.py +600 -269
- ultralytics/utils/tal.py +67 -26
- ultralytics/utils/torch_utils.py +302 -102
- ultralytics/utils/triton.py +2 -1
- ultralytics/utils/tuner.py +21 -12
- ultralytics-8.3.62.dist-info/METADATA +370 -0
- ultralytics-8.3.62.dist-info/RECORD +241 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/WHEEL +1 -1
- ultralytics/data/explorer/__init__.py +0 -5
- ultralytics/data/explorer/explorer.py +0 -472
- ultralytics/data/explorer/gui/__init__.py +0 -1
- ultralytics/data/explorer/gui/dash.py +0 -268
- ultralytics/data/explorer/utils.py +0 -166
- ultralytics/models/fastsam/prompt.py +0 -357
- ultralytics-8.1.28.dist-info/METADATA +0 -373
- ultralytics-8.1.28.dist-info/RECORD +0 -197
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/LICENSE +0 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/top_level.txt +0 -0
@@ -1,4 +1,4 @@
|
|
1
|
-
# Ultralytics
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
2
|
"""
|
3
3
|
Generate predictions using the Segment Anything Model (SAM).
|
4
4
|
|
@@ -8,16 +8,18 @@ using SAM. It forms an integral part of the Ultralytics framework and is designe
|
|
8
8
|
segmentation tasks.
|
9
9
|
"""
|
10
10
|
|
11
|
+
from collections import OrderedDict
|
12
|
+
|
11
13
|
import numpy as np
|
12
14
|
import torch
|
13
15
|
import torch.nn.functional as F
|
14
|
-
import torchvision
|
15
16
|
|
16
17
|
from ultralytics.data.augment import LetterBox
|
17
18
|
from ultralytics.engine.predictor import BasePredictor
|
18
19
|
from ultralytics.engine.results import Results
|
19
20
|
from ultralytics.utils import DEFAULT_CFG, ops
|
20
|
-
from ultralytics.utils.torch_utils import select_device
|
21
|
+
from ultralytics.utils.torch_utils import select_device, smart_inference_mode
|
22
|
+
|
21
23
|
from .amg import (
|
22
24
|
batch_iterator,
|
23
25
|
batched_mask_to_box,
|
@@ -34,39 +36,68 @@ from .build import build_sam
|
|
34
36
|
|
35
37
|
class Predictor(BasePredictor):
|
36
38
|
"""
|
37
|
-
Predictor class for
|
39
|
+
Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
|
38
40
|
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
points, and low-resolution masks.
|
41
|
+
This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image
|
42
|
+
segmentation tasks. It supports various input prompts like points, bounding boxes, and masks for
|
43
|
+
fine-grained control over segmentation results.
|
43
44
|
|
44
45
|
Attributes:
|
45
|
-
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
46
|
+
args (SimpleNamespace): Configuration arguments for the predictor.
|
47
|
+
model (torch.nn.Module): The loaded SAM model.
|
48
|
+
device (torch.device): The device (CPU or GPU) on which the model is loaded.
|
49
|
+
im (torch.Tensor): The preprocessed input image.
|
50
|
+
features (torch.Tensor): Extracted image features.
|
51
|
+
prompts (Dict): Dictionary to store various types of prompts (e.g., bboxes, points, masks).
|
52
|
+
segment_all (bool): Flag to indicate if full image segmentation should be performed.
|
53
|
+
mean (torch.Tensor): Mean values for image normalization.
|
54
|
+
std (torch.Tensor): Standard deviation values for image normalization.
|
55
|
+
|
56
|
+
Methods:
|
57
|
+
preprocess: Prepares input images for model inference.
|
58
|
+
pre_transform: Performs initial transformations on the input image.
|
59
|
+
inference: Performs segmentation inference based on input prompts.
|
60
|
+
prompt_inference: Internal function for prompt-based segmentation inference.
|
61
|
+
generate: Generates segmentation masks for an entire image.
|
62
|
+
setup_model: Initializes the SAM model for inference.
|
63
|
+
get_model: Builds and returns a SAM model.
|
64
|
+
postprocess: Post-processes model outputs to generate final results.
|
65
|
+
setup_source: Sets up the data source for inference.
|
66
|
+
set_image: Sets and preprocesses a single image for inference.
|
67
|
+
get_im_features: Extracts image features using the SAM image encoder.
|
68
|
+
set_prompts: Sets prompts for subsequent inference.
|
69
|
+
reset_image: Resets the current image and its features.
|
70
|
+
remove_small_regions: Removes small disconnected regions and holes from masks.
|
71
|
+
|
72
|
+
Examples:
|
73
|
+
>>> predictor = Predictor()
|
74
|
+
>>> predictor.setup_model(model_path="sam_model.pt")
|
75
|
+
>>> predictor.set_image("image.jpg")
|
76
|
+
>>> bboxes = [[100, 100, 200, 200]]
|
77
|
+
>>> results = predictor(bboxes=bboxes)
|
53
78
|
"""
|
54
79
|
|
55
80
|
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
56
81
|
"""
|
57
82
|
Initialize the Predictor with configuration, overrides, and callbacks.
|
58
83
|
|
59
|
-
|
60
|
-
|
84
|
+
Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
|
85
|
+
callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True
|
86
|
+
for optimal results.
|
61
87
|
|
62
88
|
Args:
|
63
|
-
cfg (
|
64
|
-
overrides (
|
65
|
-
_callbacks (
|
89
|
+
cfg (Dict): Configuration dictionary containing default settings.
|
90
|
+
overrides (Dict | None): Dictionary of values to override default configuration.
|
91
|
+
_callbacks (Dict | None): Dictionary of callback functions to customize behavior.
|
92
|
+
|
93
|
+
Examples:
|
94
|
+
>>> predictor_example = Predictor(cfg=DEFAULT_CFG)
|
95
|
+
>>> predictor_example_with_imgsz = Predictor(overrides={"imgsz": 640})
|
96
|
+
>>> predictor_example_with_callback = Predictor(_callbacks={"on_predict_start": custom_callback})
|
66
97
|
"""
|
67
98
|
if overrides is None:
|
68
99
|
overrides = {}
|
69
|
-
overrides.update(dict(task="segment", mode="predict",
|
100
|
+
overrides.update(dict(task="segment", mode="predict", batch=1))
|
70
101
|
super().__init__(cfg, overrides, _callbacks)
|
71
102
|
self.args.retina_masks = True
|
72
103
|
self.im = None
|
@@ -78,14 +109,19 @@ class Predictor(BasePredictor):
|
|
78
109
|
"""
|
79
110
|
Preprocess the input image for model inference.
|
80
111
|
|
81
|
-
|
82
|
-
|
112
|
+
This method prepares the input image by applying transformations and normalization. It supports both
|
113
|
+
torch.Tensor and list of np.ndarray as input formats.
|
83
114
|
|
84
115
|
Args:
|
85
|
-
im (torch.Tensor | List[np.ndarray]): BCHW tensor format or list of HWC numpy arrays.
|
116
|
+
im (torch.Tensor | List[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.
|
86
117
|
|
87
118
|
Returns:
|
88
|
-
(torch.Tensor): The preprocessed image tensor.
|
119
|
+
im (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
|
120
|
+
|
121
|
+
Examples:
|
122
|
+
>>> predictor = Predictor()
|
123
|
+
>>> image = torch.rand(1, 3, 640, 640)
|
124
|
+
>>> preprocessed_image = predictor.preprocess(image)
|
89
125
|
"""
|
90
126
|
if self.im is not None:
|
91
127
|
return self.im
|
@@ -106,14 +142,24 @@ class Predictor(BasePredictor):
|
|
106
142
|
"""
|
107
143
|
Perform initial transformations on the input image for preprocessing.
|
108
144
|
|
109
|
-
|
145
|
+
This method applies transformations such as resizing to prepare the image for further preprocessing.
|
110
146
|
Currently, batched inference is not supported; hence the list length should be 1.
|
111
147
|
|
112
148
|
Args:
|
113
|
-
im (List[np.ndarray]): List containing
|
149
|
+
im (List[np.ndarray]): List containing a single image in HWC numpy array format.
|
114
150
|
|
115
151
|
Returns:
|
116
|
-
(List[np.ndarray]): List
|
152
|
+
(List[np.ndarray]): List containing the transformed image.
|
153
|
+
|
154
|
+
Raises:
|
155
|
+
AssertionError: If the input list contains more than one image.
|
156
|
+
|
157
|
+
Examples:
|
158
|
+
>>> predictor = Predictor()
|
159
|
+
>>> image = np.random.rand(480, 640, 3) # Single HWC image
|
160
|
+
>>> transformed = predictor.pre_transform([image])
|
161
|
+
>>> print(len(transformed))
|
162
|
+
1
|
117
163
|
"""
|
118
164
|
assert len(im) == 1, "SAM model does not currently support batched inference"
|
119
165
|
letterbox = LetterBox(self.args.imgsz, auto=False, center=False)
|
@@ -121,28 +167,37 @@ class Predictor(BasePredictor):
|
|
121
167
|
|
122
168
|
def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
|
123
169
|
"""
|
124
|
-
Perform image segmentation inference based on the given input cues, using the currently loaded image.
|
125
|
-
|
126
|
-
|
170
|
+
Perform image segmentation inference based on the given input cues, using the currently loaded image.
|
171
|
+
|
172
|
+
This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
|
173
|
+
encoder, and mask decoder for real-time and promptable segmentation tasks.
|
127
174
|
|
128
175
|
Args:
|
129
176
|
im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
|
130
|
-
bboxes (np.ndarray | List
|
131
|
-
points (np.ndarray | List
|
132
|
-
labels (np.ndarray | List
|
133
|
-
masks (np.ndarray
|
134
|
-
multimask_output (bool
|
177
|
+
bboxes (np.ndarray | List | None): Bounding boxes with shape (N, 4), in XYXY format.
|
178
|
+
points (np.ndarray | List | None): Points indicating object locations with shape (N, 2), in pixels.
|
179
|
+
labels (np.ndarray | List | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background.
|
180
|
+
masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256.
|
181
|
+
multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts.
|
182
|
+
*args (Any): Additional positional arguments.
|
183
|
+
**kwargs (Any): Additional keyword arguments.
|
135
184
|
|
136
185
|
Returns:
|
137
|
-
(
|
138
|
-
|
139
|
-
|
140
|
-
|
186
|
+
(np.ndarray): The output masks in shape (C, H, W), where C is the number of generated masks.
|
187
|
+
(np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
|
188
|
+
(np.ndarray): Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256.
|
189
|
+
|
190
|
+
Examples:
|
191
|
+
>>> predictor = Predictor()
|
192
|
+
>>> predictor.setup_model(model_path="sam_model.pt")
|
193
|
+
>>> predictor.set_image("image.jpg")
|
194
|
+
>>> results = predictor(bboxes=[[0, 0, 100, 100]])
|
141
195
|
"""
|
142
196
|
# Override prompts if any stored in self.prompts
|
143
197
|
bboxes = self.prompts.pop("bboxes", bboxes)
|
144
198
|
points = self.prompts.pop("points", points)
|
145
199
|
masks = self.prompts.pop("masks", masks)
|
200
|
+
labels = self.prompts.pop("labels", labels)
|
146
201
|
|
147
202
|
if all(i is None for i in [bboxes, points, masks]):
|
148
203
|
return self.generate(im, *args, **kwargs)
|
@@ -151,45 +206,35 @@ class Predictor(BasePredictor):
|
|
151
206
|
|
152
207
|
def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False):
|
153
208
|
"""
|
154
|
-
|
155
|
-
|
209
|
+
Performs image segmentation inference based on input cues using SAM's specialized architecture.
|
210
|
+
|
211
|
+
This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation.
|
212
|
+
It processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.
|
156
213
|
|
157
214
|
Args:
|
158
|
-
im (torch.Tensor):
|
159
|
-
bboxes (np.ndarray | List
|
160
|
-
points (np.ndarray | List
|
161
|
-
labels (np.ndarray | List
|
162
|
-
masks (np.ndarray
|
163
|
-
multimask_output (bool
|
215
|
+
im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
|
216
|
+
bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
|
217
|
+
points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
|
218
|
+
labels (np.ndarray | List | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
|
219
|
+
masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
|
220
|
+
multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
|
221
|
+
|
222
|
+
Raises:
|
223
|
+
AssertionError: If the number of points don't match the number of labels, in case labels were passed.
|
164
224
|
|
165
225
|
Returns:
|
166
|
-
(
|
167
|
-
|
168
|
-
|
169
|
-
|
226
|
+
(np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
|
227
|
+
(np.ndarray): Quality scores predicted by the model for each mask, with length C.
|
228
|
+
|
229
|
+
Examples:
|
230
|
+
>>> predictor = Predictor()
|
231
|
+
>>> im = torch.rand(1, 3, 1024, 1024)
|
232
|
+
>>> bboxes = [[100, 100, 200, 200]]
|
233
|
+
>>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
|
170
234
|
"""
|
171
|
-
features = self.
|
172
|
-
|
173
|
-
src_shape, dst_shape = self.batch[1][0].shape[:2], im.shape[2:]
|
174
|
-
r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1])
|
175
|
-
# Transform input prompts
|
176
|
-
if points is not None:
|
177
|
-
points = torch.as_tensor(points, dtype=torch.float32, device=self.device)
|
178
|
-
points = points[None] if points.ndim == 1 else points
|
179
|
-
# Assuming labels are all positive if users don't pass labels.
|
180
|
-
if labels is None:
|
181
|
-
labels = np.ones(points.shape[0])
|
182
|
-
labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
|
183
|
-
points *= r
|
184
|
-
# (N, 2) --> (N, 1, 2), (N, ) --> (N, 1)
|
185
|
-
points, labels = points[:, None, :], labels[:, None]
|
186
|
-
if bboxes is not None:
|
187
|
-
bboxes = torch.as_tensor(bboxes, dtype=torch.float32, device=self.device)
|
188
|
-
bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
|
189
|
-
bboxes *= r
|
190
|
-
if masks is not None:
|
191
|
-
masks = torch.as_tensor(masks, dtype=torch.float32, device=self.device).unsqueeze(1)
|
235
|
+
features = self.get_im_features(im) if self.features is None else self.features
|
192
236
|
|
237
|
+
bboxes, points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
|
193
238
|
points = (points, labels) if points is not None else None
|
194
239
|
# Embed prompts
|
195
240
|
sparse_embeddings, dense_embeddings = self.model.prompt_encoder(points=points, boxes=bboxes, masks=masks)
|
@@ -207,6 +252,48 @@ class Predictor(BasePredictor):
|
|
207
252
|
# `d` could be 1 or 3 depends on `multimask_output`.
|
208
253
|
return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
|
209
254
|
|
255
|
+
def _prepare_prompts(self, dst_shape, bboxes=None, points=None, labels=None, masks=None):
|
256
|
+
"""
|
257
|
+
Prepares and transforms the input prompts for processing based on the destination shape.
|
258
|
+
|
259
|
+
Args:
|
260
|
+
dst_shape (tuple): The target shape (height, width) for the prompts.
|
261
|
+
bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
|
262
|
+
points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
|
263
|
+
labels (np.ndarray | List | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
|
264
|
+
masks (List | np.ndarray, Optional): Masks for the objects, where each mask is a 2D array.
|
265
|
+
|
266
|
+
Raises:
|
267
|
+
AssertionError: If the number of points don't match the number of labels, in case labels were passed.
|
268
|
+
|
269
|
+
Returns:
|
270
|
+
(tuple): A tuple containing transformed bounding boxes, points, labels, and masks.
|
271
|
+
"""
|
272
|
+
src_shape = self.batch[1][0].shape[:2]
|
273
|
+
r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1])
|
274
|
+
# Transform input prompts
|
275
|
+
if points is not None:
|
276
|
+
points = torch.as_tensor(points, dtype=torch.float32, device=self.device)
|
277
|
+
points = points[None] if points.ndim == 1 else points
|
278
|
+
# Assuming labels are all positive if users don't pass labels.
|
279
|
+
if labels is None:
|
280
|
+
labels = np.ones(points.shape[:-1])
|
281
|
+
labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
|
282
|
+
assert points.shape[-2] == labels.shape[-1], (
|
283
|
+
f"Number of points {points.shape[-2]} should match number of labels {labels.shape[-1]}."
|
284
|
+
)
|
285
|
+
points *= r
|
286
|
+
if points.ndim == 2:
|
287
|
+
# (N, 2) --> (N, 1, 2), (N, ) --> (N, 1)
|
288
|
+
points, labels = points[:, None, :], labels[:, None]
|
289
|
+
if bboxes is not None:
|
290
|
+
bboxes = torch.as_tensor(bboxes, dtype=torch.float32, device=self.device)
|
291
|
+
bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
|
292
|
+
bboxes *= r
|
293
|
+
if masks is not None:
|
294
|
+
masks = torch.as_tensor(masks, dtype=torch.float32, device=self.device).unsqueeze(1)
|
295
|
+
return bboxes, points, labels, masks
|
296
|
+
|
210
297
|
def generate(
|
211
298
|
self,
|
212
299
|
im,
|
@@ -224,28 +311,34 @@ class Predictor(BasePredictor):
|
|
224
311
|
"""
|
225
312
|
Perform image segmentation using the Segment Anything Model (SAM).
|
226
313
|
|
227
|
-
This
|
314
|
+
This method segments an entire image into constituent parts by leveraging SAM's advanced architecture
|
228
315
|
and real-time performance capabilities. It can optionally work on image crops for finer segmentation.
|
229
316
|
|
230
317
|
Args:
|
231
|
-
im (torch.Tensor): Input tensor representing the preprocessed image with
|
232
|
-
crop_n_layers (int):
|
233
|
-
|
234
|
-
|
235
|
-
|
236
|
-
|
237
|
-
Used in the nth crop layer.
|
238
|
-
points_stride (int, optional): Number of points to sample along each side of the image.
|
239
|
-
Exclusive with 'point_grids'.
|
318
|
+
im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W).
|
319
|
+
crop_n_layers (int): Number of layers for additional mask predictions on image crops.
|
320
|
+
crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers.
|
321
|
+
crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer.
|
322
|
+
point_grids (List[np.ndarray] | None): Custom grids for point sampling normalized to [0,1].
|
323
|
+
points_stride (int): Number of points to sample along each side of the image.
|
240
324
|
points_batch_size (int): Batch size for the number of points processed simultaneously.
|
241
|
-
conf_thres (float): Confidence threshold [0,1] for filtering based on
|
242
|
-
stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on
|
325
|
+
conf_thres (float): Confidence threshold [0,1] for filtering based on mask quality prediction.
|
326
|
+
stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability.
|
243
327
|
stability_score_offset (float): Offset value for calculating stability score.
|
244
|
-
crop_nms_thresh (float): IoU cutoff for
|
328
|
+
crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
|
245
329
|
|
246
330
|
Returns:
|
247
|
-
(
|
331
|
+
pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
|
332
|
+
pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
|
333
|
+
pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).
|
334
|
+
|
335
|
+
Examples:
|
336
|
+
>>> predictor = Predictor()
|
337
|
+
>>> im = torch.rand(1, 3, 1024, 1024) # Example input image
|
338
|
+
>>> masks, scores, boxes = predictor.generate(im)
|
248
339
|
"""
|
340
|
+
import torchvision # scope for faster 'import ultralytics'
|
341
|
+
|
249
342
|
self.segment_all = True
|
250
343
|
ih, iw = im.shape[2:]
|
251
344
|
crop_regions, layer_idxs = generate_crop_boxes((ih, iw), crop_n_layers, crop_overlap_ratio)
|
@@ -313,7 +406,7 @@ class Predictor(BasePredictor):
|
|
313
406
|
|
314
407
|
return pred_masks, pred_scores, pred_bboxes
|
315
408
|
|
316
|
-
def setup_model(self, model, verbose=True):
|
409
|
+
def setup_model(self, model=None, verbose=True):
|
317
410
|
"""
|
318
411
|
Initializes the Segment Anything Model (SAM) for inference.
|
319
412
|
|
@@ -321,18 +414,16 @@ class Predictor(BasePredictor):
|
|
321
414
|
parameters for image normalization and other Ultralytics compatibility settings.
|
322
415
|
|
323
416
|
Args:
|
324
|
-
model (torch.nn.Module): A
|
417
|
+
model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config.
|
325
418
|
verbose (bool): If True, prints selected device information.
|
326
419
|
|
327
|
-
|
328
|
-
|
329
|
-
|
330
|
-
mean (torch.Tensor): The mean values for image normalization.
|
331
|
-
std (torch.Tensor): The standard deviation values for image normalization.
|
420
|
+
Examples:
|
421
|
+
>>> predictor = Predictor()
|
422
|
+
>>> predictor.setup_model(model=sam_model, verbose=True)
|
332
423
|
"""
|
333
424
|
device = select_device(self.args.device, verbose=verbose)
|
334
425
|
if model is None:
|
335
|
-
model =
|
426
|
+
model = self.get_model()
|
336
427
|
model.eval()
|
337
428
|
self.model = model.to(device)
|
338
429
|
self.device = device
|
@@ -346,20 +437,33 @@ class Predictor(BasePredictor):
|
|
346
437
|
self.model.fp16 = False
|
347
438
|
self.done_warmup = True
|
348
439
|
|
440
|
+
def get_model(self):
|
441
|
+
"""Retrieves or builds the Segment Anything Model (SAM) for image segmentation tasks."""
|
442
|
+
return build_sam(self.args.model)
|
443
|
+
|
349
444
|
def postprocess(self, preds, img, orig_imgs):
|
350
445
|
"""
|
351
446
|
Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.
|
352
447
|
|
353
|
-
|
354
|
-
|
448
|
+
This method scales masks and boxes to the original image size and applies a threshold to the mask
|
449
|
+
predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.
|
355
450
|
|
356
451
|
Args:
|
357
|
-
preds (
|
358
|
-
|
359
|
-
|
452
|
+
preds (Tuple[torch.Tensor]): The output from SAM model inference, containing:
|
453
|
+
- pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W).
|
454
|
+
- pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1).
|
455
|
+
- pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True.
|
456
|
+
img (torch.Tensor): The processed input image tensor with shape (C, H, W).
|
457
|
+
orig_imgs (List[np.ndarray] | torch.Tensor): The original, unprocessed images.
|
360
458
|
|
361
459
|
Returns:
|
362
|
-
(
|
460
|
+
results (List[Results]): List of Results objects containing detection masks, bounding boxes, and other
|
461
|
+
metadata for each processed image.
|
462
|
+
|
463
|
+
Examples:
|
464
|
+
>>> predictor = Predictor()
|
465
|
+
>>> preds = predictor.inference(img)
|
466
|
+
>>> results = predictor.postprocess(preds, img, orig_imgs)
|
363
467
|
"""
|
364
468
|
# (N, 1, H, W), (N, 1)
|
365
469
|
pred_masks, pred_scores = preds[:2]
|
@@ -370,16 +474,19 @@ class Predictor(BasePredictor):
|
|
370
474
|
orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
|
371
475
|
|
372
476
|
results = []
|
373
|
-
for
|
374
|
-
|
375
|
-
|
376
|
-
|
477
|
+
for masks, orig_img, img_path in zip([pred_masks], orig_imgs, self.batch[0]):
|
478
|
+
if len(masks) == 0:
|
479
|
+
masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device)
|
480
|
+
else:
|
481
|
+
masks = ops.scale_masks(masks[None].float(), orig_img.shape[:2], padding=False)[0]
|
482
|
+
masks = masks > self.model.mask_threshold # to bool
|
483
|
+
if pred_bboxes is not None:
|
484
|
+
pred_bboxes = ops.scale_boxes(img.shape[2:], pred_bboxes.float(), orig_img.shape, padding=False)
|
485
|
+
else:
|
486
|
+
pred_bboxes = batched_mask_to_box(masks)
|
487
|
+
# NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency.
|
377
488
|
cls = torch.arange(len(pred_masks), dtype=torch.int32, device=pred_masks.device)
|
378
489
|
pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1)
|
379
|
-
|
380
|
-
masks = ops.scale_masks(masks[None].float(), orig_img.shape[:2], padding=False)[0]
|
381
|
-
masks = masks > self.model.mask_threshold # to bool
|
382
|
-
img_path = self.batch[0][i]
|
383
490
|
results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=pred_bboxes))
|
384
491
|
# Reset segment-all mode.
|
385
492
|
self.segment_all = False
|
@@ -389,11 +496,23 @@ class Predictor(BasePredictor):
|
|
389
496
|
"""
|
390
497
|
Sets up the data source for inference.
|
391
498
|
|
392
|
-
This method configures the data source from which images will be fetched for inference.
|
393
|
-
|
499
|
+
This method configures the data source from which images will be fetched for inference. It supports
|
500
|
+
various input types such as image files, directories, video files, and other compatible data sources.
|
394
501
|
|
395
502
|
Args:
|
396
|
-
source (str | Path): The path
|
503
|
+
source (str | Path | None): The path or identifier for the image data source. Can be a file path,
|
504
|
+
directory path, URL, or other supported source types.
|
505
|
+
|
506
|
+
Examples:
|
507
|
+
>>> predictor = Predictor()
|
508
|
+
>>> predictor.setup_source("path/to/images")
|
509
|
+
>>> predictor.setup_source("video.mp4")
|
510
|
+
>>> predictor.setup_source(None) # Uses default source if available
|
511
|
+
|
512
|
+
Notes:
|
513
|
+
- If source is None, the method may use a default source if configured.
|
514
|
+
- The method adapts to different source types and prepares them for subsequent inference steps.
|
515
|
+
- Supported source types may include local files, directories, URLs, and video streams.
|
397
516
|
"""
|
398
517
|
if source is not None:
|
399
518
|
super().setup_source(source)
|
@@ -402,53 +521,80 @@ class Predictor(BasePredictor):
|
|
402
521
|
"""
|
403
522
|
Preprocesses and sets a single image for inference.
|
404
523
|
|
405
|
-
This
|
406
|
-
and
|
524
|
+
This method prepares the model for inference on a single image by setting up the model if not already
|
525
|
+
initialized, configuring the data source, and preprocessing the image for feature extraction. It
|
526
|
+
ensures that only one image is set at a time and extracts image features for subsequent use.
|
407
527
|
|
408
528
|
Args:
|
409
|
-
image (str | np.ndarray):
|
529
|
+
image (str | np.ndarray): Path to the image file as a string, or a numpy array representing
|
530
|
+
an image read by cv2.
|
410
531
|
|
411
532
|
Raises:
|
412
|
-
AssertionError: If more than one image is set.
|
533
|
+
AssertionError: If more than one image is attempted to be set.
|
534
|
+
|
535
|
+
Examples:
|
536
|
+
>>> predictor = Predictor()
|
537
|
+
>>> predictor.set_image("path/to/image.jpg")
|
538
|
+
>>> predictor.set_image(cv2.imread("path/to/image.jpg"))
|
539
|
+
|
540
|
+
Notes:
|
541
|
+
- This method should be called before performing inference on a new image.
|
542
|
+
- The extracted features are stored in the `self.features` attribute for later use.
|
413
543
|
"""
|
414
544
|
if self.model is None:
|
415
|
-
|
416
|
-
self.setup_model(model)
|
545
|
+
self.setup_model(model=None)
|
417
546
|
self.setup_source(image)
|
418
547
|
assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
|
419
548
|
for batch in self.dataset:
|
420
549
|
im = self.preprocess(batch[1])
|
421
|
-
self.features = self.
|
422
|
-
self.im = im
|
550
|
+
self.features = self.get_im_features(im)
|
423
551
|
break
|
424
552
|
|
553
|
+
def get_im_features(self, im):
|
554
|
+
"""Extracts image features using the SAM model's image encoder for subsequent mask prediction."""
|
555
|
+
assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
|
556
|
+
f"SAM models only support square image size, but got {self.imgsz}."
|
557
|
+
)
|
558
|
+
self.model.set_imgsz(self.imgsz)
|
559
|
+
return self.model.image_encoder(im)
|
560
|
+
|
425
561
|
def set_prompts(self, prompts):
|
426
|
-
"""
|
562
|
+
"""Sets prompts for subsequent inference operations."""
|
427
563
|
self.prompts = prompts
|
428
564
|
|
429
565
|
def reset_image(self):
|
430
|
-
"""Resets the image and its features
|
566
|
+
"""Resets the current image and its features, clearing them for subsequent inference."""
|
431
567
|
self.im = None
|
432
568
|
self.features = None
|
433
569
|
|
434
570
|
@staticmethod
|
435
571
|
def remove_small_regions(masks, min_area=0, nms_thresh=0.7):
|
436
572
|
"""
|
437
|
-
|
438
|
-
|
573
|
+
Remove small disconnected regions and holes from segmentation masks.
|
574
|
+
|
575
|
+
This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM).
|
576
|
+
It removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
|
439
577
|
Suppression (NMS) to eliminate any newly created duplicate boxes.
|
440
578
|
|
441
579
|
Args:
|
442
|
-
masks (torch.Tensor):
|
443
|
-
|
444
|
-
min_area (int):
|
445
|
-
|
580
|
+
masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
|
581
|
+
masks, H is height, and W is width.
|
582
|
+
min_area (int): Minimum area threshold for removing disconnected regions and holes. Regions smaller than
|
583
|
+
this will be removed.
|
584
|
+
nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.
|
446
585
|
|
447
586
|
Returns:
|
448
|
-
(
|
449
|
-
|
450
|
-
|
587
|
+
new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
|
588
|
+
keep (List[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.
|
589
|
+
|
590
|
+
Examples:
|
591
|
+
>>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks
|
592
|
+
>>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
|
593
|
+
>>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
|
594
|
+
>>> print(f"Indices of kept masks: {keep}")
|
451
595
|
"""
|
596
|
+
import torchvision # scope for faster 'import ultralytics'
|
597
|
+
|
452
598
|
if len(masks) == 0:
|
453
599
|
return masks
|
454
600
|
|
@@ -472,3 +618,988 @@ class Predictor(BasePredictor):
|
|
472
618
|
keep = torchvision.ops.nms(boxes.float(), torch.as_tensor(scores), nms_thresh)
|
473
619
|
|
474
620
|
return new_masks[keep].to(device=masks.device, dtype=masks.dtype), keep
|
621
|
+
|
622
|
+
|
623
|
+
class SAM2Predictor(Predictor):
|
624
|
+
"""
|
625
|
+
SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
|
626
|
+
|
627
|
+
This class extends the base Predictor class to implement SAM2-specific functionality for image
|
628
|
+
segmentation tasks. It provides methods for model initialization, feature extraction, and
|
629
|
+
prompt-based inference.
|
630
|
+
|
631
|
+
Attributes:
|
632
|
+
_bb_feat_sizes (List[Tuple[int, int]]): Feature sizes for different backbone levels.
|
633
|
+
model (torch.nn.Module): The loaded SAM2 model.
|
634
|
+
device (torch.device): The device (CPU or GPU) on which the model is loaded.
|
635
|
+
features (Dict[str, torch.Tensor]): Cached image features for efficient inference.
|
636
|
+
segment_all (bool): Flag to indicate if all segments should be predicted.
|
637
|
+
prompts (Dict): Dictionary to store various types of prompts for inference.
|
638
|
+
|
639
|
+
Methods:
|
640
|
+
get_model: Retrieves and initializes the SAM2 model.
|
641
|
+
prompt_inference: Performs image segmentation inference based on various prompts.
|
642
|
+
set_image: Preprocesses and sets a single image for inference.
|
643
|
+
get_im_features: Extracts and processes image features using SAM2's image encoder.
|
644
|
+
|
645
|
+
Examples:
|
646
|
+
>>> predictor = SAM2Predictor(cfg)
|
647
|
+
>>> predictor.set_image("path/to/image.jpg")
|
648
|
+
>>> bboxes = [[100, 100, 200, 200]]
|
649
|
+
>>> result = predictor(bboxes=bboxes)[0]
|
650
|
+
>>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
|
651
|
+
"""
|
652
|
+
|
653
|
+
_bb_feat_sizes = [
|
654
|
+
(256, 256),
|
655
|
+
(128, 128),
|
656
|
+
(64, 64),
|
657
|
+
]
|
658
|
+
|
659
|
+
def get_model(self):
|
660
|
+
"""Retrieves and initializes the Segment Anything Model 2 (SAM2) for image segmentation tasks."""
|
661
|
+
return build_sam(self.args.model)
|
662
|
+
|
663
|
+
def prompt_inference(
|
664
|
+
self,
|
665
|
+
im,
|
666
|
+
bboxes=None,
|
667
|
+
points=None,
|
668
|
+
labels=None,
|
669
|
+
masks=None,
|
670
|
+
multimask_output=False,
|
671
|
+
img_idx=-1,
|
672
|
+
):
|
673
|
+
"""
|
674
|
+
Performs image segmentation inference based on various prompts using SAM2 architecture.
|
675
|
+
|
676
|
+
This method leverages the Segment Anything Model 2 (SAM2) to generate segmentation masks for input images
|
677
|
+
based on provided prompts such as bounding boxes, points, or existing masks. It supports both single and
|
678
|
+
multi-object prediction scenarios.
|
679
|
+
|
680
|
+
Args:
|
681
|
+
im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
|
682
|
+
bboxes (np.ndarray | List[List[float]] | None): Bounding boxes in XYXY format with shape (N, 4).
|
683
|
+
points (np.ndarray | List[List[float]] | None): Object location points with shape (N, 2), in pixels.
|
684
|
+
labels (np.ndarray | List[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
|
685
|
+
masks (np.ndarray | None): Low-resolution masks from previous predictions with shape (N, H, W).
|
686
|
+
multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
|
687
|
+
img_idx (int): Index of the image in the batch to process.
|
688
|
+
|
689
|
+
Returns:
|
690
|
+
(np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
|
691
|
+
(np.ndarray): Quality scores for each mask, with length C.
|
692
|
+
|
693
|
+
Examples:
|
694
|
+
>>> predictor = SAM2Predictor(cfg)
|
695
|
+
>>> image = torch.rand(1, 3, 640, 640)
|
696
|
+
>>> bboxes = [[100, 100, 200, 200]]
|
697
|
+
>>> result = predictor(image, bboxes=bboxes)[0]
|
698
|
+
>>> print(f"Generated {result.masks.shape[0]} masks with average score {result.boxes.conf.mean():.2f}")
|
699
|
+
|
700
|
+
Notes:
|
701
|
+
- The method supports batched inference for multiple objects when points or bboxes are provided.
|
702
|
+
- Input prompts (bboxes, points) are automatically scaled to match the input image dimensions.
|
703
|
+
- When both bboxes and points are provided, they are merged into a single 'points' input for the model.
|
704
|
+
|
705
|
+
References:
|
706
|
+
- SAM2 Paper: [Add link to SAM2 paper when available]
|
707
|
+
"""
|
708
|
+
features = self.get_im_features(im) if self.features is None else self.features
|
709
|
+
|
710
|
+
points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
|
711
|
+
points = (points, labels) if points is not None else None
|
712
|
+
|
713
|
+
sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
|
714
|
+
points=points,
|
715
|
+
boxes=None,
|
716
|
+
masks=masks,
|
717
|
+
)
|
718
|
+
# Predict masks
|
719
|
+
batched_mode = points is not None and points[0].shape[0] > 1 # multi object prediction
|
720
|
+
high_res_features = [feat_level[img_idx].unsqueeze(0) for feat_level in features["high_res_feats"]]
|
721
|
+
pred_masks, pred_scores, _, _ = self.model.sam_mask_decoder(
|
722
|
+
image_embeddings=features["image_embed"][img_idx].unsqueeze(0),
|
723
|
+
image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
|
724
|
+
sparse_prompt_embeddings=sparse_embeddings,
|
725
|
+
dense_prompt_embeddings=dense_embeddings,
|
726
|
+
multimask_output=multimask_output,
|
727
|
+
repeat_image=batched_mode,
|
728
|
+
high_res_features=high_res_features,
|
729
|
+
)
|
730
|
+
# (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
|
731
|
+
# `d` could be 1 or 3 depends on `multimask_output`.
|
732
|
+
return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
|
733
|
+
|
734
|
+
def _prepare_prompts(self, dst_shape, bboxes=None, points=None, labels=None, masks=None):
|
735
|
+
"""
|
736
|
+
Prepares and transforms the input prompts for processing based on the destination shape.
|
737
|
+
|
738
|
+
Args:
|
739
|
+
dst_shape (tuple): The target shape (height, width) for the prompts.
|
740
|
+
bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
|
741
|
+
points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
|
742
|
+
labels (np.ndarray | List | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground, 0 for background.
|
743
|
+
masks (List | np.ndarray, Optional): Masks for the objects, where each mask is a 2D array.
|
744
|
+
|
745
|
+
Raises:
|
746
|
+
AssertionError: If the number of points don't match the number of labels, in case labels were passed.
|
747
|
+
|
748
|
+
Returns:
|
749
|
+
(tuple): A tuple containing transformed points, labels, and masks.
|
750
|
+
"""
|
751
|
+
bboxes, points, labels, masks = super()._prepare_prompts(dst_shape, bboxes, points, labels, masks)
|
752
|
+
if bboxes is not None:
|
753
|
+
bboxes = bboxes.view(-1, 2, 2)
|
754
|
+
bbox_labels = torch.tensor([[2, 3]], dtype=torch.int32, device=bboxes.device).expand(len(bboxes), -1)
|
755
|
+
# NOTE: merge "boxes" and "points" into a single "points" input
|
756
|
+
# (where boxes are added at the beginning) to model.sam_prompt_encoder
|
757
|
+
if points is not None:
|
758
|
+
points = torch.cat([bboxes, points], dim=1)
|
759
|
+
labels = torch.cat([bbox_labels, labels], dim=1)
|
760
|
+
else:
|
761
|
+
points, labels = bboxes, bbox_labels
|
762
|
+
return points, labels, masks
|
763
|
+
|
764
|
+
def set_image(self, image):
|
765
|
+
"""
|
766
|
+
Preprocesses and sets a single image for inference using the SAM2 model.
|
767
|
+
|
768
|
+
This method initializes the model if not already done, configures the data source to the specified image,
|
769
|
+
and preprocesses the image for feature extraction. It supports setting only one image at a time.
|
770
|
+
|
771
|
+
Args:
|
772
|
+
image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.
|
773
|
+
|
774
|
+
Raises:
|
775
|
+
AssertionError: If more than one image is attempted to be set.
|
776
|
+
|
777
|
+
Examples:
|
778
|
+
>>> predictor = SAM2Predictor()
|
779
|
+
>>> predictor.set_image("path/to/image.jpg")
|
780
|
+
>>> predictor.set_image(np.array([...])) # Using a numpy array
|
781
|
+
|
782
|
+
Notes:
|
783
|
+
- This method must be called before performing any inference on a new image.
|
784
|
+
- The method caches the extracted features for efficient subsequent inferences on the same image.
|
785
|
+
- Only one image can be set at a time. To process multiple images, call this method for each new image.
|
786
|
+
"""
|
787
|
+
if self.model is None:
|
788
|
+
self.setup_model(model=None)
|
789
|
+
self.setup_source(image)
|
790
|
+
assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
|
791
|
+
for batch in self.dataset:
|
792
|
+
im = self.preprocess(batch[1])
|
793
|
+
self.features = self.get_im_features(im)
|
794
|
+
break
|
795
|
+
|
796
|
+
def get_im_features(self, im):
|
797
|
+
"""Extracts image features from the SAM image encoder for subsequent processing."""
|
798
|
+
assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
|
799
|
+
f"SAM 2 models only support square image size, but got {self.imgsz}."
|
800
|
+
)
|
801
|
+
self.model.set_imgsz(self.imgsz)
|
802
|
+
self._bb_feat_sizes = [[x // (4 * i) for x in self.imgsz] for i in [1, 2, 4]]
|
803
|
+
|
804
|
+
backbone_out = self.model.forward_image(im)
|
805
|
+
_, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
|
806
|
+
if self.model.directly_add_no_mem_embed:
|
807
|
+
vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
|
808
|
+
feats = [
|
809
|
+
feat.permute(1, 2, 0).view(1, -1, *feat_size)
|
810
|
+
for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
|
811
|
+
][::-1]
|
812
|
+
return {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
|
813
|
+
|
814
|
+
|
815
|
+
class SAM2VideoPredictor(SAM2Predictor):
|
816
|
+
"""
|
817
|
+
SAM2VideoPredictor to handle user interactions with videos and manage inference states.
|
818
|
+
|
819
|
+
This class extends the functionality of SAM2Predictor to support video processing and maintains
|
820
|
+
the state of inference operations. It includes configurations for managing non-overlapping masks,
|
821
|
+
clearing memory for non-conditional inputs, and setting up callbacks for prediction events.
|
822
|
+
|
823
|
+
Attributes:
|
824
|
+
inference_state (Dict): A dictionary to store the current state of inference operations.
|
825
|
+
non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
|
826
|
+
clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
|
827
|
+
clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object scenarios.
|
828
|
+
callbacks (Dict): A dictionary of callbacks for various prediction lifecycle events.
|
829
|
+
|
830
|
+
Args:
|
831
|
+
cfg (Dict, Optional): Configuration settings for the predictor. Defaults to DEFAULT_CFG.
|
832
|
+
overrides (Dict, Optional): Additional configuration overrides. Defaults to None.
|
833
|
+
_callbacks (List, Optional): Custom callbacks to be added. Defaults to None.
|
834
|
+
|
835
|
+
Note:
|
836
|
+
The `fill_hole_area` attribute is defined but not used in the current implementation.
|
837
|
+
"""
|
838
|
+
|
839
|
+
# fill_hole_area = 8 # not used
|
840
|
+
|
841
|
+
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
842
|
+
"""
|
843
|
+
Initialize the predictor with configuration and optional overrides.
|
844
|
+
|
845
|
+
This constructor initializes the SAM2VideoPredictor with a given configuration, applies any
|
846
|
+
specified overrides, and sets up the inference state along with certain flags
|
847
|
+
that control the behavior of the predictor.
|
848
|
+
|
849
|
+
Args:
|
850
|
+
cfg (Dict): Configuration dictionary containing default settings.
|
851
|
+
overrides (Dict | None): Dictionary of values to override default configuration.
|
852
|
+
_callbacks (Dict | None): Dictionary of callback functions to customize behavior.
|
853
|
+
|
854
|
+
Examples:
|
855
|
+
>>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
|
856
|
+
>>> predictor_example_with_imgsz = SAM2VideoPredictor(overrides={"imgsz": 640})
|
857
|
+
>>> predictor_example_with_callback = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
|
858
|
+
"""
|
859
|
+
super().__init__(cfg, overrides, _callbacks)
|
860
|
+
self.inference_state = {}
|
861
|
+
self.non_overlap_masks = True
|
862
|
+
self.clear_non_cond_mem_around_input = False
|
863
|
+
self.clear_non_cond_mem_for_multi_obj = False
|
864
|
+
self.callbacks["on_predict_start"].append(self.init_state)
|
865
|
+
|
866
|
+
def get_model(self):
|
867
|
+
"""
|
868
|
+
Retrieves and configures the model with binarization enabled.
|
869
|
+
|
870
|
+
Note:
|
871
|
+
This method overrides the base class implementation to set the binarize flag to True.
|
872
|
+
"""
|
873
|
+
model = super().get_model()
|
874
|
+
model.set_binarize(True)
|
875
|
+
return model
|
876
|
+
|
877
|
+
def inference(self, im, bboxes=None, points=None, labels=None, masks=None):
|
878
|
+
"""
|
879
|
+
Perform image segmentation inference based on the given input cues, using the currently loaded image. This
|
880
|
+
method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
|
881
|
+
mask decoder for real-time and promptable segmentation tasks.
|
882
|
+
|
883
|
+
Args:
|
884
|
+
im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
|
885
|
+
bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
|
886
|
+
points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixels.
|
887
|
+
labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
|
888
|
+
masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
|
889
|
+
|
890
|
+
Returns:
|
891
|
+
(np.ndarray): The output masks in shape CxHxW, where C is the number of generated masks.
|
892
|
+
(np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
|
893
|
+
"""
|
894
|
+
# Override prompts if any stored in self.prompts
|
895
|
+
bboxes = self.prompts.pop("bboxes", bboxes)
|
896
|
+
points = self.prompts.pop("points", points)
|
897
|
+
masks = self.prompts.pop("masks", masks)
|
898
|
+
|
899
|
+
frame = self.dataset.frame
|
900
|
+
self.inference_state["im"] = im
|
901
|
+
output_dict = self.inference_state["output_dict"]
|
902
|
+
if len(output_dict["cond_frame_outputs"]) == 0: # initialize prompts
|
903
|
+
points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
|
904
|
+
if points is not None:
|
905
|
+
for i in range(len(points)):
|
906
|
+
self.add_new_prompts(obj_id=i, points=points[[i]], labels=labels[[i]], frame_idx=frame)
|
907
|
+
elif masks is not None:
|
908
|
+
for i in range(len(masks)):
|
909
|
+
self.add_new_prompts(obj_id=i, masks=masks[[i]], frame_idx=frame)
|
910
|
+
self.propagate_in_video_preflight()
|
911
|
+
|
912
|
+
consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
|
913
|
+
batch_size = len(self.inference_state["obj_idx_to_id"])
|
914
|
+
if len(output_dict["cond_frame_outputs"]) == 0:
|
915
|
+
raise RuntimeError("No points are provided; please add points first")
|
916
|
+
|
917
|
+
if frame in consolidated_frame_inds["cond_frame_outputs"]:
|
918
|
+
storage_key = "cond_frame_outputs"
|
919
|
+
current_out = output_dict[storage_key][frame]
|
920
|
+
if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
|
921
|
+
# clear non-conditioning memory of the surrounding frames
|
922
|
+
self._clear_non_cond_mem_around_input(frame)
|
923
|
+
elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
|
924
|
+
storage_key = "non_cond_frame_outputs"
|
925
|
+
current_out = output_dict[storage_key][frame]
|
926
|
+
else:
|
927
|
+
storage_key = "non_cond_frame_outputs"
|
928
|
+
current_out = self._run_single_frame_inference(
|
929
|
+
output_dict=output_dict,
|
930
|
+
frame_idx=frame,
|
931
|
+
batch_size=batch_size,
|
932
|
+
is_init_cond_frame=False,
|
933
|
+
point_inputs=None,
|
934
|
+
mask_inputs=None,
|
935
|
+
reverse=False,
|
936
|
+
run_mem_encoder=True,
|
937
|
+
)
|
938
|
+
output_dict[storage_key][frame] = current_out
|
939
|
+
# Create slices of per-object outputs for subsequent interaction with each
|
940
|
+
# individual object after tracking.
|
941
|
+
self._add_output_per_object(frame, current_out, storage_key)
|
942
|
+
self.inference_state["frames_already_tracked"].append(frame)
|
943
|
+
pred_masks = current_out["pred_masks"].flatten(0, 1)
|
944
|
+
pred_masks = pred_masks[(pred_masks > self.model.mask_threshold).sum((1, 2)) > 0] # filter blank masks
|
945
|
+
|
946
|
+
return pred_masks, torch.ones(len(pred_masks), dtype=pred_masks.dtype, device=pred_masks.device)
|
947
|
+
|
948
|
+
def postprocess(self, preds, img, orig_imgs):
|
949
|
+
"""
|
950
|
+
Post-processes the predictions to apply non-overlapping constraints if required.
|
951
|
+
|
952
|
+
This method extends the post-processing functionality by applying non-overlapping constraints
|
953
|
+
to the predicted masks if the `non_overlap_masks` flag is set to True. This ensures that
|
954
|
+
the masks do not overlap, which can be useful for certain applications.
|
955
|
+
|
956
|
+
Args:
|
957
|
+
preds (Tuple[torch.Tensor]): The predictions from the model.
|
958
|
+
img (torch.Tensor): The processed image tensor.
|
959
|
+
orig_imgs (List[np.ndarray]): The original images before processing.
|
960
|
+
|
961
|
+
Returns:
|
962
|
+
results (list): The post-processed predictions.
|
963
|
+
|
964
|
+
Note:
|
965
|
+
If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
|
966
|
+
"""
|
967
|
+
results = super().postprocess(preds, img, orig_imgs)
|
968
|
+
if self.non_overlap_masks:
|
969
|
+
for result in results:
|
970
|
+
if result.masks is None or len(result.masks) == 0:
|
971
|
+
continue
|
972
|
+
result.masks.data = self.model._apply_non_overlapping_constraints(result.masks.data.unsqueeze(0))[0]
|
973
|
+
return results
|
974
|
+
|
975
|
+
@smart_inference_mode()
|
976
|
+
def add_new_prompts(
|
977
|
+
self,
|
978
|
+
obj_id,
|
979
|
+
points=None,
|
980
|
+
labels=None,
|
981
|
+
masks=None,
|
982
|
+
frame_idx=0,
|
983
|
+
):
|
984
|
+
"""
|
985
|
+
Adds new points or masks to a specific frame for a given object ID.
|
986
|
+
|
987
|
+
This method updates the inference state with new prompts (points or masks) for a specified
|
988
|
+
object and frame index. It ensures that the prompts are either points or masks, but not both,
|
989
|
+
and updates the internal state accordingly. It also handles the generation of new segmentations
|
990
|
+
based on the provided prompts and the existing state.
|
991
|
+
|
992
|
+
Args:
|
993
|
+
obj_id (int): The ID of the object to which the prompts are associated.
|
994
|
+
points (torch.Tensor, Optional): The coordinates of the points of interest. Defaults to None.
|
995
|
+
labels (torch.Tensor, Optional): The labels corresponding to the points. Defaults to None.
|
996
|
+
masks (torch.Tensor, optional): Binary masks for the object. Defaults to None.
|
997
|
+
frame_idx (int, optional): The index of the frame to which the prompts are applied. Defaults to 0.
|
998
|
+
|
999
|
+
Returns:
|
1000
|
+
(tuple): A tuple containing the flattened predicted masks and a tensor of ones indicating the number of objects.
|
1001
|
+
|
1002
|
+
Raises:
|
1003
|
+
AssertionError: If both `masks` and `points` are provided, or neither is provided.
|
1004
|
+
|
1005
|
+
Note:
|
1006
|
+
- Only one type of prompt (either points or masks) can be added per call.
|
1007
|
+
- If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
|
1008
|
+
- The method handles the consolidation of outputs and resizing of masks to the original video resolution.
|
1009
|
+
"""
|
1010
|
+
assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
|
1011
|
+
obj_idx = self._obj_id_to_idx(obj_id)
|
1012
|
+
|
1013
|
+
point_inputs = None
|
1014
|
+
pop_key = "point_inputs_per_obj"
|
1015
|
+
if points is not None:
|
1016
|
+
point_inputs = {"point_coords": points, "point_labels": labels}
|
1017
|
+
self.inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
|
1018
|
+
pop_key = "mask_inputs_per_obj"
|
1019
|
+
self.inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
|
1020
|
+
self.inference_state[pop_key][obj_idx].pop(frame_idx, None)
|
1021
|
+
# If this frame hasn't been tracked before, we treat it as an initial conditioning
|
1022
|
+
# frame, meaning that the inputs points are to generate segments on this frame without
|
1023
|
+
# using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
|
1024
|
+
# the input points will be used to correct the already tracked masks.
|
1025
|
+
is_init_cond_frame = frame_idx not in self.inference_state["frames_already_tracked"]
|
1026
|
+
obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
|
1027
|
+
obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
|
1028
|
+
# Add a frame to conditioning output if it's an initial conditioning frame or
|
1029
|
+
# if the model sees all frames receiving clicks/mask as conditioning frames.
|
1030
|
+
is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
|
1031
|
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
1032
|
+
|
1033
|
+
# Get any previously predicted mask logits on this object and feed it along with
|
1034
|
+
# the new clicks into the SAM mask decoder.
|
1035
|
+
prev_sam_mask_logits = None
|
1036
|
+
# lookup temporary output dict first, which contains the most recent output
|
1037
|
+
# (if not found, then lookup conditioning and non-conditioning frame output)
|
1038
|
+
if point_inputs is not None:
|
1039
|
+
prev_out = (
|
1040
|
+
obj_temp_output_dict[storage_key].get(frame_idx)
|
1041
|
+
or obj_output_dict["cond_frame_outputs"].get(frame_idx)
|
1042
|
+
or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
|
1043
|
+
)
|
1044
|
+
|
1045
|
+
if prev_out is not None and prev_out.get("pred_masks") is not None:
|
1046
|
+
prev_sam_mask_logits = prev_out["pred_masks"].to(device=self.device, non_blocking=True)
|
1047
|
+
# Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
|
1048
|
+
prev_sam_mask_logits.clamp_(-32.0, 32.0)
|
1049
|
+
current_out = self._run_single_frame_inference(
|
1050
|
+
output_dict=obj_output_dict, # run on the slice of a single object
|
1051
|
+
frame_idx=frame_idx,
|
1052
|
+
batch_size=1, # run on the slice of a single object
|
1053
|
+
is_init_cond_frame=is_init_cond_frame,
|
1054
|
+
point_inputs=point_inputs,
|
1055
|
+
mask_inputs=masks,
|
1056
|
+
reverse=False,
|
1057
|
+
# Skip the memory encoder when adding clicks or mask. We execute the memory encoder
|
1058
|
+
# at the beginning of `propagate_in_video` (after user finalize their clicks). This
|
1059
|
+
# allows us to enforce non-overlapping constraints on all objects before encoding
|
1060
|
+
# them into memory.
|
1061
|
+
run_mem_encoder=False,
|
1062
|
+
prev_sam_mask_logits=prev_sam_mask_logits,
|
1063
|
+
)
|
1064
|
+
# Add the output to the output dict (to be used as future memory)
|
1065
|
+
obj_temp_output_dict[storage_key][frame_idx] = current_out
|
1066
|
+
|
1067
|
+
# Resize the output mask to the original video resolution
|
1068
|
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
1069
|
+
frame_idx,
|
1070
|
+
is_cond=is_cond,
|
1071
|
+
run_mem_encoder=False,
|
1072
|
+
)
|
1073
|
+
pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
|
1074
|
+
return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
|
1075
|
+
|
1076
|
+
@smart_inference_mode()
|
1077
|
+
def propagate_in_video_preflight(self):
|
1078
|
+
"""
|
1079
|
+
Prepare inference_state and consolidate temporary outputs before tracking.
|
1080
|
+
|
1081
|
+
This method marks the start of tracking, disallowing the addition of new objects until the session is reset.
|
1082
|
+
It consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`.
|
1083
|
+
Additionally, it clears non-conditioning memory around input frames and ensures that the state is consistent
|
1084
|
+
with the provided inputs.
|
1085
|
+
"""
|
1086
|
+
# Tracking has started and we don't allow adding new objects until session is reset.
|
1087
|
+
self.inference_state["tracking_has_started"] = True
|
1088
|
+
batch_size = len(self.inference_state["obj_idx_to_id"])
|
1089
|
+
|
1090
|
+
# Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
|
1091
|
+
# add them into "output_dict".
|
1092
|
+
temp_output_dict_per_obj = self.inference_state["temp_output_dict_per_obj"]
|
1093
|
+
output_dict = self.inference_state["output_dict"]
|
1094
|
+
# "consolidated_frame_inds" contains indices of those frames where consolidated
|
1095
|
+
# temporary outputs have been added (either in this call or any previous calls
|
1096
|
+
# to `propagate_in_video_preflight`).
|
1097
|
+
consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
|
1098
|
+
for is_cond in {False, True}:
|
1099
|
+
# Separately consolidate conditioning and non-conditioning temp outputs
|
1100
|
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
1101
|
+
# Find all the frames that contain temporary outputs for any objects
|
1102
|
+
# (these should be the frames that have just received clicks for mask inputs
|
1103
|
+
# via `add_new_points` or `add_new_mask`)
|
1104
|
+
temp_frame_inds = set()
|
1105
|
+
for obj_temp_output_dict in temp_output_dict_per_obj.values():
|
1106
|
+
temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
|
1107
|
+
consolidated_frame_inds[storage_key].update(temp_frame_inds)
|
1108
|
+
# consolidate the temporary output across all objects on this frame
|
1109
|
+
for frame_idx in temp_frame_inds:
|
1110
|
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
1111
|
+
frame_idx, is_cond=is_cond, run_mem_encoder=True
|
1112
|
+
)
|
1113
|
+
# merge them into "output_dict" and also create per-object slices
|
1114
|
+
output_dict[storage_key][frame_idx] = consolidated_out
|
1115
|
+
self._add_output_per_object(frame_idx, consolidated_out, storage_key)
|
1116
|
+
if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
|
1117
|
+
# clear non-conditioning memory of the surrounding frames
|
1118
|
+
self._clear_non_cond_mem_around_input(frame_idx)
|
1119
|
+
|
1120
|
+
# clear temporary outputs in `temp_output_dict_per_obj`
|
1121
|
+
for obj_temp_output_dict in temp_output_dict_per_obj.values():
|
1122
|
+
obj_temp_output_dict[storage_key].clear()
|
1123
|
+
|
1124
|
+
# edge case: if an output is added to "cond_frame_outputs", we remove any prior
|
1125
|
+
# output on the same frame in "non_cond_frame_outputs"
|
1126
|
+
for frame_idx in output_dict["cond_frame_outputs"]:
|
1127
|
+
output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
|
1128
|
+
for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
|
1129
|
+
for frame_idx in obj_output_dict["cond_frame_outputs"]:
|
1130
|
+
obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
|
1131
|
+
for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
|
1132
|
+
assert frame_idx in output_dict["cond_frame_outputs"]
|
1133
|
+
consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
|
1134
|
+
|
1135
|
+
# Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
|
1136
|
+
# with either points or mask inputs (which should be true under a correct workflow).
|
1137
|
+
all_consolidated_frame_inds = (
|
1138
|
+
consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
|
1139
|
+
)
|
1140
|
+
input_frames_inds = set()
|
1141
|
+
for point_inputs_per_frame in self.inference_state["point_inputs_per_obj"].values():
|
1142
|
+
input_frames_inds.update(point_inputs_per_frame.keys())
|
1143
|
+
for mask_inputs_per_frame in self.inference_state["mask_inputs_per_obj"].values():
|
1144
|
+
input_frames_inds.update(mask_inputs_per_frame.keys())
|
1145
|
+
assert all_consolidated_frame_inds == input_frames_inds
|
1146
|
+
|
1147
|
+
@staticmethod
|
1148
|
+
def init_state(predictor):
|
1149
|
+
"""
|
1150
|
+
Initialize an inference state for the predictor.
|
1151
|
+
|
1152
|
+
This function sets up the initial state required for performing inference on video data.
|
1153
|
+
It includes initializing various dictionaries and ordered dictionaries that will store
|
1154
|
+
inputs, outputs, and other metadata relevant to the tracking process.
|
1155
|
+
|
1156
|
+
Args:
|
1157
|
+
predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
|
1158
|
+
"""
|
1159
|
+
if len(predictor.inference_state) > 0: # means initialized
|
1160
|
+
return
|
1161
|
+
assert predictor.dataset is not None
|
1162
|
+
assert predictor.dataset.mode == "video"
|
1163
|
+
|
1164
|
+
inference_state = {
|
1165
|
+
"num_frames": predictor.dataset.frames,
|
1166
|
+
"point_inputs_per_obj": {}, # inputs points on each frame
|
1167
|
+
"mask_inputs_per_obj": {}, # inputs mask on each frame
|
1168
|
+
"constants": {}, # values that don't change across frames (so we only need to hold one copy of them)
|
1169
|
+
# mapping between client-side object id and model-side object index
|
1170
|
+
"obj_id_to_idx": OrderedDict(),
|
1171
|
+
"obj_idx_to_id": OrderedDict(),
|
1172
|
+
"obj_ids": [],
|
1173
|
+
# A storage to hold the model's tracking results and states on each frame
|
1174
|
+
"output_dict": {
|
1175
|
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1176
|
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1177
|
+
},
|
1178
|
+
# Slice (view) of each object tracking results, sharing the same memory with "output_dict"
|
1179
|
+
"output_dict_per_obj": {},
|
1180
|
+
# A temporary storage to hold new outputs when user interact with a frame
|
1181
|
+
# to add clicks or mask (it's merged into "output_dict" before propagation starts)
|
1182
|
+
"temp_output_dict_per_obj": {},
|
1183
|
+
# Frames that already holds consolidated outputs from click or mask inputs
|
1184
|
+
# (we directly use their consolidated outputs during tracking)
|
1185
|
+
"consolidated_frame_inds": {
|
1186
|
+
"cond_frame_outputs": set(), # set containing frame indices
|
1187
|
+
"non_cond_frame_outputs": set(), # set containing frame indices
|
1188
|
+
},
|
1189
|
+
# metadata for each tracking frame (e.g. which direction it's tracked)
|
1190
|
+
"tracking_has_started": False,
|
1191
|
+
"frames_already_tracked": [],
|
1192
|
+
}
|
1193
|
+
predictor.inference_state = inference_state
|
1194
|
+
|
1195
|
+
def get_im_features(self, im, batch=1):
|
1196
|
+
"""
|
1197
|
+
Extracts and processes image features using SAM2's image encoder for subsequent segmentation tasks.
|
1198
|
+
|
1199
|
+
Args:
|
1200
|
+
im (torch.Tensor): The input image tensor.
|
1201
|
+
batch (int, optional): The batch size for expanding features if there are multiple prompts. Defaults to 1.
|
1202
|
+
|
1203
|
+
Returns:
|
1204
|
+
vis_feats (torch.Tensor): The visual features extracted from the image.
|
1205
|
+
vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
|
1206
|
+
feat_sizes (List(Tuple[int])): A list containing the sizes of the extracted features.
|
1207
|
+
|
1208
|
+
Note:
|
1209
|
+
- If `batch` is greater than 1, the features are expanded to fit the batch size.
|
1210
|
+
- The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
|
1211
|
+
"""
|
1212
|
+
backbone_out = self.model.forward_image(im)
|
1213
|
+
if batch > 1: # expand features if there's more than one prompt
|
1214
|
+
for i, feat in enumerate(backbone_out["backbone_fpn"]):
|
1215
|
+
backbone_out["backbone_fpn"][i] = feat.expand(batch, -1, -1, -1)
|
1216
|
+
for i, pos in enumerate(backbone_out["vision_pos_enc"]):
|
1217
|
+
pos = pos.expand(batch, -1, -1, -1)
|
1218
|
+
backbone_out["vision_pos_enc"][i] = pos
|
1219
|
+
_, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out)
|
1220
|
+
return vis_feats, vis_pos_embed, feat_sizes
|
1221
|
+
|
1222
|
+
def _obj_id_to_idx(self, obj_id):
|
1223
|
+
"""
|
1224
|
+
Map client-side object id to model-side object index.
|
1225
|
+
|
1226
|
+
Args:
|
1227
|
+
obj_id (int): The unique identifier of the object provided by the client side.
|
1228
|
+
|
1229
|
+
Returns:
|
1230
|
+
obj_idx (int): The index of the object on the model side.
|
1231
|
+
|
1232
|
+
Raises:
|
1233
|
+
RuntimeError: If an attempt is made to add a new object after tracking has started.
|
1234
|
+
|
1235
|
+
Note:
|
1236
|
+
- The method updates or retrieves mappings between object IDs and indices stored in
|
1237
|
+
`inference_state`.
|
1238
|
+
- It ensures that new objects can only be added before tracking commences.
|
1239
|
+
- It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
|
1240
|
+
- Additional data structures are initialized for the new object to store inputs and outputs.
|
1241
|
+
"""
|
1242
|
+
obj_idx = self.inference_state["obj_id_to_idx"].get(obj_id, None)
|
1243
|
+
if obj_idx is not None:
|
1244
|
+
return obj_idx
|
1245
|
+
|
1246
|
+
# This is a new object id not sent to the server before. We only allow adding
|
1247
|
+
# new objects *before* the tracking starts.
|
1248
|
+
allow_new_object = not self.inference_state["tracking_has_started"]
|
1249
|
+
if allow_new_object:
|
1250
|
+
# get the next object slot
|
1251
|
+
obj_idx = len(self.inference_state["obj_id_to_idx"])
|
1252
|
+
self.inference_state["obj_id_to_idx"][obj_id] = obj_idx
|
1253
|
+
self.inference_state["obj_idx_to_id"][obj_idx] = obj_id
|
1254
|
+
self.inference_state["obj_ids"] = list(self.inference_state["obj_id_to_idx"])
|
1255
|
+
# set up input and output structures for this object
|
1256
|
+
self.inference_state["point_inputs_per_obj"][obj_idx] = {}
|
1257
|
+
self.inference_state["mask_inputs_per_obj"][obj_idx] = {}
|
1258
|
+
self.inference_state["output_dict_per_obj"][obj_idx] = {
|
1259
|
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1260
|
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1261
|
+
}
|
1262
|
+
self.inference_state["temp_output_dict_per_obj"][obj_idx] = {
|
1263
|
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1264
|
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
1265
|
+
}
|
1266
|
+
return obj_idx
|
1267
|
+
else:
|
1268
|
+
raise RuntimeError(
|
1269
|
+
f"Cannot add new object id {obj_id} after tracking starts. "
|
1270
|
+
f"All existing object ids: {self.inference_state['obj_ids']}. "
|
1271
|
+
f"Please call 'reset_state' to restart from scratch."
|
1272
|
+
)
|
1273
|
+
|
1274
|
+
def _run_single_frame_inference(
|
1275
|
+
self,
|
1276
|
+
output_dict,
|
1277
|
+
frame_idx,
|
1278
|
+
batch_size,
|
1279
|
+
is_init_cond_frame,
|
1280
|
+
point_inputs,
|
1281
|
+
mask_inputs,
|
1282
|
+
reverse,
|
1283
|
+
run_mem_encoder,
|
1284
|
+
prev_sam_mask_logits=None,
|
1285
|
+
):
|
1286
|
+
"""
|
1287
|
+
Run tracking on a single frame based on current inputs and previous memory.
|
1288
|
+
|
1289
|
+
Args:
|
1290
|
+
output_dict (Dict): The dictionary containing the output states of the tracking process.
|
1291
|
+
frame_idx (int): The index of the current frame.
|
1292
|
+
batch_size (int): The batch size for processing the frame.
|
1293
|
+
is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame.
|
1294
|
+
point_inputs (Dict, Optional): Input points and their labels. Defaults to None.
|
1295
|
+
mask_inputs (torch.Tensor, Optional): Input binary masks. Defaults to None.
|
1296
|
+
reverse (bool): Indicates if the tracking should be performed in reverse order.
|
1297
|
+
run_mem_encoder (bool): Indicates if the memory encoder should be executed.
|
1298
|
+
prev_sam_mask_logits (torch.Tensor, Optional): Previous mask logits for the current object. Defaults to None.
|
1299
|
+
|
1300
|
+
Returns:
|
1301
|
+
current_out (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
|
1302
|
+
|
1303
|
+
Raises:
|
1304
|
+
AssertionError: If both `point_inputs` and `mask_inputs` are provided, or neither is provided.
|
1305
|
+
|
1306
|
+
Note:
|
1307
|
+
- The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
|
1308
|
+
- The method retrieves image features using the `get_im_features` method.
|
1309
|
+
- The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
|
1310
|
+
- The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
|
1311
|
+
"""
|
1312
|
+
# Retrieve correct image features
|
1313
|
+
current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
|
1314
|
+
self.inference_state["im"], batch_size
|
1315
|
+
)
|
1316
|
+
|
1317
|
+
# point and mask should not appear as input simultaneously on the same frame
|
1318
|
+
assert point_inputs is None or mask_inputs is None
|
1319
|
+
current_out = self.model.track_step(
|
1320
|
+
frame_idx=frame_idx,
|
1321
|
+
is_init_cond_frame=is_init_cond_frame,
|
1322
|
+
current_vision_feats=current_vision_feats,
|
1323
|
+
current_vision_pos_embeds=current_vision_pos_embeds,
|
1324
|
+
feat_sizes=feat_sizes,
|
1325
|
+
point_inputs=point_inputs,
|
1326
|
+
mask_inputs=mask_inputs,
|
1327
|
+
output_dict=output_dict,
|
1328
|
+
num_frames=self.inference_state["num_frames"],
|
1329
|
+
track_in_reverse=reverse,
|
1330
|
+
run_mem_encoder=run_mem_encoder,
|
1331
|
+
prev_sam_mask_logits=prev_sam_mask_logits,
|
1332
|
+
)
|
1333
|
+
|
1334
|
+
maskmem_features = current_out["maskmem_features"]
|
1335
|
+
if maskmem_features is not None:
|
1336
|
+
current_out["maskmem_features"] = maskmem_features.to(
|
1337
|
+
dtype=torch.float16, device=self.device, non_blocking=True
|
1338
|
+
)
|
1339
|
+
# NOTE: Do not support the `fill_holes_in_mask_scores` function since it needs cuda extensions
|
1340
|
+
# potentially fill holes in the predicted masks
|
1341
|
+
# if self.fill_hole_area > 0:
|
1342
|
+
# pred_masks = current_out["pred_masks"].to(self.device, non_blocking=True)
|
1343
|
+
# pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
|
1344
|
+
|
1345
|
+
# "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
|
1346
|
+
current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"])
|
1347
|
+
return current_out
|
1348
|
+
|
1349
|
+
def _get_maskmem_pos_enc(self, out_maskmem_pos_enc):
|
1350
|
+
"""
|
1351
|
+
Caches and manages the positional encoding for mask memory across frames and objects.
|
1352
|
+
|
1353
|
+
This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for
|
1354
|
+
mask memory, which is constant across frames and objects, thus reducing the amount of
|
1355
|
+
redundant information stored during an inference session. It checks if the positional
|
1356
|
+
encoding has already been cached; if not, it caches a slice of the provided encoding.
|
1357
|
+
If the batch size is greater than one, it expands the cached positional encoding to match
|
1358
|
+
the current batch size.
|
1359
|
+
|
1360
|
+
Args:
|
1361
|
+
out_maskmem_pos_enc (List[torch.Tensor] or None): The positional encoding for mask memory.
|
1362
|
+
Should be a list of tensors or None.
|
1363
|
+
|
1364
|
+
Returns:
|
1365
|
+
out_maskmem_pos_enc (List[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
|
1366
|
+
|
1367
|
+
Note:
|
1368
|
+
- The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
|
1369
|
+
- Only a single object's slice is cached since the encoding is the same across objects.
|
1370
|
+
- The method checks if the positional encoding has already been cached in the session's constants.
|
1371
|
+
- If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
|
1372
|
+
"""
|
1373
|
+
model_constants = self.inference_state["constants"]
|
1374
|
+
# "out_maskmem_pos_enc" should be either a list of tensors or None
|
1375
|
+
if out_maskmem_pos_enc is not None:
|
1376
|
+
if "maskmem_pos_enc" not in model_constants:
|
1377
|
+
assert isinstance(out_maskmem_pos_enc, list)
|
1378
|
+
# only take the slice for one object, since it's same across objects
|
1379
|
+
maskmem_pos_enc = [x[:1].clone() for x in out_maskmem_pos_enc]
|
1380
|
+
model_constants["maskmem_pos_enc"] = maskmem_pos_enc
|
1381
|
+
else:
|
1382
|
+
maskmem_pos_enc = model_constants["maskmem_pos_enc"]
|
1383
|
+
# expand the cached maskmem_pos_enc to the actual batch size
|
1384
|
+
batch_size = out_maskmem_pos_enc[0].size(0)
|
1385
|
+
if batch_size > 1:
|
1386
|
+
out_maskmem_pos_enc = [x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc]
|
1387
|
+
return out_maskmem_pos_enc
|
1388
|
+
|
1389
|
+
def _consolidate_temp_output_across_obj(
|
1390
|
+
self,
|
1391
|
+
frame_idx,
|
1392
|
+
is_cond=False,
|
1393
|
+
run_mem_encoder=False,
|
1394
|
+
):
|
1395
|
+
"""
|
1396
|
+
Consolidates per-object temporary outputs into a single output for all objects.
|
1397
|
+
|
1398
|
+
This method combines the temporary outputs for each object on a given frame into a unified
|
1399
|
+
output. It fills in any missing objects either from the main output dictionary or leaves
|
1400
|
+
placeholders if they do not exist in the main output. Optionally, it can re-run the memory
|
1401
|
+
encoder after applying non-overlapping constraints to the object scores.
|
1402
|
+
|
1403
|
+
Args:
|
1404
|
+
frame_idx (int): The index of the frame for which to consolidate outputs.
|
1405
|
+
is_cond (bool, Optional): Indicates if the frame is considered a conditioning frame.
|
1406
|
+
Defaults to False.
|
1407
|
+
run_mem_encoder (bool, Optional): Specifies whether to run the memory encoder after
|
1408
|
+
consolidating the outputs. Defaults to False.
|
1409
|
+
|
1410
|
+
Returns:
|
1411
|
+
consolidated_out (dict): A consolidated output dictionary containing the combined results for all objects.
|
1412
|
+
|
1413
|
+
Note:
|
1414
|
+
- The method initializes the consolidated output with placeholder values for missing objects.
|
1415
|
+
- It searches for outputs in both the temporary and main output dictionaries.
|
1416
|
+
- If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
|
1417
|
+
- The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
|
1418
|
+
"""
|
1419
|
+
batch_size = len(self.inference_state["obj_idx_to_id"])
|
1420
|
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
1421
|
+
|
1422
|
+
# Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
|
1423
|
+
# will be added when rerunning the memory encoder after applying non-overlapping
|
1424
|
+
# constraints to object scores. Its "pred_masks" are prefilled with a large
|
1425
|
+
# negative value (NO_OBJ_SCORE) to represent missing objects.
|
1426
|
+
consolidated_out = {
|
1427
|
+
"maskmem_features": None,
|
1428
|
+
"maskmem_pos_enc": None,
|
1429
|
+
"pred_masks": torch.full(
|
1430
|
+
size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
|
1431
|
+
fill_value=-1024.0,
|
1432
|
+
dtype=torch.float32,
|
1433
|
+
device=self.device,
|
1434
|
+
),
|
1435
|
+
"obj_ptr": torch.full(
|
1436
|
+
size=(batch_size, self.model.hidden_dim),
|
1437
|
+
fill_value=-1024.0,
|
1438
|
+
dtype=torch.float32,
|
1439
|
+
device=self.device,
|
1440
|
+
),
|
1441
|
+
"object_score_logits": torch.full(
|
1442
|
+
size=(batch_size, 1),
|
1443
|
+
# default to 10.0 for object_score_logits, i.e. assuming the object is
|
1444
|
+
# present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
|
1445
|
+
fill_value=10.0,
|
1446
|
+
dtype=torch.float32,
|
1447
|
+
device=self.device,
|
1448
|
+
),
|
1449
|
+
}
|
1450
|
+
for obj_idx in range(batch_size):
|
1451
|
+
obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
|
1452
|
+
obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
|
1453
|
+
out = (
|
1454
|
+
obj_temp_output_dict[storage_key].get(frame_idx)
|
1455
|
+
# If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
|
1456
|
+
# we fall back and look up its previous output in "output_dict_per_obj".
|
1457
|
+
# We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
|
1458
|
+
# "output_dict_per_obj" to find a previous output for this object.
|
1459
|
+
or obj_output_dict["cond_frame_outputs"].get(frame_idx)
|
1460
|
+
or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
|
1461
|
+
)
|
1462
|
+
# If the object doesn't appear in "output_dict_per_obj" either, we skip it
|
1463
|
+
# and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
|
1464
|
+
# placeholder above) and set its object pointer to be a dummy pointer.
|
1465
|
+
if out is None:
|
1466
|
+
# Fill in dummy object pointers for those objects without any inputs or
|
1467
|
+
# tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
|
1468
|
+
# i.e. when we need to build the memory for tracking).
|
1469
|
+
if run_mem_encoder:
|
1470
|
+
# fill object pointer with a dummy pointer (based on an empty mask)
|
1471
|
+
consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = self._get_empty_mask_ptr(frame_idx)
|
1472
|
+
continue
|
1473
|
+
# Add the temporary object output mask to consolidated output mask
|
1474
|
+
consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = out["pred_masks"]
|
1475
|
+
consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
|
1476
|
+
|
1477
|
+
# Optionally, apply non-overlapping constraints on the consolidated scores and rerun the memory encoder
|
1478
|
+
if run_mem_encoder:
|
1479
|
+
high_res_masks = F.interpolate(
|
1480
|
+
consolidated_out["pred_masks"],
|
1481
|
+
size=self.imgsz,
|
1482
|
+
mode="bilinear",
|
1483
|
+
align_corners=False,
|
1484
|
+
)
|
1485
|
+
if self.model.non_overlap_masks_for_mem_enc:
|
1486
|
+
high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks)
|
1487
|
+
consolidated_out["maskmem_features"], consolidated_out["maskmem_pos_enc"] = self._run_memory_encoder(
|
1488
|
+
batch_size=batch_size,
|
1489
|
+
high_res_masks=high_res_masks,
|
1490
|
+
is_mask_from_pts=True, # these frames are what the user interacted with
|
1491
|
+
object_score_logits=consolidated_out["object_score_logits"],
|
1492
|
+
)
|
1493
|
+
|
1494
|
+
return consolidated_out
|
1495
|
+
|
1496
|
+
def _get_empty_mask_ptr(self, frame_idx):
|
1497
|
+
"""
|
1498
|
+
Get a dummy object pointer based on an empty mask on the current frame.
|
1499
|
+
|
1500
|
+
Args:
|
1501
|
+
frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
|
1502
|
+
|
1503
|
+
Returns:
|
1504
|
+
(torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
|
1505
|
+
"""
|
1506
|
+
# Retrieve correct image features
|
1507
|
+
current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(self.inference_state["im"])
|
1508
|
+
|
1509
|
+
# Feed the empty mask and image feature above to get a dummy object pointer
|
1510
|
+
current_out = self.model.track_step(
|
1511
|
+
frame_idx=frame_idx,
|
1512
|
+
is_init_cond_frame=True,
|
1513
|
+
current_vision_feats=current_vision_feats,
|
1514
|
+
current_vision_pos_embeds=current_vision_pos_embeds,
|
1515
|
+
feat_sizes=feat_sizes,
|
1516
|
+
point_inputs=None,
|
1517
|
+
# A dummy (empty) mask with a single object
|
1518
|
+
mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=torch.float32, device=self.device),
|
1519
|
+
output_dict={},
|
1520
|
+
num_frames=self.inference_state["num_frames"],
|
1521
|
+
track_in_reverse=False,
|
1522
|
+
run_mem_encoder=False,
|
1523
|
+
prev_sam_mask_logits=None,
|
1524
|
+
)
|
1525
|
+
return current_out["obj_ptr"]
|
1526
|
+
|
1527
|
+
def _run_memory_encoder(self, batch_size, high_res_masks, object_score_logits, is_mask_from_pts):
|
1528
|
+
"""
|
1529
|
+
Run the memory encoder on masks.
|
1530
|
+
|
1531
|
+
This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
|
1532
|
+
memory also needs to be computed again with the memory encoder.
|
1533
|
+
|
1534
|
+
Args:
|
1535
|
+
batch_size (int): The batch size for processing the frame.
|
1536
|
+
high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
|
1537
|
+
object_score_logits (torch.Tensor): Logits representing the object scores.
|
1538
|
+
is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
|
1539
|
+
|
1540
|
+
Returns:
|
1541
|
+
(tuple[torch.Tensor, torch.Tensor]): A tuple containing the encoded mask features and positional encoding.
|
1542
|
+
"""
|
1543
|
+
# Retrieve correct image features
|
1544
|
+
current_vision_feats, _, feat_sizes = self.get_im_features(self.inference_state["im"], batch_size)
|
1545
|
+
maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
|
1546
|
+
current_vision_feats=current_vision_feats,
|
1547
|
+
feat_sizes=feat_sizes,
|
1548
|
+
pred_masks_high_res=high_res_masks,
|
1549
|
+
is_mask_from_pts=is_mask_from_pts,
|
1550
|
+
object_score_logits=object_score_logits,
|
1551
|
+
)
|
1552
|
+
|
1553
|
+
# "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
|
1554
|
+
maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc)
|
1555
|
+
return maskmem_features.to(dtype=torch.float16, device=self.device, non_blocking=True), maskmem_pos_enc
|
1556
|
+
|
1557
|
+
def _add_output_per_object(self, frame_idx, current_out, storage_key):
|
1558
|
+
"""
|
1559
|
+
Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
|
1560
|
+
|
1561
|
+
The resulting slices share the same tensor storage.
|
1562
|
+
|
1563
|
+
Args:
|
1564
|
+
frame_idx (int): The index of the current frame.
|
1565
|
+
current_out (Dict): The current output dictionary containing multi-object outputs.
|
1566
|
+
storage_key (str): The key used to store the output in the per-object output dictionary.
|
1567
|
+
"""
|
1568
|
+
maskmem_features = current_out["maskmem_features"]
|
1569
|
+
assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
|
1570
|
+
|
1571
|
+
maskmem_pos_enc = current_out["maskmem_pos_enc"]
|
1572
|
+
assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
|
1573
|
+
|
1574
|
+
for obj_idx, obj_output_dict in self.inference_state["output_dict_per_obj"].items():
|
1575
|
+
obj_slice = slice(obj_idx, obj_idx + 1)
|
1576
|
+
obj_out = {
|
1577
|
+
"maskmem_features": None,
|
1578
|
+
"maskmem_pos_enc": None,
|
1579
|
+
"pred_masks": current_out["pred_masks"][obj_slice],
|
1580
|
+
"obj_ptr": current_out["obj_ptr"][obj_slice],
|
1581
|
+
}
|
1582
|
+
if maskmem_features is not None:
|
1583
|
+
obj_out["maskmem_features"] = maskmem_features[obj_slice]
|
1584
|
+
if maskmem_pos_enc is not None:
|
1585
|
+
obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
|
1586
|
+
obj_output_dict[storage_key][frame_idx] = obj_out
|
1587
|
+
|
1588
|
+
def _clear_non_cond_mem_around_input(self, frame_idx):
|
1589
|
+
"""
|
1590
|
+
Remove the non-conditioning memory around the input frame.
|
1591
|
+
|
1592
|
+
When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated
|
1593
|
+
object appearance information and could confuse the model. This method clears those non-conditioning memories
|
1594
|
+
surrounding the interacted frame to avoid giving the model both old and new information about the object.
|
1595
|
+
|
1596
|
+
Args:
|
1597
|
+
frame_idx (int): The index of the current frame where user interaction occurred.
|
1598
|
+
"""
|
1599
|
+
r = self.model.memory_temporal_stride_for_eval
|
1600
|
+
frame_idx_begin = frame_idx - r * self.model.num_maskmem
|
1601
|
+
frame_idx_end = frame_idx + r * self.model.num_maskmem
|
1602
|
+
for t in range(frame_idx_begin, frame_idx_end + 1):
|
1603
|
+
self.inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
|
1604
|
+
for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
|
1605
|
+
obj_output_dict["non_cond_frame_outputs"].pop(t, None)
|