Загрузка изображений в каталог в виде набора данных Tensorflow
Я относительно новичок в ML и очень новичок в TensorfFlow. Я потратил немало времени на учебник TensorFlow MINST, а также https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/how_tos/reading_data, чтобы попытаться выяснить, как читать мои собственные данные, но я немного запутался.
У меня есть куча изображений (.png) в каталоге /images/ 0_Non/. Я пытаюсь сделать их в наборе данных TensorFlow, поэтому я могу в основном запустить материал из учебника MINST на нем в качестве первого прохода.
import tensorflow as tf
# Make a queue of file names including all the JPEG images files in the relative image directory.
filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once("../images/0_Non/*.png"))
image_reader = tf.WholeFileReader()
# Read a whole file from the queue, the first returned value in the tuple is the filename which we are ignoring.
_, image_file = image_reader.read(filename_queue)
image = tf.image.decode_png(image_file)
# Start a new session to show example output.
with tf.Session() as sess:
# Required to get the filename matching to run.
tf.initialize_all_variables().run()
# Coordinate the loading of image files.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
# Get an image tensor and print its value.
image_tensor = sess.run([image])
print(image_tensor)
# Finish off the filename queue coordinator.
coord.request_stop()
coord.join(threads)
У меня проблемы с пониманием того, что происходит здесь. Итак, кажется, что image
является тензором, а image_tensor
является массивом numpy?
Как получить мои изображения в наборе данных? Я также пробовал следовать примеру Iris, который для CSV привел меня сюда: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/base.py, но не был уверен, как получить это для моего случая, когда у меня есть куча png.
Спасибо!
Ответы
Ответ 1
Недавно добавленный API tf.data
позволяет сделать это проще:
import tensorflow as tf
# Make a Dataset of file names including all the PNG images files in
# the relative image directory.
filename_dataset = tf.data.Dataset.list_files("../images/0_Non/*.png")
# Make a Dataset of image tensors by reading and decoding the files.
image_dataset = filename_dataset.map(lambda x: tf.decode_png(tf.read_file(x)))
# NOTE: You can add additional transformations, like
# 'image_dataset.batch(BATCH_SIZE)' or 'image_dataset.repeat(NUM_EPOCHS)'
# in here.
iterator = image_dataset.make_one_shot_iterator()
next_image = iterator.get_next()
# Start a new session to show example output.
with tf.Session() as sess:
try:
while True:
# Get an image tensor and print its value.
image_array = sess.run([next_image])
print(image_tensor)
except tf.errors.OutOfRangeError:
# We have reached the end of 'image_dataset'.
pass
Обратите внимание, что для обучения вам нужно будет где-то получить ярлыки. Преобразование Dataset.zip()
- это возможный способ объединения image_dataset
с набором меток из другого источника.
Ответ 2
Вам может понадобиться этот ответ, но этот урок мне очень помог. https://www.tensorflow.org/tutorials/load_data/images