RF SAM 2

raw JSON →
1.0.3 verified Sat May 09 auth: no python

Roboflow-maintained package for Meta's SAM 2 (Segment Anything Model 2) for image and video segmentation. Currently version 1.0.3, updated March 2025.

pip install rf-sam-2
error ImportError: cannot import name 'SAM2' from 'sam2'
cause Incorrect import path; the module is 'rf_sam_2' not 'sam2'.
fix
Install rf-sam-2 and use: from rf_sam_2 import SAM2
error RuntimeError: No CUDA GPUs are available
cause CUDA not available but default device is cuda.
fix
Set environment variable SAM2_DEVICE=cpu before importing: os.environ['SAM2_DEVICE'] = 'cpu'
error AttributeError: module 'rf_sam_2' has no attribute 'sam_model_registry'
cause Using old SAM API with new SAM2 package.
fix
Use SAM2.from_pretrained() or SAM2ImagePredictor.from_pretrained() instead.
breaking The import path changed from 'sam2' to 'rf_sam_2' in version 1.0.0.
fix Use 'from rf_sam_2 import SAM2' instead of 'from sam2 import SAM2'.
deprecated The old 'segment_anything' API is not supported; use the new SAM2 classes.
fix Replace 'sam_model_registry' with 'SAM2.from_pretrained()'.
gotcha CPU inference requires setting environment variable 'SAM2_DEVICE=cpu' before import.
fix os.environ['SAM2_DEVICE'] = 'cpu' before importing rf_sam_2.

Basic image segmentation with a single point prompt.

import torch
from rf_sam_2 import SAM2

# Load model (set environment variable for API key if needed)
model = SAM2.from_pretrained("sam2-hiera-large")

# Predict with an image
import cv2
image = cv2.imread("path/to/image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

with torch.inference_mode():
    masks, scores, logits = model.predict(image, point_coords=[[500, 375]], point_labels=[1])

print(masks.shape, scores)