当前位置: 首页 > 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;专为自动驾驶车载芯片设计。该框架主要包…...

IGF-I Analog ;CYAAPLKPALSSC

一、基础信息多肽名称&#xff1a;IGF-I Analog 胰岛素样生长因子 I 类似物 三字母序列&#xff1a;Cys-Tyr-Ala-Ala-Pro-Leu-Lys-Pro-Ala-Lys-Ser-Cys 单字母序列&#xff1a;CYAAPLKPALSSC 氨基酸数量&#xff1a;12 aa 结构修饰&#xff1a;分子内二硫键 二硫键配对&#xf…...

告别单调仪表盘:用LVGL Gauge控件打造一个智能家居温湿度监控界面(ESP32实战)

智能家居温湿度监控实战&#xff1a;用LVGL打造动态仪表盘 在智能家居系统中&#xff0c;实时监控环境参数是基础但关键的功能。传统数字显示虽然精确&#xff0c;但缺乏直观性&#xff1b;而精心设计的仪表盘不仅能提升用户体验&#xff0c;还能通过视觉反馈快速传达环境状态。…...

TEdit地图编辑器:10倍效率打造你的泰拉瑞亚梦想世界

TEdit地图编辑器&#xff1a;10倍效率打造你的泰拉瑞亚梦想世界 【免费下载链接】Terraria-Map-Editor TEdit - Terraria Map Editor - TEdit is a stand alone, open source map editor for Terraria. It lets you edit maps just like (almost) paint! It also lets you chan…...

上午题_程序设计语言

编译程序和解释程序...

三维动画课程期末复盘:从零搭建我的马卡龙童话游乐场✨

当我按下 3ds Max 的渲染按钮&#xff0c;看着浅蓝的摩天轮缓缓转动、粉白的旋转木马跟着节奏起舞、淡紫色热气球轻轻飘动时&#xff0c;我才真正意识到&#xff1a;为期一学期的三维动画课程&#xff0c;就这样在我的指尖落下了帷幕。从刚打开软件连工具栏都认不全的 “小白”…...

Windows 11任务栏拖放功能终极修复指南:3步恢复高效操作体验

Windows 11任务栏拖放功能终极修复指南&#xff1a;3步恢复高效操作体验 【免费下载链接】Windows11DragAndDropToTaskbarFix "Windows 11 Drag & Drop to the Taskbar (Fix)" fixes the missing "Drag & Drop to the Taskbar" support in Windows…...

osModa:基于NixOS与AI智能体的下一代服务器操作系统

1. 项目概述&#xff1a;为AI智能体而生的操作系统如果你和我一样&#xff0c;长期在服务器运维和AI应用部署的一线摸爬滚打&#xff0c;那你一定对这样的场景深有体会&#xff1a;凌晨三点&#xff0c;手机突然响起刺耳的告警&#xff0c;你睡眼惺忪地爬起来&#xff0c;SSH连…...

视频对象移除与背景修复:时空联合建模实战指南

1. 项目概述&#xff1a;让AI“脑补”被遮挡的画面&#xff0c;不是魔法&#xff0c;是空间-时间联合建模的落地“This AI takes a video and fills the missing pixels behind an object!”——这句话乍看像科幻预告片里的旁白&#xff0c;但其实它精准指向一个正在快速成熟的…...

通用汽车IT部门裁员600人,为AI人才腾空间,软件团队变革进行时

通用汽车IT部门裁员600人&#xff0c;AI人才成新宠 通用汽车证实已对其IT部门进行裁员&#xff0c;约600名领薪员工&#xff08;占比10%以上&#xff09;被裁&#xff0c;目的是清除专业知识不再适用的员工&#xff0c;为具有AI背景的人员腾出空间。公司表示这是面向未来做好准…...

AI赋能医院物流:基于PDCA循环的智能供应链韧性提升实践

1. 项目概述&#xff1a;当医院物流遇上AI与PDCA医院物流&#xff0c;听起来可能有点“幕后”&#xff0c;但它绝对是现代医疗体系顺畅运转的“大动脉”。从高值耗材、药品、检验试剂&#xff0c;到被服布草、医疗废物&#xff0c;甚至是一日三餐&#xff0c;这条链条上任何一个…...