tensor、numpy以及PIL的转换
作者:互联网
tensor、numpy以及PIL的转换
numpy转为tensor
使用torch.from_numpy( )
,就可以完成转换。不过若是对numpy进行操作的时候,tensor的内容也会改变。
import torch
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(type(a)) # <class 'numpy.ndarray'>
print(type(b)) # <class 'torch.Tensor'>
tensor转为numpy
使用torch.numpy()
将Tensor转为Numpy
**一定要注意Tensor大小写!**最重要的区别t.Tensor
和t.tensor
:不论输入的类型是什么,t.tensor()
都会进行数据拷贝,不会共享内存;t.Tensor()
与Numpy共享内存,但当Numpy的数据类型和Tensor的类型不一样的时候,数据会被复制,不会共享内存。
import torch
import numpy as np
a = np.ones(5) # <class 'numpy.ndarray'>
b = torch.from_numpy(a) # <class 'torch.Tensor'>
print(type(a))
print(type(b))
PIL转tensor
from torchvision import transforms
def PIL_to_tensor(image):
loader = transforms.Compose([transforms.ToTensor()])
image = loader(image).unsqueeze(0)
# return image.to(device, torch.float)
return image
tensor转PIL
def tensor_to_PIL(tensor):
unloader = transforms.ToPILImage()
image = tensor.cpu().clone()
image = image.squeeze(0)
image = unloader(image)
return image
标签:PIL,tensor,image,torch,numpy,Tensor 来源: https://blog.csdn.net/qq_50722269/article/details/122418524