Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

Phân đoạn mọi mô hình

SAM: phân đoạn ảnh zero-shot thông qua các điểm, hộp, mặt nạ.

Siêu dữ liệu kỹ năng

NguồnĐi kèm (được cài đặt theo mặc định)
Đường dẫn

skills/mlops/models/segment-anything ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

segment-anything

, `transformers>=4.30.0

, torch>=1.7.0 | | Nền tảng | Linux, macOS, Windows | | Thẻ |

Multimodal

, `Image Segmentation

, `Computer Vision

, `SAM

, Zero-Shot |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

Mô hình phân đoạn bất kỳ (SAM)

Hướng dẫn toàn diện về cách sử dụng Mô hình bất kỳ phân đoạn nào của Meta AI để phân đoạn hình ảnh không cần chụp.

Khi nào nên sử dụng SAM`Sử dụng SAM khi:

  • Cần phân đoạn bất kỳ đối tượng nào trong hình ảnh mà không cần đào tạo về nhiệm vụ cụ thể
  • Xây dựng các công cụ chú thích tương tác với lời nhắc điểm/hộp
  • Tạo dữ liệu đào tạo cho các mô hình tầm nhìn khác
  • Cần chuyển không ảnh sang miền hình ảnh mới
  • Xây dựng quy trình phát hiện/phân đoạn đối tượng
  • Xử lý hình ảnh y tế, vệ tinh hoặc tên miền cụ thể`Các tính năng chính:
  • Phân đoạn không ảnh: Hoạt động trên mọi miền hình ảnh mà không cần tinh chỉnh
  • Lời nhắc linh hoạt: Điểm, hộp giới hạn hoặc mặt nạ trước đó
  • Phân đoạn tự động: Tự động tạo tất cả các mặt nạ đối tượng
  • Chất lượng cao: Được đào tạo trên 1,1 tỷ mặt nạ từ 11 triệu hình ảnh
  • Nhiều kích cỡ model: ViT-B (nhanh nhất), ViT-L, ViT-H (chính xác nhất)
  • Xuất ONNX: Triển khai trên trình duyệt và thiết bị biên`Sử dụng các lựa chọn thay thế thay thế:
  • YOLO/Detectron2: Để phát hiện đối tượng theo thời gian thực với các lớp
  • Mask2Former: Dành cho phân đoạn theo ngữ nghĩa/toàn cảnh với các danh mục
  • GroundingDINO + SAM: Dành cho phân đoạn được nhắc bằng văn bản
  • SAM 2: Dành cho tác vụ phân đoạn video

Bắt đầu nhanh

Cài đặt


# From GitHub
pip install git+https://GitHub.com/facebookresearch/segment-anything.git

# Optional dependencies
pip install opencv-Python pycocotools matplotlib

# Or use HuggingFace transformers
pip install transformers

`

### Tải xuống điểm kiểm tra

``` bash

# ViT-H (largest, most accurate) - 2.4GB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth

# ViT-L (medium) - 1.2GB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth

# ViT-B (smallest, fastest) - 375MB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth

`

### Cách sử dụng cơ bản với SamPredictor

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

# Load model
sam = sam_model_registry["vit_h"](https://GitHub.com/NousResearch/Hermes-agent/blob/main/skills/mlops/models/segment-anything/checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

# Create predictor
predictor = SamPredictor(sam)

# Set image (computes embeddings once)
image = cv2.imread("image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)

# Predict with point prompts
input_point = np.array([[500, 375]]) # (x, y) coordinates
input_label = np.array([1]) # 1 = foreground, 0 = background`masks, scores, logits = predictor.predict(
point_coords=input_point,
point_labels=input_label,
multimask_output=True # Returns 3 mask options
)

# Select best mask
best_mask = masks[np.argmax(scores)]

`

### Ôm Mặt Transformers

`Python
import torch
from PIL import Image
from transformers import SamModel, SamProcessor

# Load model and processor
model = SamModel.from_pretrained("facebook/sam-vit-huge")
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")
model.to("cuda")

# Process image with point prompt
image = Image.open("image.jpg")
input_points = [[[450, 600]]] # Batch of points`inputs = processor(image, input_points=input_points, return_tensors="pt")
inputs = \{k: v.to("cuda") for k, v in inputs.items()}

# Generate masks
with torch.no_grad():
outputs = model(**inputs)

# Post-process masks to original size
masks = processor.image_processor.post_process_masks(
outputs.pred_masks.cpu(),
inputs["original_sizes"].cpu(),
inputs["reshaped_input_sizes"].cpu()
)

`

## Khái niệm cốt lõi

### Kiến trúc mô hình`<!-- ascii-guard-ignore -->
<!-- ascii-guard-ignore -->

`

SAM Architecture:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Image Encoder │────▶│ Prompt Encoder │────▶│ Mask Decoder │
(ViT) │ │ (Points/Boxes) │ │ (Transformer)
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
Image Embeddings Prompt Embeddings Masks + IoU
(computed once) (per prompt) predictions

`

<!-- ascii-guard-ignore-end -->
<!-- ascii-guard-ignore-end -->

### Các biến thể của mô hình

| Người mẫu | Điểm kiểm tra | Kích thước | Tốc độ | Độ chính xác |
|-------|-------------|------|-------|----------|
| ViT-H |

vit_h
` | 2,4 GB | Chậm nhất | Tốt nhất |
| ViT-L |

vit_l
` | 1,2 GB | Trung bình | Tốt |
| ViT-B |

vit_b
` | 375 MB | Nhanh nhất | Tốt |

### Các loại lời nhắc

| Nhắc | Mô tả | Trường hợp sử dụng |
|--------|-------------|----------|
| Điểm (tiền cảnh) | Bấm vào đối tượng | Lựa chọn đối tượng đơn lẻ |
| Điểm (nền) | Bấm vào đối tượng bên ngoài | Loại trừ vùng |
| Hộp giới hạn | Hình chữ nhật xung quanh đồ vật | Vật thể lớn hơn |
| Mặt nạ trước | Đầu vào mặt nạ có độ phân giải thấp | Tinh chỉnh lặp đi lặp lại |

## Phân đoạn tương tác

### Lời nhắc về điểm

`Python

# Single foreground point
input_point = np.array([[500, 375]])
input_label = np.array([1])

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

# Multiple points (foreground + background)
input_points = np.array([[500, 375], [600, 400], [450, 300]])
input_labels = np.array([1, 1, 0]) # 2 foreground, 1 background`masks, scores, logits = predictor.predict(
point_coords=input_points,
point_labels=input_labels,
multimask_output=False # Single mask when prompts are clear
)

`

### Hộp nhắc nhở

``` python

# Bounding box [x1, y1, x2, y2]
input_box = np.array([425, 600, 700, 875])

masks, scores, logits = predictor.predict(
box=input_box,
multimask_output=False
)

`

### Lời nhắc kết hợp

``` python

# Box + points for precise control
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
box=np.array([400, 300, 700, 600]),
multimask_output=False
)

`

### Tinh chỉnh lặp đi lặp lại

``` python

# Initial prediction
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True
)

# Refine with additional point using previous mask
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375], [550, 400]]),
point_labels=np.array([1, 0]), # Add background point
mask_input=logits[np.argmax(scores)][None, :, :], # Use best mask
multimask_output=False
)

`

## Tạo mặt nạ tự động

### Phân đoạn tự động cơ bản

``` python
from segment_anything import SamAutomaticMaskGenerator

# Create generator
mask_generator = SamAutomaticMaskGenerator(sam)

# Generate all masks
masks = mask_generator.generate(image)

# Each mask contains:

# - segmentation: binary mask
# - bbox: [x, y, w, h]
# - area: pixel count
# - predicted_iou: quality score
# - stability_score: robustness score
# - point_coords: generating point

`

### Thế hệ tùy chỉnh

``` python
mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side=32, # Grid density (more = more masks)
pred_iou_thresh=0.88, # Quality threshold
stability_score_thresh=0.95, # Stability threshold
crop_n_layers=1, # Multi-scale crops
crop_n_points_downscale_factor=2,
min_mask_region_area=100, # Remove tiny masks
)

masks = mask_generator.generate(image)

`

### Mặt nạ lọc

`Python

# Sort by area (largest first)
masks = sorted(masks, key=lambda x: x['area'], reverse=True)

# Filter by predicted IoU
high_quality = [m for m in masks if m['predicted_iou'] > 0.9]

# Filter by stability score
stable_masks = [m for m in masks if m['stability_score'] > 0.95]

`

## Suy luận theo đợt

### Nhiều hình ảnh

``` python

# Process multiple images efficiently
images = [cv2.imread(f"image_\{i}.jpg") for i in range(10)]

all_masks = []
for image in images:
predictor.set_image(image)
masks, _, _ = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True
)
all_masks.append(masks)

`

### Nhiều lời nhắc cho mỗi hình ảnh

``` python

# Process multiple prompts efficiently (one image encoding)
predictor.set_image(image)

# Batch of point prompts
points = [
np.array([[100, 100]]),
np.array([[200, 200]]),
np.array([[300, 300]])
]

all_masks = []
for point in points:
masks, scores, _ = predictor.predict(
point_coords=point,
point_labels=np.array([1]),
multimask_output=True
)
all_masks.append(masks[np.argmax(scores)])

`

## Triển khai ONNX

### Xuất mô hình

``` bash
Python scripts/export_onnx_model.py \

--checkpoint sam_vit_h_4b8939.pth \
--model-type vit_h \
--output sam_onnx.onnx \
--return-single-mask

`

### Sử dụng mô hình ONNX

``` python
import onnxruntime

# Load ONNX model
ort_session = onnxruntime.InferenceSession("sam_onnx.onnx")

# Run inference (image embeddings computed separately)
masks = ort_session.run(
None,
{
"image_embeddings": image_embeddings,
"point_coords": point_coords,
"point_labels": point_labels,
"mask_input": np.zeros((1, 1, 256, 256), dtype=np.float32),
"has_mask_input": np.array([0], dtype=np.float32),
"orig_im_size": np.array([h, w], dtype=np.float32)
}
)

`

## Quy trình công việc chung

### Workflow 1: Công cụ chú thích

`Python
import cv2

# Load model
predictor = SamPredictor(sam)
predictor.set_image(image)

def on_CLIck(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:

# Foreground point
masks, scores, _ = predictor.predict(
point_coords=np.array([[x, y]]),
point_labels=np.array([1]),
multimask_output=True
)
# Display best mask
display_mask(masks[np.argmax(scores)])

`

### Workflow 2: Trích xuất đối tượng

``` python
def extract_object(image, point):
"""Extract object at point with transparent background."""
predictor.set_image(image)

masks, scores, _ = predictor.predict(
point_coords=np.array([point]),
point_labels=np.array([1]),
multimask_output=True
)

best_mask = masks[np.argmax(scores)]

# Create RGBA output
rgba = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
rgba[:, :, :3] = image
rgba[:, :, 3] = best_mask * 255`return rgba

`

### Workflow 3: Phân đoạn hình ảnh y tế

`Python

# Process medical images (grayscale to RGB)
medical_image = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)
rgb_image = cv2.cvtColor(medical_image, cv2.COLOR_GRAY2RGB)

predictor.set_image(rgb_image)

# Segment region of interest
masks, scores, _ = predictor.predict(
box=np.array([x1, y1, x2, y2]), # ROI bounding box
multimask_output=True
)

`

## Định dạng đầu ra

### Cấu trúc dữ liệu mặt nạ

``` python

# SamAutomaticMaskGenerator output
{
"segmentation": np.ndarray, # H×W binary mask
"bbox": [x, y, w, h], # Bounding box
"area": int, # Pixel count
"predicted_iou": float, # 0-1 quality score
"stability_score": float, # 0-1 robustness score
"crop_box": [x, y, w, h], # Generation crop region
"point_coords": [[x, y]], # Input point
}

`

### định dạng COCO RLE

``` python
from pycocotools import mask as mask_utils

# Encode mask to RLE
rle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))
rle["counts"] = rle["counts"].decode("utf-8")

# Decode RLE to mask
decoded_mask = mask_utils.decode(rle)

`

## Tối ưu hóa hiệu suất

### bộ nhớ GPU

`Python

# Use smaller model for limited VRAM
sam = sam_model_registry["vit_b"](https://GitHub.com/NousResearch/Hermes-agent/blob/main/skills/mlops/models/segment-anything/checkpoint="sam_vit_b_01ec64.pth")

# Process images in batches
# Clear CUDA cache between large batches
torch.cuda.empty_cache()

`

### Tối ưu hóa tốc độ

``` python

# Use half precision
sam = sam.half()

# Reduce points for automatic generation
mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side=16, # Default is 32
)

# Use ONNX for deployment
# Export with --return-single-mask for faster inference

`

## Các vấn đề thường gặp

| Vấn đề | Giải pháp |
|-------|----------|
| Hết bộ nhớ | Sử dụng mô hình ViT-B, giảm kích thước hình ảnh |
| Suy luận chậm | Dùng ViT-B, giảm point_per_side |
| Chất lượng mặt nạ kém | Hãy thử các lời nhắc khác nhau, sử dụng hộp + điểm |
| Hiện vật cạnh | Sử dụng tính năng lọc stable_score |
| Đồ vật nhỏ bị bỏ sót | Tăng điểm_per_side |

## Tài liệu tham khảo- **[Advanced Usage](https://GitHub.com/NousResearch/Hermes-agent/blob/main/skills/mlops/models/segment-anything/references/advanced-usage.md)** - Phân khối, tinh chỉnh, tích hợp
- **[Troubleshooting](https://GitHub.com/NousResearch/Hermes-agent/blob/main/skills/mlops/models/segment-anything/references/troubleshooting.md)** - Các vấn đề thường gặp và giải pháp

## Tài nguyên
- **GitHub**: https://GitHub.com/facebookresearch/segment-anything
- **Giấy**: https://arxiv.org/abs/2304.02643
- **Bản demo**: https://segment-anything.com
- **SAM 2 (Video)**: https://GitHub.com/facebookresearch/segment-anything-2
- **Hugging Face**: https://huggingface.co/facebook/sam-vit-huge