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'>
'Python' 카테고리의 다른 글
Pytorch 딥러닝 model 저장하기 (0) | 2020.12.22 |
---|---|
Matplotlib-pyplot(plt)로 Python에서 그래프 그리기 기본 (0) | 2020.12.20 |
Python os library에서 자주 쓰는 함수 정리 (0) | 2020.12.04 |
있어보이는 Python: map, lambda (0) | 2020.11.13 |
있어보이는 Python: try/except, enumerate (0) | 2020.11.09 |