torchvision.transforms - Torchvision 0.10.0 documentation

[예시코드]

dataset = dset.ImageFolder(root=dataroot,
                           transform=transforms.Compose([
                               transforms.Resize(image_size),
                               transforms.CenterCrop(image_size),
                               transforms.ToTensor(),
                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
                           ]))

# to scrips the transformations
transforms = torch.nn.Sequential(
     transforms.CenterCrop(10),
     transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
 )
scripted_transforms = torch.jit.script(transforms)

<aside> 💡 shape Tensor Image shape: (C, H, W) Batch of Tensor Images shape: (B, C, H, W) values Tensor images with a float dtype : values in [0, 1) Tensor images with an integer dtype : have values in [0, MAX_DTYPE] MAX_DTYPE : largest value that can be represented in that dtype

</aside>

v0.8.0부터 모든 random transformations들은 sample random parameters를 사용하기 위해 torch default random generator를 사용

# 이전버전
import random
random.seed(12)
# 0.8.0 이후
import torch
torch.manual_seed(12)

torchvision.transforms.Compose(transforms)

parameter transforms는 Transform객체들의 list이다.

이 Transform 들은 PIL이미지와 torch.Tensor 형식의 이미지에 적용될 수 있다.

자주 사용되는 transform들

torchvision.transform.CenterCrop(size) : 중심을 기준으로 size만큼의 크기로 크롭(size: (h, w)또는 int형. int형 또는 크기가 1인 sequence로 입력시 (size[0], size[0])으로 해석된다)

torchvision.transforms.Resize(size, interpolation <InterpolationMode.BILINEAR: 'bilinear'>, max_size=None, antialias=None) : 주어진 사이즈로 resize size : 원하는 output size. (h, w)로 주어지면 output size 는 이것에 맞춰짐. size가 int면, smaller edge of the image 가 이 숫자에 맞춰짐. i.e, if height > width, then image will be rescaled to (size * height / width, size).

torchvision.transforms.Normalize(mean, std, inplace=False) : 평균과 표준편자 입력에 따라 normalize. PIL이미지에는 적용되지 않는다 mean : (mean[1], mean[2], mean[3], ..., mean[n]) std : (std[1], std[2], ..., std[n]) n은 채널. 채널별로 평균과 표준편차 지정해주는 것. output[channel] = (input[channel] - mean[channel]) / std[channel]

torchvision.transforms.ToTensor() : PIL이미지나 numpy.ndarray를 tensor로 바꾸어준다. torchscript는 지원하지 않는다. [0,255]의 값 범위를 갖고 (H, W, C) 형식을 갖는 PIL image 또는 numpy.ndarray → (C, H, W) 형식을 갖고 [0.0, 1.0]의 범위를 갖는 torch.FloatTensor 단, PIL이미지라면 one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)여야 하고, numpy.ndarray라면 np.uint8 의 dtype을 가져야한다. 다른 경우라면 scaling없이 tensor가 리턴된다.