프로젝트/코드프레소 체험단

이미지 데이터 처리를 위한 CNN 완벽 가이드 - DataAugmentation

KimCookieYa 2022. 3. 14. 17:07

overfitting

- train 데이터가 실제 부딪힐 수 있는 모든 상황의 데이터를 갖지 못해 발생

 

Augmentation : 기존의 이미지 데이터를 조금 변형시키는 것

 - train 데이터에 약간의 변형을 가해, 데이터의 분포를 다양하게 만든다.

 

ImageDataGenerator 객체 생성

 - Image Data Augmentation을 위한 다양한 설정정보 지정

 - rotation_range : 랜덤하게 사진을 회전시킬 각도 범위

 - width_shift_range/height_shift_range : 사진을 수평과 수직으로 랜덤하게 평행 이동시킬 범위

 - shear_range : 랜덤하게 전단 변환을 적용할 각도 범위

 - zoom_range : 랜덤하게 사진을 확대할 범위

 - horizontal_flip : 랜덤하게 이미지를 수평으로 뒤집음

 - fill_mode : 회전이나 가로/세로 이동으로 인해 새롭게 생성해야 할 픽셀을 채울 전략

 

import tensorflow as tf
from tensorflow import keras

import os
import matplotlib.pyplot as plt

url = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
path_to_zip = keras.utils.get_file(fname='cats_and_dogs_filtered.zip', origin=url, extract=True, cache_dir='/content')

cats_dir = '/content/datasets/cats_and_dogs_filtered/train/cats'

from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rotation_range=40,
                             width_shift_range=0.2,
                             height_shift_range=0.2,
                             shear_range=0.2,
                             zoom_range=0.2,
                             horizontal_flip=True,
                             fill_mode='nearest')

from tensorflow.keras.preprocessing import image

def image_augmentation_plot(img_path):
  # 이미지를 읽고 크기를 변경
  img = image.load_img(img_path, target_size=(150, 150))

  # (150, 150, 3) 크기의 넘파이 배열로 변환
  x = image.img_to_array(img)

  # (1, 150. 150. 3) 크기로 변환
  x = x.reshape((1,) + x.shape)

  # flow() 메서드는 랜덤하게 변환된 이미지의 배치를 생성
  # 무한 반복되기 때문에 어느 지점에서 중지해야 함
  i = 0
  for batch in datagen.flow(x, batch_size=1):
    plt.figure(i)
    imgplot = plt.imshow(image.array_to_img(batch[0]))
    i += 1
    if i % 4 == 0:
      break
  plt.show()

fnames = sorted([os.path.join(cats_dir, fname) for fname in os.listdir(cats_dir)])

image_augmentation_plot(fnames[0])