Convert cifar10 data to image files

  1. Download the cifar10 dataset
  2. Get the file name queue
  3. Read files from the file queue
  4. Start the filling queue thread
  5. Save the file as a picture
# copding:utf-8

import cifar10
import cifar10_input
# cifar10.py, cifar10_input.py are official documents
# Download address: https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10
import tensorflow as tf
import os
import scipy.misc


def inputs_origin(data_dir):
    filenames = [os.path.join(data_dir,'data_batch_%d.bin'% i) for i in range(1, 6)]
    #print(filenames)
    #['cifar10_data/cifar-10-batches-bin/data_batch_1.bin',
    #'cifar10_data/cifar-10-batches-bin/data_batch_2.bin',
    #'cifar10_data/cifar-10-batches-bin/data_batch_3.bin',
    #'cifar10_data/cifar-10-batches-bin/data_batch_4.bin',
    #'cifar10_data/cifar-10-batches-bin/data_batch_5.bin']

    for f in filenames:
        if not tf.gfile.Exists(f):
            raise ValueError('Failed to find file:' +f)
    # tf.train.string_input_producer tensorflow creates a file name queue
    filename_queue = tf.train.string_input_producer(filenames)
    # cifar10_input.read_cifar10 The program written in advance is a function to read files from the queue
    read_input = cifar10_input.read_cifar10(filename_queue)
    print(read_input)
    # Convert the picture to the form of real numbers
    reshape_image = tf.cast(read_input.uint8image, tf.float32)
    # print(reshape_image)
    # Tensor("Cast_1:0", shape=(32, 32, 3), dtype=float32)
    # The returned reshape_image is the tensor of a picture, and each time you use sess.run(reshape_image), a picture will be taken out
    return reshape_image

if __name__ =='__main__':
    # Modify the default address of the data set
    flag = tf.app.flags.FLAGS
    flag.data_dir ='cifar10_data'
    # Check whether the data set has been downloaded, skip if it has, and download the data if it is not
    cifar10.maybe_download_and_extract()

    if not os.path.exists('cifar10_pic/'):
        os.makedirs('cifar10_pic/')

    with tf.Session() as sess:
        reshape_image = inputs_origin('cifar10_data/cifar-10-batches-bin')
        # tf.train.start_queue_runners Start threads that fill the queue
        threads = tf.train.start_queue_runners(sess=sess)
        # Initialize variables
        sess.run(tf.global_variables_initializer())
        for i in range(30):
            # Take out one picture at a time
            image_array = sess.run(reshape_image)
            scipy.misc.toimage(image_array).save('cifar10_pic/%d.jpg'% i)
0

Leave a Reply

Your email address will not be published.