Sometimes you need to read and process your own images when using TensorFlow.
Write a script here to facilitate your own learning and consolidation. (Code based on Python3)
The storage path for the picture file is as follows:
"
Root_folder
|--------subfolder (CLASS 0)
| | | | -----image1.jpg
| |----- image2.jpg | | -----etc ...
|
| --------subfolder (CLASS 1)
| | | | -----image1.jpg
| |-----image2.jpg
| | -----etc.
.. ```
Under the root directory, create folders of each category and place the pictures of the respective categories under the corresponding folders
Import TensorFlow as tf import OS # root Root_path = './' # Set image category, height, width and number of channels Num_class = 2 Image_height = Image_wid TH = Image_channels = 3 # color = 3, gray =1 def read_iamge (Root_path, batch_size): Imagepaths = [] labels = [] Lab el = 0 classes = sorted (Os.walk (Root_path). __next__ () [1]) for C in classes:c_dir = Os.path.join (root_path , c) walk = Os.walk (C_dir). __next__ () [2] for sample in Walk:if sample.endswith ('. jpg ') and SA Mple.endswith ('. jpeg '): Imagepaths.append (Os.path.join (C_dir, sample)) Labels.append (label
) Label + = 1 # convert iamgepaths and labels to a format that TF can handle imagepaths = Tf.convert_to_tensor (imagepaths, tf.string) Labels = tf.convert_to_tensor (labels, tf.int32) # establishes Queue imagepath, label = Tf.train.slice_input_producer ( [Imagepaths, labels], shuffle=true) # Read the picture and decode image = Tf.read_file (imagepath) image = Tf.image.decode_jpeg (Image, Channels=image_cHannels) # Cropping and regularization of a picture (converting the value [0,255] to [ -1,1]) image = Tf.image.resize_images (image, Size=[image_height, image_width ]) image = image*1.0/127.5-1.0 # Create Batch X, Y = Tf.train.batch ([image, label], Batch_size=batch_size, num_ Threads=4, Capacity=batch_size*8) return X, Y
where the Tf.train.slice_input_producer () function randomly selects a tensor from the tensorlist
The Tf.train.batch () function creates a batch that meets the design requirements
-----> Because Tf.train.batch () is a queue-based implementation, you must perform a start queue operation when you use Tf.train.start_queue_runners ()