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)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/59218.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C++刷题】力扣-#697-数组的度

题目描述 给定一个非空且只包含非负数的整数数组 nums,数组的 度 的定义是指数组里任一元素出现频数的最大值。 你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。 示例 示例 1 输入:nums [1,2,2,3,1] 输出…

LocalDate 类常用方法详解(日期时间类)

LocalDate 类常用方法详解 LocalDate 是 Java 8 引入的日期时间API中的一个类,用于表示不含时间和时区的日期(年、月、日)。以下是一些常用的 LocalDate 方法: 创建 LocalDate 实例 now():获取当前日期 LocalDate t…

一些常用的react hooks以及各自的作用

一些常用的react hooks以及各自的作用 一、React Hooks是什么二、一些常用的Hooks以及各自的作用1、useState2、useEffect3、useContext4、useMemo5、useCallback6、useReducer7、useRef 一、React Hooks是什么 Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情…

不用买PSP,画质甚至更好,这款免费神器让你玩遍经典游戏

作为掌机游戏爱好者的福音,PPSSPP模拟器为玩家带来了前所未有的PSP游戏体验,彻底改变了掌机游戏的体验方式。这款精湛的软件不仅完美复刻了PSP主机的游戏体验,更通过先进的模拟技术,将经典游戏提升到了全新的高度。对于那些珍藏PS…

lua学习笔记---面向对象

在 Lua 中,封装主要通过元表(metatable)来实现。元表可以定义 __index、__newindex、__call 等元方法来控制对表的访问和赋值行为。 __index 元方法:当尝试访问一个不存在的键时,Lua 会查找元表的 __index 字段。如果 …

第15课 算法(下)

掌握冒泡排序、选择排序、插入排序、顺序查找、对分查找的的基本原理,并能使用这些算法编写简单的Python程序。 一、冒泡排序 1、冒泡排序的概念 冒泡排序是最简单的排序算法,是在一列数据中把较大(或较小)的数据逐次向右推移的…

golang通用后台管理系统03(登录校验,并生成token)

代码 package serviceimport ("fmt"//"fmt""gin/common""gin/config"sysEntity "gin/system/entity"sysUtil "gin/system/util""github.com/gin-gonic/gin""log" )func Login(c *gin.Contex…

Java环境下配置环境(jar包)并连接mysql数据库

目录 jar包下载 配置 简单连接数据库 一、注册驱动(jdk6以后会自动注册) 二、连接对应的数据库 以前学习数据库就只是操作数据库,根本不知道该怎么和软件交互,将存储的数据读到软件中去,最近学习了Java连接数据库…

快速遍历包含合并单元格的Word表格

Word中的合并表格如下,现在需要根据子类(例如:果汁)查找对应的品类,如果这是Excel表格,那么即使包含合并单元格,也很容易处理,但是使用Word VBA进行查找,就需要一些技巧。…

「C/C++」C/C++标准库 之 #include<ctime> 时间日期库

✨博客主页何曾参静谧的博客📌文章专栏「C/C」C/C程序设计📚全部专栏「VS」Visual Studio「C/C」C/C程序设计「UG/NX」BlockUI集合「Win」Windows程序设计「DSA」数据结构与算法「UG/NX」NX二次开发「QT」QT5程序设计「File」数据文件格式「PK」Parasoli…

写论文随想(整理我自己的感悟)(不断更新中,废案按照删除号标记)

写论文随想(整理我自己的感悟)(不断更新中,废案按照删除号标记) 论文的所有内容,都是为了服务于自己的创新点,只要整个文章围绕这个创新点讲好了,一篇自己满意的文章就成了。这也就是我现在的目…

使用wordcloud与jieba库制作词云图

目录 一、WordCloud库 例子: 结果: 二、Jieba库 两个基本方法 jieba.cut() jieba.cut_for_serch() 关键字提取: jieba.analyse包 extract_tags() 一、WordCloud库 词云图,以视觉效果提现关键词,可以过滤文本…

深入解析缓存模式下的数据一致性问题

今天,我们来聊聊常见的缓存模式和数据一致性问题。 常见的缓存模式有:Cache Aside、Read Through、Write Through、Write Back、Refresh Ahead、Singleflight。 缓存模式 Cache Aside 在 Cache Aside 模式中,是把缓存当做一个独立的数据源…

第四篇: 用Python和SQL在BigQuery中进行基础数据查询

用Python和SQL在BigQuery中进行基础数据查询 在大数据分析领域,Google BigQuery 提供了一种快速且经济高效的数据处理方式。对于想要使用SQL查询大规模数据的读者来说,BigQuery的公共数据集资源丰富、操作简便,是学习和实践SQL基础操作的理想…

Spring学习笔记_19——@PostConstruct @PreDestroy

PostConstruct && PreDestroy 1. 介绍 PostConstruct注解与PreDestroy注解都是JSR250规范中提供的注解。 PostConstruct注解标注的方法可以在创建Bean后在为属性赋值后,初始化Bean之前执行。 PreDestroy注解标注的方法可以在Bean销毁之前执行。 2. 依赖…

11.4模拟赛总结

文章目录 时间安排成绩反思 时间安排 7 : 40 − 8 : 00 7:40 - 8:00 7:40−8:00 开题。把题都看了一遍。 T 1 T1 T1 看起来有点神秘。 T 2 T2 T2 想很难的构造。 T 3 T3 T3 看起来像比较正常的计数题。 T 4 T4 T4 应该是扫描线 8 : 00 − 9 : 20 8:00 - 9:20 8:00−9:20 尝试…

ffmpeg视频滤镜:膨胀操作-dilation

滤镜介绍 dilation 官网链接 > FFmpeg Filters Documentation 膨胀滤镜会使图片变的更亮,会让细节别的更明显。膨胀也是形态学中的一种操作,在opencv中也有响应的算子。此外膨胀结合此前腐蚀操作,可以构成开闭操作。 开操作是先腐蚀…

多线程和线程同步基础篇学习笔记(Linux)

大丙老师教学视频:10-线程死锁_哔哩哔哩_bilibili 目录 大丙老师教学视频:10-线程死锁_哔哩哔哩_bilibili 线程概念 为什么要有线程 线程和进程的区别 在处理多任务的时候为什么线程数量不是越多越好? Linux提供的线程API 主要接口 线程创建 pth…

jeecgbootvue2菜单路由配置静态文件夹(public)下的html

需求:想要在菜单配置src/assets/iconfont/chart.html显示页面(目的是打包上线以后运维依然可以修改数据) 官网没有相关数据:菜单配置说明 JeecgBoot 开发文档 看云 问题现象: 我把文件放在src/assets/iconfont/chart.html然后在vue中作为 iframe 的 src 属性&am…

3种AI黑科技,让照片中的人物开口说话的简易方法,快进来学!

本文背景 用AI工作这么久了,我经常碰到各种关于AI的问题,比如制作让照片中人物开口说话的数字人。 很多小伙伴想知道是怎么弄的,不知从何下手。不过不用担心,今天就给大家带来三种实用的方法,快来一起试试吧。 首先是腾…