[Deeplearning] 이미지 데이터 증강(Augmentation) - Pytorch transforms 정리

2023. 1. 11. 15:28·공부정리/Deep learnig & Machine learning
728x90
반응형

 

 

 

 

파이토치 데이터증강

[데이터 증강]Pytorch transform(변형)종류 살펴보고 이미지 증강 처리¶

In [ ]:
import torch
torch.cuda.is_available()
Out[ ]:
True
In [ ]:
torch.__version__
Out[ ]:
'1.12.1+cu116'

transforms.Grayscale(num_output_channels=1) - grayscale로 변환한다.

transforms.ColorJitter() - 색을 바꾼다.

transforms.RandomAffine(degrees, translate) - 랜덤으로 affine 변형을 한다. 회전, 이동을 함

transforms.RandomCrop(size, scale, ratio) -이미지를 랜덤으로 아무데나 잘라 size 크기로 출력한다.

transforms.Resize(size) - 이미지 사이즈를 size로 변경한다

transforms.RandomRotation(degrees) 이미지를 랜덤으로 degrees 각도로 회전한다.

transforms.RandomResizedCrop(size, scale, ratio) - 이미지를 랜덤으로 변형한다.

transforms.RandomVerticalFlip(p=0.5) - 이미지를 랜덤으로 수직으로 뒤집는다. p =0이면 뒤집지 않는다.

transforms.RandomHorizontalFlip(p=0.5) - 이미지를 랜덤으로 수평으로 뒤집는다.

transforms.RandomApply([transforms, p=0.3) - transform함수를 p확률 만큼 적용한다.

transforms.ToTensor() - 이미지 데이터를 tensor로 바꿔준다.

transforms.Normalize(mean, std, inplace=False) - 이미지를 정규화한다.

In [ ]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

import matplotlib.pyplot as plt
import numpy as np

import warnings
warnings.filterwarnings('ignore')

device = 'cuda' if torch.cuda.is_available() else 'cpu'
torch.manual_seed(777)
Out[ ]:
<torch._C.Generator at 0x7f08281493f0>
In [ ]:
train_set = torchvision.datasets.CIFAR100(
    root = './data',
    train = True,
    download = True,
    transform = transforms.Compose([
        transforms.ToTensor() # 데이터를 0에서 255까지 있는 값을 0에서 1사이 값으로 변환
    ])
)

train_loader = torch.utils.data.DataLoader(train_set, batch_size=16)
Files already downloaded and verified
In [ ]:
for i in train_loader:
    s = 1
    plt.figure(figsize=(16,10))
    for img in i[0][:4]:
        plt.subplot(1, int(len(i[0])/4), s)
        plt.imshow(np.transpose(img, (1,2,0)))
        s = s + 1
    break
plt.show()
In [ ]:
def plottransform(transform):
  train_set = torchvision.datasets.CIFAR100(
    root = './data',
    train = True,
    download = True,
    transform = transforms.Compose([
        transforms.ToTensor() # 데이터를 0에서 255까지 있는 값을 0에서 1사이 값으로 변환
    ])
  )

  train_loader = torch.utils.data.DataLoader(train_set, batch_size=4)

  test_set = torchvision.datasets.CIFAR100(
    root = './data',
    train = True,
    download = True,
    transform = transforms.Compose([
        transforms.ToTensor(),
        transform
    ])
  )

  test_loader = torch.utils.data.DataLoader(test_set, batch_size=4)

  plt.figure(figsize=(16,10))
  for i in train_loader:
      s = 1
      for img in i[0]:
          plt.subplot(2, len(i[0]), s)
          plt.imshow(np.transpose(img, (1,2,0)))
          s = s + 1
      break
  for i in test_loader:
      for img in i[0]:
          plt.subplot(2, len(i[0]), s)
          plt.imshow(np.transpose(img, (1,2,0)))
          s = s + 1
      break
  plt.show()
In [ ]:
 
In [ ]:
plottransform(transforms.CenterCrop(10))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomCrop(10))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.Resize(100))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomResizedCrop(50))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomResizedCrop(30))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomResizedCrop(10, scale=(0.08, 1.0), ratio=(0.75, 1.3333333333333333)))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomAffine((-90,90), translate=(0.2, 0.2)))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomAffine((-90,90), translate=(0.2, 0.2), scale=(0.8, 2)))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomRotation(90))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomVerticalFlip(p=0.5))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.RandomHorizontalFlip(p=0.5))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
# brightness 밝기, contrast 대조, saturation 채도, hue 색조
plottransform(torchvision.transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
plottransform(transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]))
Files already downloaded and verified
Files already downloaded and verified
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
In [ ]:
plottransform(transforms.RandomApply([transforms.RandomAffine((-90,90), translate=(0.5, 0.5))], p=0.3))
Files already downloaded and verified
Files already downloaded and verified
In [ ]:
 
728x90
반응형

'공부정리 > Deep learnig & Machine learning' 카테고리의 다른 글

[Deeplearning] LSTM Networks  (0) 2023.01.16
[Deeplearning] RNN Model  (0) 2023.01.16
[Deeplearning] 작물 잎 사진으로 질병 분류하기 (2) - Pytorch  (0) 2023.01.10
[Deeplearning] 작물 잎 사진으로 질병 분류하기 (1) 베이스라인 설계- Pytorch  (0) 2023.01.10
[딥러닝] 밑바닥부터 시작하는 딥러닝 2 - Chapter 1 신경망 복습 (1)  (0) 2022.09.16
'공부정리/Deep learnig & Machine learning' 카테고리의 다른 글
  • [Deeplearning] LSTM Networks
  • [Deeplearning] RNN Model
  • [Deeplearning] 작물 잎 사진으로 질병 분류하기 (2) - Pytorch
  • [Deeplearning] 작물 잎 사진으로 질병 분류하기 (1) 베이스라인 설계- Pytorch
sillon
sillon
꾸준해지려고 합니다..
    반응형
  • sillon
    sillon coding
    sillon
  • 전체
    오늘
    어제
    • menu (614)
      • notice (2)
      • python (68)
        • 자료구조 & 알고리즘 (23)
        • 라이브러리 (19)
        • 기초 (8)
        • 자동화 (14)
        • 보안 (1)
      • coding test - python (301)
        • Programmers (166)
        • 백준 (76)
        • Code Tree (22)
        • 기본기 문제 (37)
      • coding test - C++ (5)
        • Programmers (4)
        • 백준 (1)
        • 기본기문제 (0)
      • 공부정리 (5)
        • 신호처리 시스템 (0)
        • Deep learnig & Machine lear.. (41)
        • Data Science (18)
        • Computer Vision (17)
        • NLP (40)
        • Dacon (2)
        • 모두를 위한 딥러닝 (강의 정리) (4)
        • 모두의 딥러닝 (교재 정리) (9)
        • 통계 (2)
      • HCI (23)
        • Haptics (7)
        • Graphics (11)
        • Arduino (4)
      • Project (21)
        • Web Project (1)
        • App Project (1)
        • Paper Project (1)
        • 캡스톤디자인2 (17)
        • etc (1)
      • OS (10)
        • Ubuntu (9)
        • Rasberry pi (1)
      • App & Web (9)
        • Android (7)
        • javascript (2)
      • C++ (5)
        • 기초 (5)
      • Cloud & SERVER (8)
        • Git (2)
        • Docker (1)
        • DB (4)
      • Paper (7)
        • NLP Paper review (6)
      • 데이터 분석 (0)
        • GIS (0)
      • daily (2)
        • 대학원 준비 (0)
      • 영어공부 (6)
        • job interview (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    Python
    programmers
    소수
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
sillon
[Deeplearning] 이미지 데이터 증강(Augmentation) - Pytorch transforms 정리
상단으로

티스토리툴바