Python

tensor - numpy - PILImage 변환

qlsenddl 2020. 12. 4. 19:23
728x90

1. from numpy to tensor

tensor_data = torch.from_numpy(numpy_data)


ex>

a = np.array([1.,2.])

print(type(a))

>> <class 'numpy.ndarray'>

print(a)

>> [1. 2.]

b = torch.from_numpy(a).float()

print(type(b))

>> <class 'torch.Tensor'>

print(b)

>> tensor([1., 2.])


2. from tensor to numpy

numpy_data = tensor_data.numpy()


ex>

a = torch.tensor([1, 2])

print(type(a))

>> <class 'torch.Tensor'>

print(a)

>> tensor([1, 2])

b = a.numpy()

print(type(b))

>> <class 'numpy.ndarray'>

print(b)

>> [1 2]


3. from tensor to PILImage

torchvision에서 transforms를 import한 후(import torchvision.transforms as transforms)

trans = transforms.ToPILImage() 정의해서 사용

image_data = trans(tensor_data)


ex>

import torchvision.transforms as transforms


trans = transforms.ToPILImage()

a = torch.tensor([[1.,2.], [3.,4.]])

print(type(a))

>> <class 'torch.Tensor'>

b = trans(a)

print(type(b))

>> <class 'PIL.Image.Image'>


4. from PILImage to tensor

torchvision에서 transforms를 import한 후(import torchvision.transforms as transforms)

trans = transforms.ToTensor() 정의해서 사용

tensor_data = trans(image_data)


ex>

import torchvision.transforms as transforms

from PIL import Image


trans = transforms.ToTensor()

a = Image.open("C:/Users/user/Desktop/test.png")

print(type(a))

>> <class 'PIL.PngImagePlugin.PngImageFile'>

b = trans(a)

print(type(b))

>> <class 'torch.Tensor'>


5. from PILImage to numpy

numpy_data = np.array(image_data)


ex>

from PIL import Image


a = Image.open("C:/Users/user/Desktop/test.png")

print(type(a))

>> <class 'PIL.PngImagePlugin.PngImageFile'>

b = np.array(a)

print(type(b))

>> <class 'numpy.ndarray'>


6. from numpy to PILImage

image_data = Image.fromarray(np.uint8(numpy_data))


ex>

from PIL import Image


a = np.array([[1., 2.], [3., 4.]])

print(type(a))

>> <class 'numpy.ndarray'>

b = Image.fromarray(np.uint8(a))

print(type(b))

>> <class 'PIL.Image.Image'>

728x90