PyTorch로 이미지 다루기

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

구름 데이터셋

구름 데이터셋 샘플: 다양한 구름 유형을 보여주는 다섯 이미지.

1 https://www.kaggle.com/competitions/cloud-type-classification2/data
PyTorch로 배우는 Intermediate Deep Learning

이미지란?

확대해 픽셀이 보이도록 일부를 확대한 구름 이미지.

  • 이미지는 픽셀(화소)로 구성됩니다
  • 각 픽셀에는 색상 정보가 있습니다

  • 그레이스케일: 0~255 정수

    • 30:

회색 상자

  • 컬러 이미지: 각 채널(빨강, 초록, 파랑)별 정수 3개
    • RGB = (52, 171, 235):

파란색 상자

PyTorch로 배우는 Intermediate Deep Learning

PyTorch로 이미지 로드하기

원하는 디렉터리 구조:

clouds_train

- cumulus
- 75cbf18.jpg - ...
- cumulonimbus - ...
clouds_test
- cumulus - cumulonimbus - ...

 

  • 최상위 폴더: clouds_train, clouds_test
  • 각 최상위 폴더 내부: 범주별 하위 폴더 1개씩
  • 각 클래스 폴더 내부: 이미지 파일
PyTorch로 배우는 Intermediate Deep Learning

PyTorch로 이미지 로드하기

from torchvision.datasets import ImageFolder
from torchvision import transforms


train_transforms = transforms.Compose([ transforms.ToTensor(), transforms.Resize((128, 128)), ])
dataset_train = ImageFolder( "data/clouds_train", transform=train_transforms, )
  • 변환 정의:

    • 텐서로 변환
    • 128x128로 리사이즈
  • 데이터셋 생성 시 전달:

    • 데이터 경로
    • 사전 정의한 변환
PyTorch로 배우는 Intermediate Deep Learning

이미지 표시

dataloader_train = DataLoader(
    dataset_train, 
    shuffle=True, 
    batch_size=1,
)

image, label = next(iter(dataloader_train))
print(image.shape)
torch.Size([1, 3, 128, 128])
image = image.squeeze().permute(1, 2, 0)
print(image.shape)
torch.Size([128, 128, 3])
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()

plt.show 출력의 구름 이미지

PyTorch로 배우는 Intermediate Deep Learning

데이터 증강

train_transforms = transforms.Compose([

transforms.RandomHorizontalFlip(), transforms.RandomRotation(45),
transforms.ToTensor(), transforms.Resize((128, 128)), ])
dataset_train = ImageFolder( "data/clouds/train", transform=train_transforms, )

데이터 증강: 원본 이미지에 무작위 변환을 적용해 데이터를 늘립니다

  • 학습 세트의 크기와 다양성 확대
  • 모델 견고성 향상
  • 과적합 감소

회전 변환을 보여 주는 세 장의 구름 이미지

PyTorch로 배우는 Intermediate Deep Learning

연습해 봅시다!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...