Skip to content
Advertisement

Tensorflow Datasets: Crop/Resize images per batch after dataset.batch()

Is it possible to Crop/Resize images per batch ?

I’m using Tensorflow dataset API as below:

JavaScript

I want, within the batch all the images should have the same size. However across the batches it can have different sizes.

For example, 1st batch has all the images of shape (batch_size, 300, 300, 3). Next batch can have images of shape (batch_size, 224, 224, 3). Another batch can have images of shape (batch_size, 400, 400, 3).

Basically I want to have dynamically shaped batches, however all the images within the batch have static shapes.

If we do as follow:

JavaScript

Does the above .map() applies to each batch separately or over the entire dataset ?

If above .map() doesn’t apply to each batch separately, how can we do this ? Can we define any iterator after dataset.batch(), apply tf.image.crop_and_resize() over each image per batch and later use dataset.concatenate() to combine all transformed batches ?

I’m creating the dataset as below:

JavaScript

Advertisement

Answer

Generally, you can try something like this:

JavaScript
JavaScript

You could also use tf.image.resize_with_crop_or_pad if you want:

JavaScript

Note that using repeat() will create an infinite dataset.

Update 1

If you want a random size for each batch, try something like this:

JavaScript
JavaScript

Update 2

A very flexible option that works for any batch size would look like this:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement