Segment Anything

Segment Anything

code: https://github.com/facebookresearch/segment-anything
paper: 论文地址
在线demo:https://segment-anything.com/demo
数据集:https://segment-anything.com/dataset/index.html

安装

python>=3.8, as well as pytorch>=1.7 and torchvision>=0.8

pip install git+https://github.com/facebookresearch/segment-anything.git
or 
git clone git@github.com:facebookresearch/segment-anything.git
cd segment-anything; pip install -e .

pip install opencv-python pycocotools matplotlib onnxruntime onnx

代码测试

可以通过jupyter notebook 体验测试
在这里插入图片描述

#显示点、框和遮罩所需的导入和辅助函数
import numpy as np
import torch
import matplotlib.pyplot as plt
import cv2

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_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_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))  
#导入测试图片
image = cv2.imread('images/w1200.jpeg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10,10))
plt.imshow(image)
plt.axis('on')
plt.show()

在这里插入图片描述
使用SAM选择对象
首先,加载SAM模型和预测器。将下面的路径更改为指向SAM checkpoint。
为了获得最佳效果,建议在CUDA上运行并使用默认模型。

import sys
sys.path.append("..")
from segment_anything import sam_model_registry, SamPredictor

sam_checkpoint = "sam_vit_h_4b8939.pth" #需下载模型权重
model_type = "vit_h"

device = "cuda"

sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)

predictor = SamPredictor(sam)

通过调用SamPredictor.set_image处理图像以生成图像嵌入,SamPredictor会记住这个嵌入,并将其用于后续的掩码预测。

predictor.set_image(image)

要选择人,在人区域内选择一个点。点以(x,y)格式输入到模型中,并带有标签1(前景点)或0(背景点)。可以输入多个点;这里只使用一个,所选的点将在图像上显示为一颗星。

input_point = np.array([[250, 300]])
input_label = np.array([1])
plt.figure(figsize=(10,10))
plt.imshow(image)
show_points(input_point, input_label, plt.gca())
plt.axis('on')
plt.show()  

在这里插入图片描述
使用SamPredictor.predict进行预测,该模型返回mask,这些mask的质量预测以及可传递到下一次预测迭代的低分辨率mask逻辑。

#multimask_output=True(默认设置)时,SAM输出3个mask,
#其中scores给出模型自己对这些遮罩质量的估计。此设置用于不明确的输入提示,
#有助于模型区分与提示一致的不同对象。如果为False,它将返回单个掩码。
#对于像单点这样的模糊提示,建议使用multimask_output=True,即使只需要一个掩码;
#可以通过挑选在分数中返回最高分数的一个来选择最佳的单个掩码。这通常会产生更好的mask。
masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True,
)

输入mask结果

for i, (mask, score) in enumerate(zip(masks, scores)):
    plt.figure(figsize=(10,10))
    plt.imshow(image)
    show_mask(mask, plt.gca())
    show_points(input_point, input_label, plt.gca())
    plt.title(f"Mask {i+1}, Score: {score:.3f}", fontsize=18)
    plt.axis('off')
    plt.show()  

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

网页demo测试

在这里插入图片描述
根据坐标点分割
在这里插入图片描述
根据box区域分割
在这里插入图片描述
全局分割
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值