pythonadvanced

Image Segmentation with SAM in Python

Segment any object in an image using Meta's Segment Anything Model (SAM) with Python.

python
from segment_anything import sam_model_registry, SamPredictor
import numpy as np
import cv2

# Download weights: wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
sam = sam_model_registry['vit_h'](checkpoint='sam_vit_h_4b8939.pth')
predictor = SamPredictor(sam)

image = cv2.imread('photo.jpg')
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image_rgb)

# Prompt with a point (x, y)
input_point = np.array([[250, 375]])
input_label = np.array([1])  # 1=foreground

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True,
)

best_mask = masks[np.argmax(scores)]
print(f'Masks: {masks.shape}, Best score: {scores.max():.3f}')
cv2.imwrite('segmented.png', best_mask.astype(np.uint8) * 255)

Use Cases

  • object segmentation
  • image editing
  • computer vision

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.