ここまでの経過:
$ source \[venv のパス\]/venv/bin/activate
(venv) $ python
>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> TRAIN_DATA_URL = \
'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz'
>>> data_root_orig = \
tf.keras.utils.get_file(origin=TRAIN_DATA_URL, fname='flower_photos', untar=True)
>>> import pathlib
>>> data_root = pathlib.Path(data_root_orig)
>>> all_image_paths = list(data_root.glob('*/*'))
>>> all_image_paths = [str(path) for path in all_image_paths]
>>> label_names = \
... sorted(item.name for item in data_root.glob('*/') if item.is_dir())
>>> label_to_index = \
... dict((name, index) for index,name in enumerate(label_names))
>>> all_image_labels = \
... [label_to_index[pathlib.Path(path).parent.name] for path in all_image_paths]
データの画像は,サイズがまちまちである。
モデルに合わせて,これらを 192x192 にリサイズする。
さらに,画素値の範囲 0〜255 を,0〜1 に変換する。
この内容を,つぎの画像を例にして示す:
>>> img_path = all_image_paths[0]
>>> label = all_image_labels[0]
>>> img_path
'/home/[user name]/.keras/datasets/flower_photos/roses/3624546109_8eb98f0cdb.jpg'
この画像の生データ(註):
>>> img_raw = tf.io.read_file(img_path)
>>> print(repr(img_raw)[:100]+"...")
>>
テンソルにデコード(註)
>>> img_tensor = tf.image.decode_jpeg(img_raw)
>>> print(img_tensor.shape)
(332, 500, 3)
>>> print(img_tensor.dtype)
192x192 にリサイズ(註):
>>> img_final = tf.image.resize(img_tensor, [192, 192])
>>> print(img_final.shape)
(192, 192, 3)
normalize to [0,1] range:
>>> img_final = img_final/255.0
>>> print(img_final.numpy().min())
0.0013071845
>>> print(img_final.numpy().max())
0.99999994
以上のプロセスを,関数にまとめる:
>>> def raw_to_tensor(path):
... image_raw = tf.io.read_file(path)
... return tf.image.decode_image(image_raw, channels=3)
...
>>> def load_and_preprocess_image(path):
... img_tensor = raw_to_tensor(path)
... img_final = tf.image.resize(img_tensor, [192, 192])
... img_final /= 255.0
... return image
...
実際,
img_path = all_image_paths[0]
→ img_raw
→ img_tensor
→ img_final
のプロセスは,つぎの表現にまとまる:
>>> img_final = load_and_preprocess_image( all_image_paths[0] )
註. |
python を起動して「import tensorflow as tf」とした後に「tf.enable_eager_execution()」 を実行していないと,つぎのようになる:
|
>>> img_raw = tf.io.read_file(img_path)
>>> print(repr(img_raw)[:100]+"...")
...
>>> img_tensor = tf.image.decode_image(img_raw)
>>> print(img_tensor.shape)
>>> img_final = tf.image.resize(img_tensor, [192, 192])
File "", line 1, in
File "/home/pi/venv/lib/python3.7/site-packages/
tensorflow_core/python/ops/image_ops_impl.py",
line 1226, in resize_images
skip_resize_if_same=True)
File "/home/pi/venv/lib/python3.7/site-packages/
tensorflow_core/python/ops/image_ops_impl.py",
line 1073, in _resize_images_common
raise ValueError('\'images\' contains no shape.')
ValueError: 'images' contains no shape.
|