pytorch_13_pytorch 中tensor,numpy,PIL的转换

PIL:使用Python自带图像处理库读取出来的图片格式
numpy:使用Python-opencv库读取出来的图片格式
tensor:pytorch中训练时所采取的向量格式
import torch
import torchvision.transforms as transforms 

PIL  to Tensor

1 def PIL2tensor(img):
2     loader = transforms.Compose([
3         transforms.ToTensor()
4     ])
5     image = loader(img).unsqueeze(0)
6     return image.to(torch.device,torch.float)

Tensor to PIL

1 def tensor2PIL(tensor): # 将tensor-> PIL
2     unloader = transforms.ToPILImage()
3     image = tensor.cpu().clone()
4     image = image.squeeze(0)
5     image = unloader(image)
6     return image

Tensor to numpy

1 def tensor2numpy(tensor):
2     img = tensor.mul(255).byte()
3     img = img.cpu().numpy().squeeze(0).tranpose((1,2,0))
4     return img

numpy to tensor

    if isinstance(pic,np.ndarray):
        img = torch.from_numpy(pic.transpose((2,0,1)))
        return img.float().div(255)

  

猜你喜欢

转载自www.cnblogs.com/shuangcao/p/11930743.html