How to batch images with arbitrary sizes in tensorflow?

by tressie.damore , in category: Third Party Scripts , 7 months ago

How to batch images with arbitrary sizes in tensorflow?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 7 months ago

@tressie.damore 

To batch images with arbitrary sizes in TensorFlow, you can use the tf.image.resize function to resize all images to a fixed size before batching them together. Here is a step-by-step guide on how to do this:

  1. Load the images and store them in a list or TensorFlow data structure (e.g. tf.data.Dataset).
  2. Iterate through the images and resize them to a fixed size using tf.image.resize function. You can use either tf.image.ResizeMethod.BILINEAR or tf.image.ResizeMethod.NEAREST_NEIGHBOR as the resizing method.
  3. Create batches of resized images using tf.data.Dataset.batch function.


Here is an example code snippet that demonstrates how to batch images with arbitrary sizes in TensorFlow:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import tensorflow as tf

# Load images (replace this with your own dataset loading code)
image_paths = ["image1.jpg", "image2.jpg", "image3.jpg"]
images = [tf.io.read_file(path) for path in image_paths]

# Resize images to a fixed size
target_size = (100, 100)
resized_images = [tf.image.resize(tf.image.decode_image(image), target_size) for image in images]

# Create a TensorFlow dataset from the resized images
dataset = tf.data.Dataset.from_tensor_slices(resized_images)

# Batch the images together
batch_size = 2
batched_dataset = dataset.batch(batch_size)

# Iterate through the batches
for batch in batched_dataset:
    print(batch.shape)


In this code snippet, we first load the images and resize them to a fixed size of 100x100 using tf.image.resize. We then create a TensorFlow dataset from the resized images and batch them together with a batch size of 2. Finally, we iterate through the batches and print out their shapes.


By following these steps, you can batch images with arbitrary sizes in TensorFlow.