numpy与image互转,numpy和tensor互转 (np.array,Image.fromarray ,a.numpy, torch.from_numpy)

一、numpy与image互转

from PIL import Image  
import numpy as np
im = Image.open("a.jpg")
im.show() 
img = np.array(im)      # image类 转 numpy
img = img[:,:,0]        #第1通道
im=Image.fromarray(img) # numpy 转 image类
im.show() 

二、numpy和tensor互转

  • 我们很容易用numpy()和from_numpy()将Tensor和NumPy中的数组相互转换。但是需要注意的一点是:这两个函数所产生的的Tensor和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中一个时另一个也会改变!!!
  • 还有一个常用的将NumPy中的array转换成Tensor的方法就是torch.tensor(), 需要注意的是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的Tensor和原来的数据不再共享内存。
  • 所有在CPU上的Tensor(除了CharTensor)都支持与NumPy数组相互转换。

(1)tensor转numpy

1)使用numpy()将Tensor转换成NumPy数组
a = torch.ones(5)
b = a.numpy()
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
  • 输出
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

(2)numpy转tensor

1)使用from_numpy()将NumPy数组转换成Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
  • 输出
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)
2)用torch.tensor()将NumPy数组转换成Tensor
  • 需要注意的是该方法总是会进行数据拷贝,返回的Tensor和原来的数据不再共享内存。
c = torch.tensor(a)
a += 1
print(a, c)
  • 输出
[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)

三、参考

numpy与Image互转

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值