segment_anything2
SegmentAnything2
¶
Bases: RoboflowCoreModel
SegmentAnything class for handling segmentation tasks.
Attributes:
Name | Type | Description |
---|---|---|
sam |
The segmentation model. |
|
predictor |
The predictor for the segmentation model. |
|
ort_session |
ONNX runtime inference session. |
|
embedding_cache |
Cache for embeddings. |
|
image_size_cache |
Cache for image sizes. |
|
embedding_cache_keys |
Keys for the embedding cache. |
Source code in inference/models/sam2/segment_anything2.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
|
__init__(*args, model_id=f'sam2/{SAM2_VERSION_ID}', low_res_logits_cache_size=SAM2_MAX_LOGITS_CACHE_SIZE, embedding_cache_size=SAM2_MAX_EMBEDDING_CACHE_SIZE, **kwargs)
¶
Initializes the SegmentAnything.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Variable length argument list. |
()
|
|
**kwargs
|
Arbitrary keyword arguments. |
{}
|
Source code in inference/models/sam2/segment_anything2.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
embed_image(image, image_id=None, **kwargs)
¶
Embeds an image and caches the result if an image_id is provided. If the image has been embedded before and cached, the cached result will be returned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Any
|
The image to be embedded. The format should be compatible with the preproc_image method. |
required |
image_id
|
Optional[str]
|
An identifier for the image. If provided, the embedding result will be cached with this ID. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
Type | Description |
---|---|
Tuple[np.ndarray, Tuple[int, int]]: A tuple where the first element is the embedding of the image and the second element is the shape (height, width) of the processed image. |
Notes
- Embeddings and image sizes are cached to improve performance on repeated requests for the same image.
- The cache has a maximum size defined by SAM2_MAX_CACHE_SIZE. When the cache exceeds this size, the oldest entries are removed.
Example
img_array = ... # some image array embed_image(img_array, image_id="sample123") (array([...]), (224, 224))
Source code in inference/models/sam2/segment_anything2.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
|
get_infer_bucket_file_list()
¶
Gets the list of files required for inference.
Returns:
Type | Description |
---|---|
List[str]
|
List[str]: List of file names. |
Source code in inference/models/sam2/segment_anything2.py
102 103 104 105 106 107 108 |
|
infer_from_request(request)
¶
Performs inference based on the request type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SamInferenceRequest
|
The inference request. |
required |
Returns:
Type | Description |
---|---|
Union[SamEmbeddingResponse, SamSegmentationResponse]: The inference response. |
Source code in inference/models/sam2/segment_anything2.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
preproc_image(image)
¶
Preprocesses an image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
InferenceRequestImage
|
The image to preprocess. |
required |
Returns:
Type | Description |
---|---|
np.array: The preprocessed image. |
Source code in inference/models/sam2/segment_anything2.py
210 211 212 213 214 215 216 217 218 219 220 |
|
segment_image(image, image_id=None, prompts=None, multimask_output=True, mask_input=None, save_logits_to_cache=False, load_logits_from_cache=False, **kwargs)
¶
Segments an image based on provided embeddings, points, masks, or cached results. If embeddings are not directly provided, the function can derive them from the input image or cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Any
|
The image to be segmented. |
required |
image_id
|
Optional[str]
|
A cached identifier for the image. Useful for accessing cached embeddings or masks. |
None
|
prompts
|
Optional[List[Sam2Prompt]]
|
List of prompts to use for segmentation. Defaults to None. |
None
|
mask_input
|
Optional[Union[ndarray, List[List[List[float]]]]]
|
Input low_res_logits for the image. |
None
|
multimask_output
|
Optional[bool]
|
(bool): Flag to decide if multiple masks proposal to be predicted (among which the most promising will be returned |
True
|
use_logits_cache
|
(bool): Flag to decide to use cached logits from prior prompting |
required | |
**kwargs
|
Additional keyword arguments. |
{}
|
Returns:
Type | Description |
---|---|
Tuple[np.ndarray, np.ndarray, np.ndarray]: Tuple of np.array, where: - first element is of size (prompt_set_size, h, w) and represent mask with the highest confidence for each prompt element - second element is of size (prompt_set_size, ) and represents ths score for most confident mask of each prompt element - third element is of size (prompt_set_size, 256, 256) and represents the low resolution logits for most confident mask of each prompt element |
Raises:
Type | Description |
---|---|
ValueError
|
If necessary inputs are missing or inconsistent. |
Notes
- Embeddings, segmentations, and low-resolution logits can be cached to improve performance on repeated requests for the same image.
- The cache has a maximum size defined by SAM_MAX_EMBEDDING_CACHE_SIZE. When the cache exceeds this size, the oldest entries are removed.
Source code in inference/models/sam2/segment_anything2.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
|
choose_most_confident_sam_prediction(masks, scores, low_resolution_logits)
¶
This function is supposed to post-process SAM2 inference and choose most confident
mask regardless of multimask_output
parameter value
Args:
masks: np array with values 0.0 and 1.0 representing predicted mask of size
(prompt_set_size, proposed_maks, h, w) or (proposed_maks, h, w) - depending on
prompt set size - unfortunately, prompt_set_size=1 causes squeeze operation
in SAM2 library, so to handle inference uniformly, we need to compensate with
this function.
scores: array of size (prompt_set_size, proposed_maks) or (proposed_maks, ) depending
on prompt set size - this array gives confidence score for mask proposal
low_resolution_logits: array of size (prompt_set_size, proposed_maks, 256, 256) or
(proposed_maks, 256, 256) - depending on prompt set size. These low resolution logits
can be passed to a subsequent iteration as mask input.
Returns:
Tuple of np.array, where:
- first element is of size (prompt_set_size, h, w) and represent mask with the highest confidence
for each prompt element
- second element is of size (prompt_set_size, ) and represents ths score for most confident mask
of each prompt element
- third element is of size (prompt_set_size, 256, 256) and represents the low resolution logits
for most confident mask of each prompt element
Source code in inference/models/sam2/segment_anything2.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
|
find_prior_prompt_in_cache(initial_prompt_set, image_id, cache)
¶
Performs search over the cache to see if prior used prompts are subset of this one.
Source code in inference/models/sam2/segment_anything2.py
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
|
hash_prompt_set(image_id, prompt_set)
¶
Computes unique hash from a prompt set.
Source code in inference/models/sam2/segment_anything2.py
342 343 344 345 346 |
|
maybe_load_low_res_logits_from_cache(image_id, prompt_set, cache)
¶
Loads prior masks from the cache by searching over possibel prior prompts.
Source code in inference/models/sam2/segment_anything2.py
349 350 351 352 353 354 355 356 357 358 359 |
|
pad_points(args)
¶
Pad arguments to be passed to sam2 model with not_a_point label (-1). This is necessary when there are multiple prompts per image so that a tensor can be created.
Also pads empty point lists with a dummy non-point entry.
Source code in inference/models/sam2/segment_anything2.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
|