当前位置:网站首页>PyTorch中的一些常见数据类型转换方法,与list和np.ndarray的转换方法
PyTorch中的一些常见数据类型转换方法,与list和np.ndarray的转换方法
2022-04-23 06:11:00 【小风_】
目录
0.导包
import torch
import numpy as np
import PIL
1.tensor类型转换
# 设置Torch默认类型
torch.set_default_tensor_type(torch.FloatTensor)
# CPU GPU # 数据类型
# torch.FloatTensor torch.cuda.FloatTensor # 32位浮点数
# torch.DoubleTensor torch.cuda.DoubleTensor # 64位浮点数
# torch.cuda.HalfTensor # 16位浮点数
# 类型转换
tensor = torch.rand(1,3,224,224)
tensor = tensor.float() # 转为float类型,其他:half() int() double() char() byte() short() long()
tensor = tensor.cuda() # 转为GPU对象
tensor = tensor.cpu() # 转为CPU对象
# type_as()方法
tensor1 = torch.rand(2,3)
tensor2 = torch.IntTensor(2,3)
tensor3 = tensor1.type_as(tensor2) # 将tensor1转为tensor2的类型
# print(tensor1,tensor2,tensor3)
2.tensor和list转换
'''tensor和list转换'''
tensor1 = torch.ones([1,5]) # 创建一个1x5的单位张量
list1 = tensor1.tolist() # tensor -> list
tensor1 = torch.tensor(list1) # list -> tensor
3.tensor和np.ndarray转换
'''tensor和np.ndarray转换'''
ndarray = tensor.numpy() # 注意GPU对象要先转为CPU对象
tensor = torch.from_numpy(ndarray) # 注意一般转为浮点数对象
4.图像tensor和图像ndarray转换,tensor -> cv2
'''图像tensor和图像ndarray转换,tensor -> cv2'''
# tensor的图像是维度信息是[N, C, H, W]
ndarray = np.random.random((3,224,224))
tensor = torch.tensor(ndarray).permute(2,0,1) #ndarray转tensor图像要注意维度是HWC->CHW
img = tensor.permute(1,2,0).cpu().numpy() #反之同理
5.cv2(ndarray)与PIL之间的转换
'''PIL.Image和np.ndarray转换,也可是cv2与PIL之间的转换'''
path = '1.jpg' #这里传入自己的图像地址
ndarray = np.asarray(PIL.Image.open(path)) #Image转ndarray
img = PIL.Image.fromarray(ndarray.astype(np.uint8)) #ndarray转Image
版权声明
本文为[小风_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_33952811/article/details/124293373
边栏推荐
- Component learning (2) arouter principle learning
- error 403 In most cases, you or one of your dependencies are requesting解决
- iTOP4412 HDMI显示(4.0.3_r1)
- [多屏互动] 实现双多屏异显二:startActivity方式
- Record WebView shows another empty pit
- MySQL5.7插入中文数据,报错:`Incorrect string value: ‘\xB8\xDF\xAE\xF9\x80 at row 1`
- [recommendation of new books in 2021] practical IOT hacking
- 常用UI控件简写名
- GEE配置本地开发环境
- 【2021年新书推荐】Professional Azure SQL Managed Database Administration
猜你喜欢
随机推荐
Bottomsheetdialogfragment conflicts with listview recyclerview Scrollview sliding
MySQL notes 2_ data sheet
Component learning
iTOP4412无法显示开机动画(4.0.3_r1)
Antd Design Form表单检验
DCMTK (dcm4che) works together with dicoogle
MySQL notes 3_ Restraint_ Primary key constraint
組件化學習
Component based learning (1) idea and Implementation
iTOP4412 FramebufferNativeWindow(4.0.3_r1)
iTOP4412内核反复重启
项目,怎么打包
Itop4412 HDMI display (4.0.3_r1)
Android room database quick start
最简单完整的libwebsockets的例子
扫雷小游戏
机器学习 三: 基于逻辑回归的分类预测
C# EF mysql更新datetime字段报错Modifying a column with the ‘Identity‘ pattern is not supported
[2021 book recommendation] artistic intelligence for IOT Cookbook
基于BottomNavigationView实现底部导航栏