Tensorflow Dataset
Oxford IIIT Pet 데이터¶
from pathlib import Path
import tensorflow as tf
from PIL import Image
# 최초 실행 시 Oxford IIIT Pet 원본 이미지와 마스크 압축파일을 내려받습니다.
cache = Path.home() / '.keras' / 'datasets' / 'oxford-iiit-pet'
cache.mkdir(parents=True, exist_ok=True)
for name in ('images', 'annotations'):
tf.keras.utils.get_file(
fname=f'{name}.tar.gz',
origin=f'https://www.robots.ox.ac.uk/~vgg/data/pets/data/{name}.tar.gz',
cache_dir=str(cache), cache_subdir='', extract=True)
# Keras 버전에 따라 압축 해제 디렉터리의 이름이 다를 수 있습니다.
image_dir = next(p for p in cache.rglob('images') if p.is_dir())
mask_dir = next(p for p in cache.rglob('trimaps') if p.is_dir())
img_files = sorted(image_dir.glob('*.jpg'))
mask_by_stem = {p.stem: p for p in mask_dir.glob('*.png')}
pairs = [(p, mask_by_stem[p.stem]) for p in img_files if p.stem in mask_by_stem]
assert pairs, '이미지와 마스크 쌍이 없습니다.'
print(f'파일 쌍: {len(pairs)}')
for image_path, mask_path in pairs:
assert image_path.stem == mask_path.stem
from pathlib import Path
import tensorflow as tf
from PIL import Image
# 최초 실행 시 Oxford IIIT Pet 원본 이미지와 마스크 압축파일을 내려받습니다.
cache = Path.home() / '.keras' / 'datasets' / 'oxford-iiit-pet'
cache.mkdir(parents=True, exist_ok=True)
for name in ('images', 'annotations'):
tf.keras.utils.get_file(
fname=f'{name}.tar.gz',
origin=f'https://www.robots.ox.ac.uk/~vgg/data/pets/data/{name}.tar.gz',
cache_dir=str(cache), cache_subdir='', extract=True)
# Keras 버전에 따라 압축 해제 디렉터리의 이름이 다를 수 있습니다.
image_dir = next(p for p in cache.rglob('images') if p.is_dir())
mask_dir = next(p for p in cache.rglob('trimaps') if p.is_dir())
img_files = sorted(image_dir.glob('*.jpg'))
mask_by_stem = {p.stem: p for p in mask_dir.glob('*.png')}
pairs = [(p, mask_by_stem[p.stem]) for p in img_files if p.stem in mask_by_stem]
assert pairs, '이미지와 마스크 쌍이 없습니다.'
bad = []
valid_pairs = []
for image_path, mask_path in pairs:
try:
with Image.open(image_path) as image:
if image.mode != 'RGB':
bad.append(image_path.stem)
continue
image.verify()
valid_pairs.append((image_path, mask_path))
except (OSError, ValueError):
bad.append(image_path.stem)
print(f'RGB 이미지 {len(valid_pairs)}개, 제외 {len(bad)}개')
assert valid_pairs
tf.Dataset¶
from pathlib import Path
import tensorflow as tf
from PIL import Image
# 최초 실행 시 Oxford IIIT Pet 원본 이미지와 마스크 압축파일을 내려받습니다.
cache = Path.home() / '.keras' / 'datasets' / 'oxford-iiit-pet'
cache.mkdir(parents=True, exist_ok=True)
for name in ('images', 'annotations'):
tf.keras.utils.get_file(
fname=f'{name}.tar.gz',
origin=f'https://www.robots.ox.ac.uk/~vgg/data/pets/data/{name}.tar.gz',
cache_dir=str(cache), cache_subdir='', extract=True)
# Keras 버전에 따라 압축 해제 디렉터리의 이름이 다를 수 있습니다.
image_dir = next(p for p in cache.rglob('images') if p.is_dir())
mask_dir = next(p for p in cache.rglob('trimaps') if p.is_dir())
img_files = sorted(image_dir.glob('*.jpg'))
mask_by_stem = {p.stem: p for p in mask_dir.glob('*.png')}
pairs = [(p, mask_by_stem[p.stem]) for p in img_files if p.stem in mask_by_stem]
assert pairs, '이미지와 마스크 쌍이 없습니다.'
bad = []
valid_pairs = []
for image_path, mask_path in pairs:
try:
with Image.open(image_path) as image:
if image.mode != 'RGB':
bad.append(image_path.stem)
continue
image.verify()
valid_pairs.append((image_path, mask_path))
except (OSError, ValueError):
bad.append(image_path.stem)
print(f'RGB 이미지 {len(valid_pairs)}개, 제외 {len(bad)}개')
assert valid_pairs
def transform(image_path, mask_path):
image = tf.image.decode_jpeg(tf.io.read_file(image_path), channels=3)
mask = tf.image.decode_png(tf.io.read_file(mask_path), channels=1)
image = tf.image.resize(image, (200, 200))
mask = tf.image.resize(mask, (200, 200), method='nearest')
return image, tf.cast(mask, tf.int32) - 1
# 실습에서는 유효한 파일 128쌍을 사용합니다.
selected = valid_pairs[:128]
dataset = tf.data.Dataset.from_tensor_slices((
[str(p[0]) for p in selected], [str(p[1]) for p in selected]))
tf_dataset = dataset.map(transform, num_parallel_calls=1)
for sample, target in tf_dataset.take(1):
assert sample.shape == (200, 200, 3)
assert target.shape == (200, 200, 1)
assert int(tf.reduce_min(target)) >= 0 and int(tf.reduce_max(target)) < 3
print(sample.shape, target.shape)
배치 생성¶
from pathlib import Path
import tensorflow as tf
from PIL import Image
# 최초 실행 시 Oxford IIIT Pet 원본 이미지와 마스크 압축파일을 내려받습니다.
cache = Path.home() / '.keras' / 'datasets' / 'oxford-iiit-pet'
cache.mkdir(parents=True, exist_ok=True)
for name in ('images', 'annotations'):
tf.keras.utils.get_file(
fname=f'{name}.tar.gz',
origin=f'https://www.robots.ox.ac.uk/~vgg/data/pets/data/{name}.tar.gz',
cache_dir=str(cache), cache_subdir='', extract=True)
# Keras 버전에 따라 압축 해제 디렉터리의 이름이 다를 수 있습니다.
image_dir = next(p for p in cache.rglob('images') if p.is_dir())
mask_dir = next(p for p in cache.rglob('trimaps') if p.is_dir())
img_files = sorted(image_dir.glob('*.jpg'))
mask_by_stem = {p.stem: p for p in mask_dir.glob('*.png')}
pairs = [(p, mask_by_stem[p.stem]) for p in img_files if p.stem in mask_by_stem]
assert pairs, '이미지와 마스크 쌍이 없습니다.'
bad = []
valid_pairs = []
for image_path, mask_path in pairs:
try:
with Image.open(image_path) as image:
if image.mode != 'RGB':
bad.append(image_path.stem)
continue
image.verify()
valid_pairs.append((image_path, mask_path))
except (OSError, ValueError):
bad.append(image_path.stem)
print(f'RGB 이미지 {len(valid_pairs)}개, 제외 {len(bad)}개')
assert valid_pairs
def transform(image_path, mask_path):
image = tf.image.decode_jpeg(tf.io.read_file(image_path), channels=3)
mask = tf.image.decode_png(tf.io.read_file(mask_path), channels=1)
image = tf.image.resize(image, (200, 200))
mask = tf.image.resize(mask, (200, 200), method='nearest')
return image, tf.cast(mask, tf.int32) - 1
# 실습에서는 유효한 파일 128쌍을 사용합니다.
selected = valid_pairs[:128]
dataset = tf.data.Dataset.from_tensor_slices((
[str(p[0]) for p in selected], [str(p[1]) for p in selected]))
tf_dataset = dataset.map(transform, num_parallel_calls=1)
batch_size = 32
for batch_data, batch_target in tf_dataset.batch(batch_size):
assert batch_data.shape[1:] == (200, 200, 3)
assert batch_target.shape[1:] == (200, 200, 1)
print(batch_data.shape, batch_target.shape)
배치별 소요 시간¶
from pathlib import Path
import tensorflow as tf
from PIL import Image
# 최초 실행 시 Oxford IIIT Pet 원본 이미지와 마스크 압축파일을 내려받습니다.
cache = Path.home() / '.keras' / 'datasets' / 'oxford-iiit-pet'
cache.mkdir(parents=True, exist_ok=True)
for name in ('images', 'annotations'):
tf.keras.utils.get_file(
fname=f'{name}.tar.gz',
origin=f'https://www.robots.ox.ac.uk/~vgg/data/pets/data/{name}.tar.gz',
cache_dir=str(cache), cache_subdir='', extract=True)
# Keras 버전에 따라 압축 해제 디렉터리의 이름이 다를 수 있습니다.
image_dir = next(p for p in cache.rglob('images') if p.is_dir())
mask_dir = next(p for p in cache.rglob('trimaps') if p.is_dir())
img_files = sorted(image_dir.glob('*.jpg'))
mask_by_stem = {p.stem: p for p in mask_dir.glob('*.png')}
pairs = [(p, mask_by_stem[p.stem]) for p in img_files if p.stem in mask_by_stem]
assert pairs, '이미지와 마스크 쌍이 없습니다.'
bad = []
valid_pairs = []
for image_path, mask_path in pairs:
try:
with Image.open(image_path) as image:
if image.mode != 'RGB':
bad.append(image_path.stem)
continue
image.verify()
valid_pairs.append((image_path, mask_path))
except (OSError, ValueError):
bad.append(image_path.stem)
print(f'RGB 이미지 {len(valid_pairs)}개, 제외 {len(bad)}개')
assert valid_pairs
def transform(image_path, mask_path):
image = tf.image.decode_jpeg(tf.io.read_file(image_path), channels=3)
mask = tf.image.decode_png(tf.io.read_file(mask_path), channels=1)
image = tf.image.resize(image, (200, 200))
mask = tf.image.resize(mask, (200, 200), method='nearest')
return image, tf.cast(mask, tf.int32) - 1
# 실습에서는 유효한 파일 128쌍을 사용합니다.
selected = valid_pairs[:128]
dataset = tf.data.Dataset.from_tensor_slices((
[str(p[0]) for p in selected], [str(p[1]) for p in selected]))
tf_dataset = dataset.map(transform, num_parallel_calls=1)
import time
import pandas as pd
results = {}
for batch_size in (1, 8, 32, 64):
start = time.perf_counter()
for images, masks in tf_dataset.batch(batch_size).prefetch(1):
_ = images.numpy(), masks.numpy()
results[batch_size] = time.perf_counter() - start
print(pd.DataFrame.from_dict(results, orient='index', columns=['소요 시간 (초)']).round(3))