Tensorflow CNN training images are all different sizes
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
CNN training data often contains images with different widths and heights, but a standard training batch usually needs a consistent tensor shape. In practice, that means you almost always resize, crop, or pad images before batching them.
TensorFlow gives you several ways to do this cleanly in tf.data. The right choice depends on whether aspect ratio matters, whether you can tolerate distortion, and whether your model can accept variable input shapes during inference.
Why Variable Sizes Are a Problem
A CNN layer can operate on different spatial dimensions in theory, but batched training is stricter. A batch is one tensor, and every element in that tensor must share the same shape.
So while a single image of shape 200 x 300 x 3 and another of shape 480 x 640 x 3 are both valid individually, they cannot be stacked into one dense batch without preprocessing.
Resize Everything to a Fixed Shape
The simplest approach is resizing every image to the same target size.
This is easy and fast, but it can distort the image if the original aspect ratio is not square.
Preserve Aspect Ratio With Padding
If distortion is a problem, resize while preserving aspect ratio and then pad to the target dimensions.
This is a good default for many classification tasks because it avoids stretching objects unnaturally.
Cropping as an Alternative
For some image problems, especially when the subject is usually centered, cropping can work better than padding. You can resize the shorter side and then crop a fixed window.
Cropping is commonly used as part of data augmentation, but it can remove important content if the target object is near the edge.
A Complete tf.data Pipeline
Here is a minimal pipeline that loads variable-size JPEG files and produces normalized fixed-size batches:
Once the resize or padding step is in place, batching works normally.
Can the Model Accept Variable Input Shapes?
Some TensorFlow and Keras models can declare None for height and width, especially when they avoid dense layers early in the network.
That helps at inference time for single images, but it does not remove the batching requirement. During training, each batch still needs consistent dimensions unless you use more advanced bucketing or per-example processing strategies.
Common Pitfalls
The most common mistake is decoding images and calling batch() before resizing or padding. TensorFlow then fails because it cannot combine tensors with different shapes.
Another issue is ignoring aspect ratio. A naive resize to a square input can silently reduce model quality if object shape matters.
Be careful with image data types too. Many image ops return floating point tensors, so normalize consistently and make sure the model sees the range it expects.
Finally, remember that pretrained models often expect a specific input size and preprocessing rule. Match those exactly when fine-tuning.
Summary
- Variable-size images usually need preprocessing before batched CNN training.
- Resizing to a fixed shape is the simplest approach.
- '
tf.image.resize_with_padpreserves aspect ratio better than a plain stretch.' - Models can support variable image sizes at inference, but batches still need consistent dimensions.
- Put the resize, crop, or pad step inside the
tf.datapipeline before batching.
Related reading
- tensorflow code optimization strategy
- TensorFlow Combining Dense Layer with LSTM Cell
- Tensorflow command tf.test.is_gpu_available returns False
- Tensorflow compatibility with Keras
- Tensorflow Compile Runs For A Long Time
- TensorFlow concat a variable-sized placeholder with a vector
- tensorflow constant with variable size
- Tensorflow conv2d_transpose Size of out_backprop doesn't match computed
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.