0.导包
import torch
import numpy as np
import PIL
1.tensor类型转换
torch.set_default_tensor_type(torch.FloatTensor)
tensor = torch.rand(1,3,224,224)
tensor = tensor.float()
tensor = tensor.cuda()
tensor = tensor.cpu()
tensor1 = torch.rand(2,3)
tensor2 = torch.IntTensor(2,3)
tensor3 = tensor1.type_as(tensor2)
2.tensor和list转换
'''tensor和list转换'''
tensor1 = torch.ones([1,5])
list1 = tensor1.tolist()
tensor1 = torch.tensor(list1)
3.tensor和np.ndarray转换
'''tensor和np.ndarray转换'''
ndarray = tensor.numpy()
tensor = torch.from_numpy(ndarray)
4.图像tensor和图像ndarray转换,tensor -> cv2
'''图像tensor和图像ndarray转换,tensor -> cv2'''
ndarray = np.random.random((3,224,224))
tensor = torch.tensor(ndarray).permute(2,0,1)
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))
img = PIL.Image.fromarray(ndarray.astype(np.uint8))