当前位置: 首页 > news >正文

Vision - 开源视觉分割算法框架 Grounded SAM2 配置与推理 教程 (1)

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/143388189

免责声明:本文来源于个人知识与公开资料,仅用于学术交流,欢迎讨论,不支持转载。


Grounded SAM2

Grounded SAM2 集成多个先进模型的视觉 AI 框架,融合 GroundingDINO、Florence-2 和 SAM2 等模型,实现开放域目标检测、分割和跟踪等多项视觉任务的突破性进展,通过自然语言描述来定位图像中的目标,生成精细的目标分割掩码,在视频序列中持续跟踪目标,保持 ID 的一致性。

Paper: Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks,SAM 版本由 1.0 升级至 2.0

1. 环境配置

GitHub: Grounded-SAM-2

git clone https://github.com/IDEA-Research/Grounded-SAM-2
cd Grounded-SAM-2

准备 SAM 2.1 模型,格式是 pt 的,GroundingDINO 模型,格式是 pth 的,即:

wget https://huggingface.co/facebook/sam2.1-hiera-large/resolve/main/sam2.1_hiera_large.pt?download=true -O sam2.1_hiera_large.pt
wget https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth

最新模型位置:

cd checkpoints
ln -s [your path]/llm/workspace_comfyui/ComfyUI/models/sam2/sam2_hiera_large.pt sam2_hiera_large.ptcd gdino_checkpoints
ln -s [your path]/llm/workspace_comfyui/ComfyUI/models/grounding-dino/groundingdino_swinb_cogcoor.pth groundingdino_swinb_cogcoor.pth
ln -s [your path]/llm/workspace_comfyui/ComfyUI/models/grounding-dino/groundingdino_swint_ogc.pth groundingdino_swint_ogc.pth

激活环境:

conda activate sam2

测试 PyTorch:

import torch
print(torch.__version__)  # 2.5.0+cu124
print(torch.cuda.is_available())  # True
exit()
echo $CUDA_HOME

安装 Grounding DINO:

pip install --no-build-isolation -e grounding_dino
pip show groundingdino

安装 SAM2:

pip install --no-build-isolation -e .
pip install --no-build-isolation -e ".[notebooks]"  # 适配 Jupyter
pip show SAM-2

配置参数:视觉分割开源算法 SAM2(Segment Anything 2) 配置与推理

依赖文件:

cd grounding_dino/
pip install -r requirements.txt --verbose

2. 测试图像

测试脚本:grounded_sam2_local_demo.py

导入相关的依赖包:

import os
import cv2
import json
import torch
import numpy as np
import supervision as sv
import pycocotools.mask as mask_util
from pathlib import Path
from torchvision.ops import box_convert
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
from grounding_dino.groundingdino.util.inference import load_model, load_image, predictfrom PIL import Image
import matplotlib.pyplot as plt

配置数据,以及依赖环境,其中包括:

  • 输入文本提示,例如 袜子(socks) 和 吉他(guitar)
  • 输入图像
  • SAM2 模型 v2.1 版本,以及配置
  • GroundingDINO (DETR with Improved deNoising anchOr boxes, 改进的去噪锚框的DETR) 模型,以及配置
  • Box 阈值、文本阈值
  • 输出文件夹与Json

即:

TEXT_PROMPT = "socks. guitar."
#IMG_PATH = "notebooks/images/truck.jpg"
IMG_PATH = "[your path]/llm/vision_test_data/image2.png"image = Image.open(IMG_PATH)
plt.figure(figsize=(9, 6))
plt.title(f"annotated_frame")
plt.imshow(image)SAM2_CHECKPOINT = "./checkpoints/sam2.1_hiera_large.pt"
SAM2_MODEL_CONFIG = "configs/sam2.1/sam2.1_hiera_l.yaml"
GROUNDING_DINO_CONFIG = "grounding_dino/groundingdino/config/GroundingDINO_SwinT_OGC.py"
GROUNDING_DINO_CHECKPOINT = "gdino_checkpoints/groundingdino_swint_ogc.pth"
BOX_THRESHOLD = 0.35
TEXT_THRESHOLD = 0.25
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
OUTPUT_DIR = Path("outputs/grounded_sam2_local_demo")
DUMP_JSON_RESULTS = True# create output directory
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

加载 SAM2 模型,获得 sam2_predictor,即:

# build SAM2 image predictor
sam2_checkpoint = SAM2_CHECKPOINT
model_cfg = SAM2_MODEL_CONFIG
sam2_model = build_sam2(model_cfg, sam2_checkpoint, device=DEVICE)
sam2_predictor = SAM2ImagePredictor(sam2_model)

加载 GroundingDINO 模型,获得 grounding_model,即:

# build grounding dino model
grounding_model = load_model(model_config_path=GROUNDING_DINO_CONFIG, model_checkpoint_path=GROUNDING_DINO_CHECKPOINT,device=DEVICE
)

SAM2 加载图像数据,即:

text = TEXT_PROMPT
img_path = IMG_PATH# image(原图), image_transformed(正则化图像)
image_source, image = load_image(img_path)
sam2_predictor.set_image(image_source)

GroudingDINO 预测 Bounding Box,输入模型、图像、文本、Box和Text阈值,即:

  • load_image()predict() 都来自于 GroundingDINO,数据和模型匹配。
boxes, confidences, labels = predict(model=grounding_model,image=image,caption=text,box_threshold=BOX_THRESHOLD,text_threshold=TEXT_THRESHOLD,
)

适配不同 Box 的格式:

h, w, _ = image_source.shape
boxes = boxes * torch.Tensor([w, h, w, h])
input_boxes = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()

SAM2 依赖的 PyTorch 配置:

# FIXME: figure how does this influence the G-DINO model
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()if torch.cuda.get_device_properties(0).major >= 8:# turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = True

SAM2 预测图像:

masks, scores, logits = sam2_predictor.predict(point_coords=None,point_labels=None,box=input_boxes,multimask_output=False,
)

后处理预测结果:

"""
Post-process the output of the model to get the masks, scores, and logits for visualization
"""
# convert the shape to (n, H, W)
if masks.ndim == 4:masks = masks.squeeze(1)confidences = confidences.numpy().tolist()
class_names = labelsclass_ids = np.array(list(range(len(class_names))))labels = [f"{class_name} {confidence:.2f}"for class_name, confidencein zip(class_names, confidences)
]

输出结果可视化:

"""
Visualize image with supervision useful API
"""
img = cv2.imread(img_path)
detections = sv.Detections(xyxy=input_boxes,  # (n, 4)mask=masks.astype(bool),  # (n, h, w)class_id=class_ids
)box_annotator = sv.BoxAnnotator()
annotated_frame = box_annotator.annotate(scene=img.copy(), detections=detections)label_annotator = sv.LabelAnnotator()
annotated_frame = label_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels)
cv2.imwrite(os.path.join(OUTPUT_DIR, "groundingdino_annotated_image.jpg"), annotated_frame)
plt.figure(figsize=(9, 6))
plt.title(f"annotated_frame")
plt.imshow(annotated_frame[:,:,::-1])mask_annotator = sv.MaskAnnotator()
annotated_frame = mask_annotator.annotate(scene=annotated_frame, detections=detections)
cv2.imwrite(os.path.join(OUTPUT_DIR, "grounded_sam2_annotated_image_with_mask.jpg"), annotated_frame)
plt.figure(figsize=(9, 6))
plt.title(f"annotated_frame")
plt.imshow(annotated_frame[:,:,::-1])

GroundingDINO 的 Box 效果,准确检测出 袜子 和 吉他,两类实体:

Box

SAM2 的分割效果,如下:
Seg

转换成 COCO 数据格式:

def single_mask_to_rle(mask):rle = mask_util.encode(np.array(mask[:, :, None], order="F", dtype="uint8"))[0]rle["counts"] = rle["counts"].decode("utf-8")return rleif DUMP_JSON_RESULTS:# convert mask into rle formatmask_rles = [single_mask_to_rle(mask) for mask in masks]input_boxes = input_boxes.tolist()scores = scores.tolist()# save the results in standard formatresults = {"image_path": img_path,"annotations" : [{"class_name": class_name,"bbox": box,"segmentation": mask_rle,"score": score,}for class_name, box, mask_rle, score in zip(class_names, input_boxes, mask_rles, scores)],"box_format": "xyxy","img_width": w,"img_height": h,}with open(os.path.join(OUTPUT_DIR, "grounded_sam2_local_image_demo_results.json"), "w") as f:json.dump(results, f, indent=4)

相关文章:

Vision - 开源视觉分割算法框架 Grounded SAM2 配置与推理 教程 (1)

欢迎关注我的CSDN:https://spike.blog.csdn.net/ 本文地址:https://spike.blog.csdn.net/article/details/143388189 免责声明:本文来源于个人知识与公开资料,仅用于学术交流,欢迎讨论,不支持转载。 Ground…...

DAY21|二叉树Part08|LeetCode: 669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树

目录 LeetCode: 669. 修剪二叉搜索树 基本思路 C代码 LeetCode: 108.将有序数组转换为二叉搜索树 基本思路 C代码 LeetCode: 538.把二叉搜索树转换为累加树 基本思路 C代码 LeetCode: 669. 修剪二叉搜索树 力扣代码链接 文字讲解:LeetCode: 669. 修剪二叉搜…...

在gitlab,把新分支替换成master分支

1、备份master分支,可以打tag 2、删除master分支 正常情况下,master分支不允许删除,需要做两个操作才能删除 a、变更项目默认分支为非master分支,可以先随便选择 b、取消master为非保护分支 操作了上述两步,就可以删…...

使用 Spring Boot 集成 Thymeleaf 和 Flying Saucer 实现 PDF 导出

在 Spring Boot 项目中,生成 PDF 报表或发票是常见需求。本文将介绍如何使用 Spring Boot 集成 Thymeleaf 模板引擎和 Flying Saucer 实现 PDF 导出,并提供详细的代码实现和常见问题解决方案。 目录 一、项目依赖二、创建 Thymeleaf 模板三、创建 PDF 生…...

web——upload1——攻防世界

第一次做木马题目,有点懵逼,浮现一下做题思路 可以上传一个文件,通过学习学习到了一句话木马 一句话木马: 利用文件上传漏洞,往目标网站中上传一句话木马,然后你就可以在本地通过中国菜刀chopper.exe即可…...

nginx 搭建网站

1.查看防火墙状态systemctl status firewalld 2.getenforce 3.安装nginx yum install nginx -y 4.网站信息 echo "welcome to yinchuankejixuanyuan" > /usr/share/nginx/html/index.html 5.查看命令状态 nginx -t 6.重启 systemctl restart nginx...

Java基础-Java中的常用类(上)

(创作不易,感谢有你,你的支持,就是我前行的最大动力,如果看完对你有帮助,请留下您的足迹) 目录 String类 创建字符串 字符串长度 连接字符串 创建格式化字符串 String 方法 System类 常用方法 方…...

气压仪器智能打气泵方案芯片SIC8833

智能打气泵方案最开始是机械式的开发,后来慢慢地演变成由一个气缸、压力传感器和主控芯片的开发的PCBA方案,它具备小体积、智能数显、预设胎压、动态测量、精准压力检测以及过充过放等功能。 其方案设计原理是利用主控芯片和压力传感器的组合设计&#x…...

软件测试(系统测试)的定位和专业:完善产品;专业;非助手;自动化

软件测试(系统测试)的定位 在研发流程的后端,测试并非无中生有的创举,而是从既有基础(即“1”)出发,致力于推动产品向更高层次(即从“1”到“100”)的跃升与完善。在这一…...

2024 CSS保姆级教程四

CSS中的动画 CSS动画(CSS Animations)是为层叠样式表建议的允许可扩展标记语言(XML)元素使用CSS的动画的模块​ 即指元素从一种样式逐渐过渡为另一种样式的过程​ 常见的动画效果有很多,如平移、旋转、缩放等等&#…...

PostgreSQL技术内幕17:PG分区表

文章目录 0.简介1.概念介绍2.分区表技术产生的背景3.分区类型及使用方式4.实现原理4.1 分区表创建4.2 分区表查询4.3 分区表写入4.4 分区表删除 0.简介 本文主要介绍PG中分区表的概念,产生分区表技术的原因,使用方式和其内部实现原理,旨在能…...

群控系统服务端开发模式-应用开发-上传工厂开发

现在的文件、图片等上传基本都在使用oss存储。而现在常用的oss存储有阿里云、腾讯云、七牛云、华为云等,但是用的最多的还是前三种。而我主要封装的是本地存储、阿里云存储、腾讯云存储、七牛云存储。废话不多说,直接上传设计图及说明,就一目…...

【Docker系列】指定系统平台拉取 openjdk:8 镜像

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…...

语音识别:docker部署FunASR以及springboot集成funasr

内容摘选自: https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_offline_zh.md FunASR FunASR是一个基础语音识别工具包,提供多种功能,包括语音识别(ASR)、语音端点检测(VAD&#xf…...

Rust项目结构

文章目录 一、module模块1.文件内的module 二、模块化项目结构1.关于module2.各个模块之间互相引用 三、推荐项目结构1.实例 参考 一、module模块 1.文件内的module 关键字:mod 引入模块中的方法 usemod名字:方法名usemod名字.*写全路径 二、模块化项…...

计算并联电阻的阻值

计算并联电阻的阻值 C语言代码C代码Java代码Python代码 💐The Begin💐点点关注,收藏不迷路💐 对于阻值为r1和r2的电阻,其并联电阻阻值公式计算如下: R1/(1/r11/r2) 输入 两个电阻阻抗大小,浮…...

MySQL符号类型(详细)

在 MySQL 中,符号可以分为几种主要类型,以下是所有符号类型的小写分类: 1. 占位符 ?:用于准备语句中的占位符,表示将来要替换的值。 2. 分隔符 ;:表示 sql 语句的结束。 ,:用于分隔列、值或…...

Angular引用控件类

说明: angular 在一个控件类里面,引入另外一个控件类,这样做的好处,就是代码分离,当你一个页面存在多少类似于独立的界面时,可以使用这种方式,分离代码 更好维护程序 效果图: step…...

stm32 踩坑笔记

串口问题: 问题:会改变接收缓冲的下一个字节 串口的初始化如下,位长度选择了9位。因为要奇偶校验,要选择9位。但是接收有用数据只用到1个字节。 问题原因: 所以串口接收时会把下一个数据更改...

文件上传和文件包含

声明: 本文章只是适用于网络安全教学,请自觉遵守网络安全法,严禁用于非法途径,若读者做出来任何危害网络安全的行为,后果自负,均与本人无关. 文件上传: 大部分的网站和应用系统都有上传的功能,如用户头像上传,图片上传,文档上传…...

突破不可导策略的训练难题:零阶优化与强化学习的深度嵌合

强化学习(Reinforcement Learning, RL)是工业领域智能控制的重要方法。它的基本原理是将最优控制问题建模为马尔可夫决策过程,然后使用强化学习的Actor-Critic机制(中文译作“知行互动”机制),逐步迭代求解…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了:一行…...

Java 8 Stream API 入门到实践详解

一、告别 for 循环&#xff01; 传统痛点&#xff1a; Java 8 之前&#xff0c;集合操作离不开冗长的 for 循环和匿名类。例如&#xff0c;过滤列表中的偶数&#xff1a; List<Integer> list Arrays.asList(1, 2, 3, 4, 5); List<Integer> evens new ArrayList…...

23-Oracle 23 ai 区块链表(Blockchain Table)

小伙伴有没有在金融强合规的领域中遇见&#xff0c;必须要保持数据不可变&#xff0c;管理员都无法修改和留痕的要求。比如医疗的电子病历中&#xff0c;影像检查检验结果不可篡改行的&#xff0c;药品追溯过程中数据只可插入无法删除的特性需求&#xff1b;登录日志、修改日志…...

vue3 字体颜色设置的多种方式

在Vue 3中设置字体颜色可以通过多种方式实现&#xff0c;这取决于你是想在组件内部直接设置&#xff0c;还是在CSS/SCSS/LESS等样式文件中定义。以下是几种常见的方法&#xff1a; 1. 内联样式 你可以直接在模板中使用style绑定来设置字体颜色。 <template><div :s…...

【决胜公务员考试】求职OMG——见面课测验1

2025最新版&#xff01;&#xff01;&#xff01;6.8截至答题&#xff0c;大家注意呀&#xff01; 博主码字不易点个关注吧,祝期末顺利~~ 1.单选题(2分) 下列说法错误的是:&#xff08; B &#xff09; A.选调生属于公务员系统 B.公务员属于事业编 C.选调生有基层锻炼的要求 D…...

【JavaSE】绘图与事件入门学习笔记

-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角&#xff0c;以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向&#xff0c;距离坐标原点x个像素;第二个是y坐标&#xff0c;表示当前位置为垂直方向&#xff0c;距离坐标原点y个像素。 坐标体系-像素 …...

IT供电系统绝缘监测及故障定位解决方案

随着新能源的快速发展&#xff0c;光伏电站、储能系统及充电设备已广泛应用于现代能源网络。在光伏领域&#xff0c;IT供电系统凭借其持续供电性好、安全性高等优势成为光伏首选&#xff0c;但在长期运行中&#xff0c;例如老化、潮湿、隐裂、机械损伤等问题会影响光伏板绝缘层…...

tree 树组件大数据卡顿问题优化

问题背景 项目中有用到树组件用来做文件目录&#xff0c;但是由于这个树组件的节点越来越多&#xff0c;导致页面在滚动这个树组件的时候浏览器就很容易卡死。这种问题基本上都是因为dom节点太多&#xff0c;导致的浏览器卡顿&#xff0c;这里很明显就需要用到虚拟列表的技术&…...

算法笔记2

1.字符串拼接最好用StringBuilder&#xff0c;不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...