api查询

记录自己常用API Demo

Tensor PIL Numpy图片编码互转

To Tensor

1
2
3
4
5
# PIL->Tensor 0-1
PIL_img=Image.open('palette.png').convert('RGB')
tensor_img=torchvision.transforms.functional.to_tensor(PIL_img)
#Numpy->Tensor
tensor_im=torch.from_numpy(numpy_img)

To PIL

1
2
3
4
5
# Tensor->PIL
from torchvision.transforms import ToPILImage
PIL_Img=ToPILImage()(tensor_img)
# Numpy->PIL
PIL_img = Image.fromarray(numpy_img.astype('uint8')).convert('RGB')

To Numpy

1
2
3
4
# PIL->Numpy 0-255
numpy_img = np.array(PIL_img)
# Tensor->Numpy
numpy_img = tensor_img.numpy()
  • PIL: Width Height
  • numpy: Height Width Channel(128,128,3)
  • tensor: Channel Height Width
  • tf_tensor:[b, c, h, w]
  • torch_tensor:[b, h, w, c]

输出大小

1
2
3
4
5
6
7
numpy_img.shape -->(128,128,3)
PIL_img.size -->(128,128)
tensor_img.shape -->torch.Size([3, 128, 128])
tensor_img.size() -->torch.Size([3, 128, 128])
如果对你有帮助,请赏包辣条