pytorch学习笔记——数据类型的转化

参考链接:
https://mp.weixin.qq.com/s/yz8l54VusPWmF6dWkYL1VA
https://zhuanlan.zhihu.com/p/87441580
https://www.jb51.net/article/177575.htm

1、np.ndarray与PIL.Image的转换

image = PIL.Image.fromarray(ndarray.astype(uint8))

ndarray = np.asarray(PIL.Image.open(path))

2、PIL.Image转Opencv

image = cv2.cvtColor(numpy.asarray(PIL.Image.open(path)),cv2.COLOR_RGB2BGR)

image = PIL.Image.fromarray(cv2.cvtColor((cv2.imread(path),cv2.COLOR_BGR2RGB))

3、torch.Tensor与np.ndarray转换

ndarray = tensor.cpu().numpy()

tensor = torch.from_numpy(ndarray).float()

tensor = torch.from_numpy(ndarray.copy()).float() # If ndarray has negative stride.

4、torch.tensor与PIL.Image转换

# pytorch中的张量默认采用[N, C, H, W]的顺序,并且数据范围在[0,1],需要进行转置和规范化
# torch.Tensor -> PIL.Image
image = PIL.Image.fromarray(torch.clamp(tensor*255, min=0, max=255).byte().permute(1,2,0).cpu().numpy())
image = torchvision.transforms.functional.to_pil_image(tensor)  # Equivalently way

# PIL.Image -> torch.Tensor
path = r'./figure.jpg'
tensor = torch.from_numpy(np.asarray(PIL.Image.open(path))).permute(2,0,1).float() / 255
tensor = torchvision.transforms.functional.to_tensor(PIL.Image.open(path)) # Equivalently way

在这里插入图片描述

5、tensor张量与list相互转换

tensor转list

a = torch.ones([1,5])
# tensor([[1., 1., 1., 1., 1.]])
b = a.tolist()
# [[1.0, 1.0, 1.0, 1.0, 1.0]]

list转tensor

a=list(range(1,6))
# [1, 2, 3, 4, 5]
b=torch.tensor(a)
# tensor([1, 2, 3, 4, 5])

6、tensor张量常见类型转换

tensor = torch.Tensor(3, 5)

# torch.long() 将tensor投射为long类型
newtensor = tensor.long()

# torch.half()将tensor投射为半精度浮点类型
newtensor = tensor.half()

# torch.int()将该tensor投射为int类型
newtensor = tensor.int()

# torch.double()将该tensor投射为double类型
newtensor = tensor.double()

# torch.float()将该tensor投射为float类型
newtensor = tensor.float()

# torch.char()将该tensor投射为char类型
newtensor = tensor.char()

# torch.byte()将该tensor投射为byte类型
newtensor = tensor.byte()

# torch.short()将该tensor投射为short类型
newtensor = tensor.short()

7、torchvision.transforms.ToTensor(ndarry/PIL)

注意: 这种转化方式会将数据归一化,不过cv2.imshow()显示图片时会自动将归一化的像素值乘以255,自己之前将经过ToTensor归一化的像素值直接乘以255再输入给imshow函数结果都是白色,原来imshow函数内部判断数据类型是float32会自己处理。

8、为什么pytorch中transforms.ToTorch要把(H,W,C)的矩阵转为(C,H,W)?

https://www.zhihu.com/question/310094451

因为pytorch很多函数都是设计成假设你的输入是 (c,h,w)的格式,当然你如果不嫌麻烦的话可以每次要用这些函数的时候转成chw格式,但我想这会比你输入的时候就转成chw要麻烦很多至于为什么pytorch选择设计成chw而不是hwc(毕竟传统的读图片的函数opencv的cv2.imread或者sklearn的imread都是读成hwc的格式的)这点确实比较令初学者困惑。个人感觉是因为pytorch做矩阵加减乘除以及卷积等运算是需要调用cuda和cudnn的函数的,而这些接口都设成成chw格式了,故而pytorch为了方便起见也设计成chw格式了那新问题就来了,cuda和cudnn为什么设计成chw格式呢?我想这是由于涉及到图片操作的都是和卷积相关的,而内部做卷积运算的加速设计成chw在操作上会比hwc处理起来更容易,更快。题主如果想进一步了解可以google一下cudnn的卷积实现。

9、cv2.imshow()显示图片时会自动匹配数据类型

对于imshow函数,opencv的官方注释指出:根据图像的深度,imshow函数会自动对其显示灰度值进行缩放,规则如下:

1.如果图像数据类型是8U(8位无符号),则直接显示。
2.如果图像数据类型是16U(16位无符号)或32S(32位有符号整数),则imshow函数内部会自动将每个像素值除以256并显示,即将原图像素值的范围由[0255*256]映射到[0255]
3.如果图像数据类型是32F(32位浮点数)或64F(64位浮点数),则imshow函数内部会自动将每个像素值乘以255并显示,即将原图像素值的范围由[01]映射到[0255](注意:原图像素值必须要归一化)
Opencv中的imshow函数详解

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pytorch是机器学习中的一个重要框架,它与TensorFlow一起被认为是机器学习的两大框架。Pytorch学习可以从以下几个方面入手: 1. Pytorch基本语法:了解Pytorch的基本语法和操作,包括张量(Tensors)的创建、导入torch库、基本运算等\[2\]。 2. Pytorch中的autograd:了解autograd的概念和使用方法,它是Pytorch中用于自动计算梯度的工具,可以方便地进行反向传播\[2\]。 3. 使用Pytorch构建一个神经网络:学习使用torch.nn库构建神经网络的典型流程,包括定义网络结构、损失函数、反向传播和更新网络参数等\[2\]。 4. 使用Pytorch构建一个分类器:了解如何使用Pytorch构建一个分类器,包括任务和数据介绍、训练分类器的步骤以及在GPU上进行训练等\[2\]。 5. Pytorch的安装:可以通过pip命令安装Pytorch,具体命令为"pip install torch torchvision torchaudio",这样就可以在Python环境中使用Pytorch了\[3\]。 以上是一些关于Pytorch学习笔记,希望对你有帮助。如果你需要更详细的学习资料,可以参考引用\[1\]中提到的网上帖子,或者查阅Pytorch官方文档。 #### 引用[.reference_title] - *1* [pytorch自学笔记](https://blog.csdn.net/qq_41597915/article/details/123415393)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Pytorch学习笔记](https://blog.csdn.net/pizm123/article/details/126748381)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值