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

python保存中间变量(学习笔记)

python保存中间变量

原因:

最近在部署dust3r算法,虽然在本地部署了,也能测试出一定的结果,但是发现无法跑很多图片,为了能够测试多张图片跑出来的模型,于是就在打算在autodl上部署算法,但是由于官方给定的代码是训练好模型后通过可视化三维模型的形式来给出的效果,所以在服务器上没有办法来可视化三维模型(可能有办法,但是总是有解决不了的报错,于是便放弃)

产生思路

打算把官方中的代码分成两部分,上部分是训练好的模型output变量,将output保存下来,下载到本地上,在本地上加载output变量,进而完成后续的代码操作。

保存中间变量的方式

通过下面方式output变量会以output.pkl的文件形式保存在当前文件夹下

import pickle
output=1 #这里就是要保存的中间变量
pickle.dump(output, open('output.pkl', 'wb'))

通过下面的方式来读取刚才保存的output.pkl文件,这样就可以顺利保存下来了

 f = open("output.pkl",'rb')output=pickle.loads(f.read())f.close()

原理

pickle是Python官方自带的库,提供dump函数实现Python对象的保存。支持自定义的对象,非常方便。Pandas的DataFrame和Obspy的Stream也都可以保存成pickle的格式。主要是以二进制的形式来保存成一种无逻辑的文件。

解决原来的问题

dust3r官方给的代码如下,其中服务器主要是在scene.show()这行代码中无法运行。

import osfrom dust3r.inference import inference, load_model
from dust3r.utils.image import load_images
from dust3r.image_pairs import make_pairs
from dust3r.cloud_opt import global_aligner, GlobalAlignerModeif __name__ == '__main__':model_path = "checkpoints/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth"device = 'cuda'batch_size = 4schedule = 'cosine'lr = 0.01niter = 100model = load_model(model_path, device)# load_images can take a list of images or a directory# base_dir = 'tankandtemples/tankandtemples/intermediate/M60/images/'base_dir = 'croco/assets/'# 获取当前目录下的所有文件files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]images = load_images(files, size=512)pairs = make_pairs(images, scene_graph='complete', prefilter=None, symmetrize=True)output = inference(pairs, model, device, batch_size=batch_size)# at this stage, you have the raw dust3r predictionsview1, pred1 = output['view1'], output['pred1']view2, pred2 = output['view2'], output['pred2']scene = global_aligner(output, device=device, mode=GlobalAlignerMode.PointCloudOptimizer)loss = scene.compute_global_alignment(init="mst", niter=niter, schedule=schedule, lr=lr)# retrieve useful values from scene:imgs = scene.imgsfocals = scene.get_focals()poses = scene.get_im_poses()pts3d = scene.get_pts3d()confidence_masks = scene.get_masks()# visualize reconstructionscene.show()# find 2D-2D matches between the two imagesfrom dust3r.utils.geometry import find_reciprocal_matches, xy_gridpts2d_list, pts3d_list = [], []for i in range(2):conf_i = confidence_masks[i].cpu().numpy()pts2d_list.append(xy_grid(*imgs[i].shape[:2][::-1])[conf_i])  # imgs[i].shape[:2] = (H, W)pts3d_list.append(pts3d[i].detach().cpu().numpy()[conf_i])reciprocal_in_P2, nn2_in_P1, num_matches = find_reciprocal_matches(*pts3d_list)print(f'found {num_matches} matches')matches_im1 = pts2d_list[1][reciprocal_in_P2]matches_im0 = pts2d_list[0][nn2_in_P1][reciprocal_in_P2]# visualize a few matchesimport numpy as npfrom matplotlib import pyplot as pln_viz = 10match_idx_to_viz = np.round(np.linspace(0, num_matches-1, n_viz)).astype(int)viz_matches_im0, viz_matches_im1 = matches_im0[match_idx_to_viz], matches_im1[match_idx_to_viz]H0, W0, H1, W1 = *imgs[0].shape[:2], *imgs[1].shape[:2]img0 = np.pad(imgs[0], ((0, max(H1 - H0, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)img1 = np.pad(imgs[1], ((0, max(H0 - H1, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)img = np.concatenate((img0, img1), axis=1)pl.figure()pl.imshow(img)cmap = pl.get_cmap('jet')for i in range(n_viz):(x0, y0), (x1, y1) = viz_matches_im0[i].T, viz_matches_im1[i].Tpl.plot([x0, x1 + W0], [y0, y1], '-+', color=cmap(i / (n_viz - 1)), scalex=False, scaley=False)pl.show(block=True)

将代码分成两部分,上部分由服务器来跑,下部分由本地来跑。

import os
from dust3r.inference import inference, load_model
from dust3r.utils.image import load_images
from dust3r.image_pairs import make_pairs
from dust3r.cloud_opt import global_aligner, GlobalAlignerMode
if __name__ == '__main__':model_path = "checkpoints/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth"device = 'cuda'batch_size = 32schedule = 'cosine'lr = 0.01niter = 300model = load_model(model_path, device)# load_images can take a list of images or a directorybase_dir = 'croco/assets/'# 获取当前目录下的所有文件files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]files_new = []for i in range(0,files.__len__(),10):files_new.append(files[i])images = load_images(files_new, size=512)pairs = make_pairs(images, scene_graph='complete', prefilter=None, symmetrize=True)output = inference(pairs, model, device, batch_size=batch_size)import picklepickle.dump(output, open('output.pkl', 'wb'))

本地代码

import os
from dust3r.inference import inference, load_model
from dust3r.utils.image import load_images
from dust3r.image_pairs import make_pairs
from dust3r.cloud_opt import global_aligner, GlobalAlignerMode
if __name__ == '__main__':model_path = "checkpoints/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth"device = 'cuda'batch_size = 1schedule = 'cosine'lr = 0.01niter = 300base_dir = 'croco/assets/'# 获取当前目录下的所有文件files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]files_new = []for i in range(0,files.__len__(),4):files_new.append(files[i])print(files_new)import picklef = open("output.pkl",'rb')output=pickle.loads(f.read())f.close()view1, pred1 = output['view1'], output['pred1']view2, pred2 = output['view2'], output['pred2']scene = global_aligner(output, device=device, mode=GlobalAlignerMode.PointCloudOptimizer)loss = scene.compute_global_alignment(init="mst", niter=niter, schedule=schedule, lr=lr)# retrieve useful values from scene:imgs = scene.imgsfocals = scene.get_focals()poses = scene.get_im_poses()pts3d = scene.get_pts3d()confidence_masks = scene.get_masks()# visualize reconstructionscene.show()# find 2D-2D matches between the two imagesfrom dust3r.utils.geometry import find_reciprocal_matches, xy_gridpts2d_list, pts3d_list = [], []for i in range(2):conf_i = confidence_masks[i].cpu().numpy()pts2d_list.append(xy_grid(*imgs[i].shape[:2][::-1])[conf_i])  # imgs[i].shape[:2] = (H, W)pts3d_list.append(pts3d[i].detach().cpu().numpy()[conf_i])reciprocal_in_P2, nn2_in_P1, num_matches = find_reciprocal_matches(*pts3d_list)print(f'found {num_matches} matches')matches_im1 = pts2d_list[1][reciprocal_in_P2]matches_im0 = pts2d_list[0][nn2_in_P1][reciprocal_in_P2]# visualize a few matchesimport numpy as npfrom matplotlib import pyplot as pln_viz = 10match_idx_to_viz = np.round(np.linspace(0, num_matches-1, n_viz)).astype(int)viz_matches_im0, viz_matches_im1 = matches_im0[match_idx_to_viz], matches_im1[match_idx_to_viz]H0, W0, H1, W1 = *imgs[0].shape[:2], *imgs[1].shape[:2]img0 = np.pad(imgs[0], ((0, max(H1 - H0, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)img1 = np.pad(imgs[1], ((0, max(H0 - H1, 0)), (0, 0), (0, 0)), 'constant', constant_values=0)img = np.concatenate((img0, img1), axis=1)pl.figure()pl.imshow(img)cmap = pl.get_cmap('jet')for i in range(n_viz):(x0, y0), (x1, y1) = viz_matches_im0[i].T, viz_matches_im1[i].Tpl.plot([x0, x1 + W0], [y0, y1], '-+', color=cmap(i / (n_viz - 1)), scalex=False, scaley=False)pl.show(block=True)

总结

这种解决办法也不是根本解决办法,虽然比较麻烦,但是还是能将项目跑起来,也是没有办法的办法,在此做一个笔记记录。

相关文章:

python保存中间变量(学习笔记)

python保存中间变量 原因: 最近在部署dust3r算法,虽然在本地部署了,也能测试出一定的结果,但是发现无法跑很多图片,为了能够测试多张图片跑出来的模型,于是就在打算在autodl上部署算法,但是由…...

CTF wed安全(攻防世界)练习题

一、Training-WWW-Robots 进入网站如图: 翻译:在这个小小的挑战训练中,你将学习Robots exclusion standard。网络爬虫使用robots.txt文件来检查它们是否被允许抓取和索引您的网站或只是其中的一部分。 有时这些文件会暴露目录结构&#xff0c…...

计算机网络链路层

数据链路 链路是从一个节点到相邻节点之间的物理线路(有线或无线) 数据链路是指把实现协议的软件和硬件加到对应链路上。帧是点对点信道的数据链路层的协议数据单元。 点对点信道 通信的主要步骤: 节点a的数据链路层将网络层交下来的包添…...

VUE3——reactive对比ref

从定义数据角度对比: 。ref用来定义:基本类型数据 。reactive用来定义:对象(或数组)类型数据。 。备注:ref也可以用来定义对象(或数组)类型数据,它内部会自动通过 reactive 转为代理对象。 从原理角度对比: 。ref通过 object.defineProperty()的 get 与set 来实现响应式(数据劫…...

广场舞团系统的设计与实现|Springboot+ Mysql+Java+ B/S结构(可运行源码+数据库+设计文档)

本项目包含可运行源码数据库LW,文末可获取本项目的所有资料。 推荐阅读100套最新项目持续更新中..... 2024年计算机毕业论文(设计)学生选题参考合集推荐收藏(包含Springboot、jsp、ssmvue等技术项目合集) 目录 1. 系…...

经典永不过时 Wordpress模板主题

经得住时间考验的模板,才是经典模板,带得来客户的网站,才叫NB网站。 https://www.jianzhanpress.com/?p2484...

QT布局管理和空间提升为和空间间隔

QHBoxLayout:按照水平方向从左到右布局; QVBoxLayout:按照竖直方向从上到下布局; QGridLayout:在一个网格中进行布局,类似于HTML的table; 基本布局管理类包括:QBoxLayout、QGridL…...

Yolo 自制数据集dect训练改进

上一文请看 Yolo自制detect训练-CSDN博客 简介 如下图: 首先看一下每个图的含义 loss loss分为cls_loss, box_loss, obj_loss三部分。 cls_loss用于监督类别分类,计算锚框与对应的标定分类是否正确。 box_loss用于监督检测框的回归,预测框…...

vlan间单臂路由

【项目实践4】 --vlan间单臂路由 一、实验背景 实验的目的是在一个有限的网络环境中实现VLAN间的通信。网络环境包括两个交换机和一个路由器,交换机之间通过Trunk链路相连,路由器则连接到这两个交换机的Trunk端口上。 二、案例分析 在网络工程中&#…...

day4 linux上部署第一个nest项目(java转ts全栈/3R教室)

背景:上一篇吧nest-vben-admin项目,再开发环境上跑通了,并且build出来了dist文件,接下来再部署到linux试试吧 dist文件夹是干嘛的? 一个pnpn install 直接生成了两个dist文件夹,前端admin项目一个&#xf…...

学会这几点,是搭建产品知识库的关键

现如今,企业都特别看重产品知识库,因为有了它,企业就能更好地管理产品信息,提升客户服务水平,还能帮企业做决策。但是,搭建一个好用、高效的产品知识库,也难倒了不少人。下面,我们一…...

MySql 常用的聚合函数总结

MySQL 中的聚合函数用于对一组数据进行计算,并返回单个值作为结果。以下是常用的 MySQL 聚合函数的总结及其功能描述: 1. COUNT() 功能:用于计算指定列或表中的行数。 语法: COUNT(*) COUNT(expression) 示例: SELECT …...

Charles for Mac 强大的网络调试工具

Charles for Mac是一款功能强大的网络调试工具,可以帮助开发人员和测试人员更轻松地进行网络通信测试和调试。以下是一些Charles for Mac的主要特点: 软件下载:Charles for Mac 4.6.6注册激活版 流量截获:Charles可以截获和分析通…...

【数据结构】优先级队列——堆

🧧🧧🧧🧧🧧个人主页🎈🎈🎈🎈🎈 🧧🧧🧧🧧🧧数据结构专栏🎈🎈🎈&…...

【力扣】45.跳跃游戏Ⅱ

45.跳跃游戏Ⅱ 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说&#xff0c;如果你在 nums[i] 处&#xff0c;你可以跳转到任意 nums[i j] 处: 0 < j < nums[i]i j < n 返回到达 n…...

containerd使用了解

containerd使用了解 yum安装 [rootvm ~]# curl -o /etc/yum.repos.d/docker.repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo [rootvm ~]# yum list | grep containerd containerd.io.x86_64 1.6.28-3.1.el7 doc…...

gateway 分发时若两个服务的路由地址一样,怎么指定访问想要的服务下的地址

1.思路 在使用Spring Cloud Gateway时&#xff0c;如果两个服务的路由地址相同&#xff0c;可以通过Predicate&#xff08;断言&#xff09;和Filter&#xff08;过滤器&#xff09;的组合来实现根据请求的不同条件将请求分发到不同的服务下的地址。 使用Predicate进行路由条件…...

【LeetCode】三月题解

文章目录 [2369. 检查数组是否存在有效划分](https://leetcode.cn/problems/check-if-there-is-a-valid-partition-for-the-array/)思路&#xff1a;代码&#xff1a; [1976. 到达目的地的方案数](https://leetcode.cn/problems/number-of-ways-to-arrive-at-destination/) 思路…...

云手机:实现便携与安全的双赢

随着5G时代的到来&#xff0c;云手机在各大游戏、直播和新媒体营销中扮演越来越重要的角色。它不仅节约了成本&#xff0c;提高了效率&#xff0c;而且在边缘计算和云技术逐渐成熟的背景下&#xff0c;展现出了更大的发展机遇。 云手机的便携性如何&#xff1f; 云手机的便携性…...

fast_bev学习笔记

目录 一. 简述二. 输入输出三. github资源四. 复现推理过程4.1 cuda tensorrt 版 一. 简述 原文:Fast-BEV: A Fast and Strong Bird’s-Eye View Perception Baseline FAST BEV是一种高性能、快速推理和部署友好的解决方案&#xff0c;专为自动驾驶车载芯片设计。该框架主要包…...

JavaSec-RCE

简介 RCE(Remote Code Execution)&#xff0c;可以分为:命令注入(Command Injection)、代码注入(Code Injection) 代码注入 1.漏洞场景&#xff1a;Groovy代码注入 Groovy是一种基于JVM的动态语言&#xff0c;语法简洁&#xff0c;支持闭包、动态类型和Java互操作性&#xff0c…...

零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?

一、核心优势&#xff1a;专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发&#xff0c;是一款收费低廉但功能全面的Windows NAS工具&#xff0c;主打“无学习成本部署” 。与其他NAS软件相比&#xff0c;其优势在于&#xff1a; 无需硬件改造&#xff1a;将任意W…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

Python:操作 Excel 折叠

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

系统设计 --- MongoDB亿级数据查询优化策略

系统设计 --- MongoDB亿级数据查询分表策略 背景Solution --- 分表 背景 使用audit log实现Audi Trail功能 Audit Trail范围: 六个月数据量: 每秒5-7条audi log&#xff0c;共计7千万 – 1亿条数据需要实现全文检索按照时间倒序因为license问题&#xff0c;不能使用ELK只能使用…...

mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包

文章目录 现象&#xff1a;mysql已经安装&#xff0c;但是通过rpm -q 没有找mysql相关的已安装包遇到 rpm 命令找不到已经安装的 MySQL 包时&#xff0c;可能是因为以下几个原因&#xff1a;1.MySQL 不是通过 RPM 包安装的2.RPM 数据库损坏3.使用了不同的包名或路径4.使用其他包…...

七、数据库的完整性

七、数据库的完整性 主要内容 7.1 数据库的完整性概述 7.2 实体完整性 7.3 参照完整性 7.4 用户定义的完整性 7.5 触发器 7.6 SQL Server中数据库完整性的实现 7.7 小结 7.1 数据库的完整性概述 数据库完整性的含义 正确性 指数据的合法性 有效性 指数据是否属于所定…...

NPOI操作EXCEL文件 ——CAD C# 二次开发

缺点:dll.版本容易加载错误。CAD加载插件时&#xff0c;没有加载所有类库。插件运行过程中用到某个类库&#xff0c;会从CAD的安装目录找&#xff0c;找不到就报错了。 【方案2】让CAD在加载过程中把类库加载到内存 【方案3】是发现缺少了哪个库&#xff0c;就用插件程序加载进…...

什么是VR全景技术

VR全景技术&#xff0c;全称为虚拟现实全景技术&#xff0c;是通过计算机图像模拟生成三维空间中的虚拟世界&#xff0c;使用户能够在该虚拟世界中进行全方位、无死角的观察和交互的技术。VR全景技术模拟人在真实空间中的视觉体验&#xff0c;结合图文、3D、音视频等多媒体元素…...