pythonadvanced
Image Segmentation with SAM in Python
Segment any object in an image using Meta's Segment Anything Model (SAM) with Python.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Segmentation Models
AI/ML technique: segmentation-models
Best for: machine learning
#ai#machine-learning
pythonintermediate
OpenCV Face Detection with DNN
Detect faces in images using OpenCV's deep neural network face detector for accurate results.
Best for: face detection
#opencv#computer-vision
kotlinbeginner
SAM Conversions and Functional Interfaces
Use SAM conversions with fun interfaces: Java interop, event listeners, and callback patterns.
Best for: Java interop with functional interfaces
#kotlin#sam
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming