torchvision은 MNIST, CIFAR-10/100, ImageNet, COCO처럼 바로 쓸 수 있는 데이터셋과 변환 파이프라인을 제공해. 현재 권장 API는 torchvision.transforms.v2야. 기존의 torchvision.transforms도 작동하지만 새 코드에는 v2를 사용해.
왜 v2가 중요할까?
tv_tensors(이미지, BoundingBoxes, 마스크, Video)를 기본 지원해. 탐지와 분할 작업에 특히 중요해.
이미지, 경계 상자, 마스크 같은 여러 입력에 같은 변환을 정확히 적용해. 예를 들어 셋을 한 번에 같은 각도로 회전할 수 있어.
흔한 연산을 새로 구현해 이전 버전보다 훨씬 빠른 경우가 많아.
PIL 이미지 변환과 텐서 변환의 역할을 깔끔하게 나눠.
표준 전처리 순서
ImageNet으로 사전 학습된 모델을 다룰 때 다음 구성을 계속 만나게 될 거야:
ToImage(): 입력을 v2 기본 형식인 tv_tensor.Image로 감싸.
ToDtype(torch.float32, scale=True): 값을 [0, 1] 범위의 float32로 바꿔.
Resize(256): 짧은 변의 길이를 256으로 맞춰.
CenterCrop(224): 중앙의 224x224 영역을 잘라.
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): ImageNet 통계로 정규화해. 이 값은 기억해 두는 게 좋아.
import torch
import torchvision.transforms.v2 as T
# This is the chain that matches every torchvision pretrained model
preprocess = T.Compose([
T.ToImage(),
T.ToDtype(torch.float32, scale=True),
T.Resize(256),
T.CenterCrop(224),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
# But the modern recommended way is to ASK the model for its transforms:
from torchvision.models import resnet50, ResNet50_Weights
weights = ResNet50_Weights.IMAGENET1K_V2
preprocess = weights.transforms()
# weights.transforms() returns the EXACT preprocessing the model was trained with
v2의 핵심 장점: 여러 입력 변환·python
import torch
import torchvision.transforms.v2 as T
from torchvision import tv_tensors
# A scene with image + bounding boxes + segmentation mask
img = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8)
boxes = tv_tensors.BoundingBoxes(
[[10, 20, 100, 150]], format='XYXY', canvas_size=(224, 224)
)
mask = tv_tensors.Mask(torch.zeros(224, 224, dtype=torch.uint8))
transform = T.Compose([
T.RandomHorizontalFlip(p=1.0),
T.RandomRotation(15),
])
# Apply to all three at once — boxes and mask transform consistently with image
img_t, boxes_t, mask_t = transform(img, boxes, mask)
print(img_t.shape, boxes_t, mask_t.shape)
# This was nearly impossible with the old transforms API.