抠图模型:segment anything本地使用教程

说明:这里用到的是mata改进的EfficientSAM,参数只有segment anything原版的5%,但是准确度差别不超过2%。

简介

segment anything是著名的分割模型,也就是抠图,

环境准备

sudo apt-get install python3-pyqt5  # PyQt5
sudo pip3 install labelme

代码说明

拉取项目后在这里有两个分割模型,是两个版本,两个版本效果会有一些差别,给的EfficientSAM_example.py文件中对两个版本的模型都进行了测试,我自己的体验是vitt要更好一些,不过差别不大
在这里插入图片描述
然后用这样的代码加载两个模型

models = {}
models['efficientsam_ti'] = build_efficient_sam_vitt()

with zipfile.ZipFile("weights/efficient_sam_vits.pt.zip", 'r') as zip_ref:
    zip_ref.extractall("weights")
models['efficientsam_s'] = build_efficient_sam_vits()

这边定义要抠图的路径

sample_image = Image.open("figs/examples/dogs.png")

在这里插入图片描述
安装一个labelme工具,从而获取要抠图的目标点
比如这张图有两个主要色块点,就找到这两个点的坐标【绿色标注】
在这里插入图片描述
在这里填写你获取的坐标,举个例子,如果你有两个点,就填写两个点,两个label,有三个点也可以设置三个【把下面改成三个点的坐标:torch.tensor([[[[373, 307], [344, 328], [490, 330]]]]和 [[[1, 1, 1]]]】

# Input points for the mask
input_points = torch.tensor([[[[373, 307], [344, 328]]]).float()  # Ensure float for model input
input_labels = torch.tensor([[[1, 1]]]).float()  # Ensure float for model input

最后生成透明背景图保存

以下是完整代码【由于我的需求是生成透明背景,这里是改过之后的,输入图为png格式】

from PIL import Image
import numpy as np
import torch
from torchvision import transforms
import zipfile
from efficient_sam.build_efficient_sam import build_efficient_sam_vitt, build_efficient_sam_vits

# Models initialization
models = {}
models['efficientsam_ti'] = build_efficient_sam_vitt()

with zipfile.ZipFile("weights/efficient_sam_vits.pt.zip", 'r') as zip_ref:
    zip_ref.extractall("weights")
models['efficientsam_s'] = build_efficient_sam_vits()

# Load the image
sample_image = Image.open("figs/program2/ship2.png")

# Convert RGBA to RGB if the image has an alpha channel
if sample_image.mode == 'RGBA':
    sample_image = sample_image.convert('RGB')

# Convert the image to a numpy array
sample_image_np = np.array(sample_image)

# Convert the numpy array to a tensor and normalize
sample_image_tensor = transforms.ToTensor()(sample_image_np)

# Input points for the mask
input_points = torch.tensor([[[[373, 307], [344, 328], [490, 330]]]]).float()  # Ensure float for model input
input_labels = torch.tensor([[[1, 1, 1]]]).float()  # Ensure float for model input

# Run inference for both EfficientSAM-Ti and EfficientSAM-S models
for model_name, model in models.items():
    print('Running inference using ', model_name)
    
    predicted_logits, predicted_iou = model(
        sample_image_tensor[None, ...],  # Add batch dimension
        input_points,
        input_labels,
    )
    
    sorted_ids = torch.argsort(predicted_iou, dim=-1, descending=True)
    predicted_iou = torch.take_along_dim(predicted_iou, sorted_ids, dim=2)
    predicted_logits = torch.take_along_dim(predicted_logits, sorted_ids[..., None, None], dim=2)
    
    # Get the mask: true for object, false for background
    mask = torch.ge(predicted_logits[0, 0, 0, :, :], 0).cpu().detach().numpy()
    
    # Create an RGBA image, with transparent background
    masked_image_np = np.zeros((sample_image_np.shape[0], sample_image_np.shape[1], 4), dtype=np.uint8)
    
    # Set the RGB channels (retain original image colors for the masked region)
    masked_image_np[:, :, :3] = sample_image_np
    
    # Set alpha channel (transparency)
    # Alpha channel is 255 for the object region, 0 for the background
    masked_image_np[:, :, 3] = (mask * 255).astype(np.uint8)

    # Save the image with transparency
    Image.fromarray(masked_image_np).save(f"figs/program2/ship_{model_name}_mask.png")

运行结果
在这里插入图片描述

### 如何结合使用 Stable Diffusion 和 Segment Anything 模型 为了使 Stable Diffusion 能够利用 Segment Anything 的功能来增强图像处理能力,具体操作流程如下: #### 准备工作环境 确保已经安装好 Stable Diffusion WebUI 并能够正常运行。接着,在扩展管理界面中查找并安装 `sd-webui-segment-anything` 插件[^2]。 #### 下载 SAM 模型文件 根据需求选择合适的 SAM 模型版本进行下载。对于大多数应用场景而言,推荐下载较大规模的 vit_h 版本以获得更优的效果,尽管这会占用更多显存资源。下载链接可参照官方 GitHub 页面获取,并将模型放置于指定目录:“...\sd-webui-aki-v4\extensions\sd-webui-segment-anything\models\sam”。如果遇到网络问题无法直接从GitHub下载,可以考虑其他第三方提供的镜像源,比如 mobile_sam.pt 文件可以通过特定网盘链接下载[^3][^4]。 #### 配置与测试 完成上述准备工作之后,重启 Stable Diffusion WebUI 应用程序使得新加载的组件生效。此时应该可以在界面上看到由 sd-webui-segment-anything 提供的新特性选项,如基于文本提示词的目标检测框绘制以及自动抠图等功能。通过这些工具可以帮助用户更加精准地定义想要修改或保留的画面区域,从而提高最终生成图片的质量和可控度。 ```bash cd stable_diffusion_webui_docker/extensions/sd-webui-segment-anything/models/sam bypy downfile /stable_diffusion/extensions/segment_anything/sam_vit_h_4b8939.pth sam_vit_h_4b8939.pth ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值