I am trying to build a CNN based image recognition system for the Tensorflow malaria dataset. I loaded the dataset (~27k RGB images) using conventional tensorflow_datasets syntax.

After some data exploration, I found that all the images are not of the same size. A print statement for few instances is shown in below snippet:

import tensorflow_datasets as tfds

ds_train, ds_info = tfds.load('malaria', split='train', as_supervised=True,with_info=True)

ds = ds_train.take(5)  #selecting 5 images

for image, label in tfds.as_numpy(ds):
  print(type(image),image.shape, type(label), label)


<class 'numpy.ndarray'> (103, 103, 3) <class 'numpy.int64'> 1
<class 'numpy.ndarray'> (106, 121, 3) <class 'numpy.int64'> 1
<class 'numpy.ndarray'> (139, 142, 3) <class 'numpy.int64'> 0
<class 'numpy.ndarray'> (130, 118, 3) <class 'numpy.int64'> 1

The varying sizes of images across the dataset affect the initial CNN layer as flattening each image tensor yields a different sized array.

I understand that all the images need to be converted to a common aspect ratio before the modelling step and we can achieve that by using padding or some other preprocessing techniques of keras.preprocessing.image but I am not sure about the steps to efficiently implement it.

I will be grateful if someone could provide an elegant way around this.
Thank you in advance!


1 Answer 1

#Here image is your batch.
# Add "batch" and "channels" dimensions
image = image[tf.newaxis, ..., tf.newaxis]
image.shape.as_list()  # [batch, height, width, channels]

tf.image.resize(image, [height,width])[0,...,0].numpy()
  • $\begingroup$ I'm sorry, please could you elaborate on what the code does ? Is your initial image object a 4d tensor containing the dataset or is this an example for a single image? Will be grateful if you could clarify. Thanks :) $\endgroup$ Jul 27, 2020 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.