SAM 2: Segmen Anything v2 操作示例

SAM 2 是 Meta 的Segment Anything Model (SAM) 的第二代产品,官网地址

官方操作教程写得很清楚了,这里主要介绍一下如何通过YOLO来快速实现分割。

1、安装

安装非常简单,要安装SAM 2,请使用以下命令。首次使用时,所有SAM 2 型号都会自动下载。

pip install ultralytics

2、预训练权重下载

官网下载,

3、SAM 2 预测示例

from ultralytics import SAM

# Load a model
model = SAM("sam2.1_b.pt")

# Display model information (optional)
model.info()

# Run inference with bboxes prompt
results = model("path/to/image.jpg", bboxes=[100, 100, 200, 200])

# Run inference with single point
results = model(points=[900, 370], labels=[1])

# Run inference with multiple points
results = model(points=[[400, 370], [900, 370]], labels=[1, 1])

# Run inference with multiple points prompt per object
results = model(points=[[[400, 370], [900, 370]]], labels=[[1, 1]])

# Run inference with negative points prompt
results = model(points=[[[400, 370], [900, 370]]], labels=[[1, 0]])

4、Surprise

### Segment Anything Ultra V2 概述 Segment Anything Ultra V2 是由 Facebook Research 开发的一个图像分割模型,旨在提供更高效、精确的分割能力。该版本引入了多项改进和技术优化[^3]。 #### 模型特性 相比之前的版本,Segment Anything Ultra V2 提供了几项显著增强的功能: - **更高的精度**:通过采用先进的神经网络架构设计,实现了更加细致入微的目标检测效果。 - **更快的速度**:针对硬件加速进行了特别优化,在保持高分辨率的同时大幅提升了处理速度。 - **更低资源消耗**:对于显存有限的情况提供了有效的解决方案,允许在较低配置设备上运行复杂任务[^2]。 #### 安装与依赖库 为了顺利安装并使用此模型,建议先确认环境满足最低要求,并按照官方指南完成必要的准备工作。通常情况下需要 Python 3.x 及以上版本的支持,以及 PyTorch 等深度学习框架作为基础组件。 如果遇到类似于 "找不到VITMatte模型" 的错误提示,则可能是因为缺少特定文件或路径设置不正确所致。此时应当仔细核对文档说明中的指引来解决问题[^1]。 ```bash pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117/ git clone https://github.com/facebookresearch/segment-anything.git cd segment-anything pip install -e . ``` #### 使用教程 以下是基于 Python 编写的简单示例程序,用于展示如何加载预训练权重并对单张图片执行实例级语义分割操作: ```python from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor import cv2 import matplotlib.pyplot as plt def show_anns(anns): if len(anns) == 0: return sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True) ax = plt.gca() ax.set_autoscale_on(False) img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4)) img[:,:,3] = 0 for ann in sorted_anns: m = ann['segmentation'] color_mask = np.random.random((1, 3)).tolist()[0] + [0.6] img[m] = color_mask ax.imshow(img) image = cv2.imread('./assets/dogs.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) sam_checkpoint = "./models/sam_vit_h_4b8939.pth" model_type = "vit_h" device = "cuda" sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) sam.to(device=device) mask_generator = SamAutomaticMaskGenerator(sam) masks = mask_generator.generate(image) plt.figure(figsize=(20,20)) plt.imshow(image) show_anns(masks) plt.axis('off') plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值