模型简介
模型特点
模型能力
使用案例
🚀 高质量任意分割模型 (SAM-HQ)
SAM-HQ 是对任意分割模型 (SAM) 的增强版本,能根据点或框等输入提示生成更高质量的对象掩码。在处理复杂结构的对象时,它显著提升了掩码质量,同时保留了 SAM 原有的可提示设计、效率和零样本泛化能力。
🚀 快速开始
SAM-HQ(高质量任意分割模型)是任意分割模型(SAM)的增强版本,可根据点或框等输入提示生成更高质量的对象掩码。SAM 在包含 1100 万张图像和 11 亿个掩码的数据集上进行训练,但在许多情况下,其掩码预测质量欠佳,尤其是处理具有复杂结构的对象时。SAM-HQ 以最小的额外参数和计算成本解决了这些限制。
该模型即使对于具有复杂边界和细结构的对象(原始 SAM 模型通常难以处理),也能出色地生成高质量的分割掩码。SAM-HQ 在显著提高掩码质量的同时,保留了 SAM 原有的可提示设计、效率和零样本泛化能力。
✨ 主要特性
SAM-HQ 在保留 SAM 预训练权重的基础上,对原始 SAM 架构进行了两项关键创新:
- 高质量输出令牌:注入到 SAM 掩码解码器中的可学习令牌,负责预测高质量掩码。与 SAM 的原始输出令牌不同,此令牌及其关联的 MLP 层经过专门训练,以生成高度准确的分割掩码。
- 全局 - 局部特征融合:SAM-HQ 不是仅在掩码解码器特征上应用 HQ 输出令牌,而是首先将这些特征与早期和最终的 ViT 特征融合,以改善掩码细节。这结合了高级语义上下文和低级边界信息,实现更准确的分割。
SAM-HQ 在精心策划的 44K 细粒度掩码数据集(HQSeg - 44K)上进行训练,该数据集来自多个来源,具有极其准确的注释。训练过程在 8 个 GPU 上仅需 4 小时,与原始 SAM 模型相比,引入的额外参数不到 0.5%。
该模型在 10 个不同的分割数据集上进行了评估,涵盖不同的下游任务,其中 8 个数据集采用零样本迁移协议进行评估。结果表明,SAM-HQ 可以生成比原始 SAM 模型明显更好的掩码,同时保持其零样本泛化能力。
SAM-HQ 解决了原始 SAM 模型的两个关键问题:
- 掩码边界粗糙,常常忽略细对象结构。
- 在具有挑战性的情况下,预测错误、掩码断裂或出现较大误差。
这些改进使 SAM-HQ 对于需要高精度图像掩码的应用特别有价值,例如自动注释和图像/视频编辑任务。
💻 使用示例
基础用法
from PIL import Image
import requests
from transformers import SamHQModel, SamHQProcessor
model = SamHQModel.from_pretrained("syscv-community/sam-hq-vit-base")
processor = SamHQProcessor.from_pretrained("syscv-community/sam-hq-vit-base")
img_url = "https://raw.githubusercontent.com/SysCV/sam-hq/refs/heads/main/demo/input_imgs/example1.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
input_boxes = [[[306, 132, 925, 893]]] # Bounding box for the image
inputs = processor(raw_image, input_boxes=input_boxes, return_tensors="pt").to("cuda")
outputs = model(**inputs)
masks = processor.image_processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu())
scores = outputs.iou_scores
在生成掩码的其他参数中,您可以传递感兴趣对象近似位置的二维位置、包围感兴趣对象的边界框(格式应为边界框右上角和左下角的 x、y 坐标)、分割掩码。撰写本文时,根据官方仓库,官方模型不支持将文本作为输入。有关更多详细信息,请参阅此笔记本,其中展示了如何使用该模型,并配有可视化示例!
高级用法
from transformers import pipeline
generator = pipeline("mask-generation", model="syscv-community/sam-hq-vit-base", device=0, points_per_batch=256)
image_url = "https://raw.githubusercontent.com/SysCV/sam-hq/refs/heads/main/demo/input_imgs/example1.png"
outputs = generator(image_url, points_per_batch=256)
现在显示图像:
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
ax.imshow(mask_image)
plt.imshow(np.array(raw_image))
ax = plt.gca()
for mask in outputs["masks"]:
show_mask(mask, ax=ax, random_color=True)
plt.axis("off")
plt.show()
带可视化的完整示例
import numpy as np
import matplotlib.pyplot as plt
def show_mask(mask, ax, random_color=False):
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30/255, 144/255, 255/255, 0.6])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
ax.imshow(mask_image)
def show_box(box, ax):
x0, y0 = box[0], box[1]
w, h = box[2] - box[0], box[3] - box[1]
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
def show_boxes_on_image(raw_image, boxes):
plt.figure(figsize=(10,10))
plt.imshow(raw_image)
for box in boxes:
show_box(box, plt.gca())
plt.axis('on')
plt.show()
def show_points_on_image(raw_image, input_points, input_labels=None):
plt.figure(figsize=(10,10))
plt.imshow(raw_image)
input_points = np.array(input_points)
if input_labels is None:
labels = np.ones_like(input_points[:, 0])
else:
labels = np.array(input_labels)
show_points(input_points, labels, plt.gca())
plt.axis('on')
plt.show()
def show_points_and_boxes_on_image(raw_image, boxes, input_points, input_labels=None):
plt.figure(figsize=(10,10))
plt.imshow(raw_image)
input_points = np.array(input_points)
if input_labels is None:
labels = np.ones_like(input_points[:, 0])
else:
labels = np.array(input_labels)
show_points(input_points, labels, plt.gca())
for box in boxes:
show_box(box, plt.gca())
plt.axis('on')
plt.show()
def show_points_and_boxes_on_image(raw_image, boxes, input_points, input_labels=None):
plt.figure(figsize=(10,10))
plt.imshow(raw_image)
input_points = np.array(input_points)
if input_labels is None:
labels = np.ones_like(input_points[:, 0])
else:
labels = np.array(input_labels)
show_points(input_points, labels, plt.gca())
for box in boxes:
show_box(box, plt.gca())
plt.axis('on')
plt.show()
def show_points(coords, labels, ax, marker_size=375):
pos_points = coords[labels==1]
neg_points = coords[labels==0]
ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
def show_masks_on_image(raw_image, masks, scores):
if len(masks.shape) == 4:
masks = masks.squeeze()
if scores.shape[0] == 1:
scores = scores.squeeze()
nb_predictions = scores.shape[-1]
fig, axes = plt.subplots(1, nb_predictions, figsize=(15, 15))
for i, (mask, score) in enumerate(zip(masks, scores)):
mask = mask.cpu().detach()
axes[i].imshow(np.array(raw_image))
show_mask(mask, axes[i])
axes[i].title.set_text(f"Mask {i+1}, Score: {score.item():.3f}")
axes[i].axis("off")
plt.show()
def show_masks_on_single_image(raw_image, masks, scores):
if len(masks.shape) == 4:
masks = masks.squeeze()
if scores.shape[0] == 1:
scores = scores.squeeze()
# Convert image to numpy array if it's not already
image_np = np.array(raw_image)
# Create a figure
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(image_np)
# Overlay all masks on the same image
for i, (mask, score) in enumerate(zip(masks, scores)):
mask = mask.cpu().detach().numpy() # Convert to NumPy
show_mask(mask, ax) # Assuming `show_mask` properly overlays the mask
ax.set_title(f"Overlayed Masks with Scores")
ax.axis("off")
plt.show()
import torch
from transformers import SamHQModel, SamHQProcessor
device = "cuda" if torch.cuda.is_available() else "cpu"
model = SamHQModel.from_pretrained("syscv-community/sam-hq-vit-base").to(device)
processor = SamHQProcessor.from_pretrained("syscv-community/sam-hq-vit-base")
from PIL import Image
import requests
img_url = "https://raw.githubusercontent.com/SysCV/sam-hq/refs/heads/main/demo/input_imgs/example1.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
plt.imshow(raw_image)
inputs = processor(raw_image, return_tensors="pt").to(device)
image_embeddings, intermediate_embeddings = model.get_image_embeddings(inputs["pixel_values"])
input_boxes = [[[306, 132, 925, 893]]]
show_boxes_on_image(raw_image, input_boxes[0])
inputs.pop("pixel_values", None)
inputs.update({"image_embeddings": image_embeddings})
inputs.update({"intermediate_embeddings": intermediate_embeddings})
with torch.no_grad():
outputs = model(**inputs)
masks = processor.image_processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu())
scores = outputs.iou_scores
show_masks_on_single_image(raw_image, masks[0], scores)
show_masks_on_image(raw_image, masks[0], scores)
📄 许可证
本项目采用 Apache - 2.0 许可证。
📚 引用
@misc{ke2023segmenthighquality,
title={Segment Anything in High Quality},
author={Lei Ke and Mingqiao Ye and Martin Danelljan and Yifan Liu and Yu-Wing Tai and Chi-Keung Tang and Fisher Yu},
year={2023},
eprint={2306.01567},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2306.01567},
}











