Tensorflow How to randomly crop input images and labels in the same way?
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
When an image and its label must stay aligned, you cannot crop them independently with separate random calls. The correct solution is to generate one random crop location and apply that exact location to both tensors. This matters especially for segmentation masks, depth maps, and other dense labels where even a one-pixel mismatch corrupts the training data.
Why Separate Random Crops Break the Dataset
Suppose you do this:
Even if the crop sizes match, those two calls choose offsets independently. The image crop and label crop will usually come from different regions, which destroys supervision quality.
So the rule is simple: one random decision, two synchronized crops.
A Robust Shared-Offset Approach
The most general pattern is:
- sample crop offsets once
- apply those offsets to both image and label
This pattern is reliable because the offsets are shared explicitly.
Why Stateless Randomness Helps
TensorFlow has both stateful and stateless random APIs. For paired augmentations, stateless randomness is especially useful because the same seed always produces the same random choice. That makes debugging and reproducibility much easier.
If you are building a tf.data pipeline, passing a seed or deriving one per example can keep augmentation deterministic when needed.
Concatenation as a Shortcut
If image and label have compatible spatial shapes and you are comfortable combining them temporarily, another trick is concatenating them along the channel axis and cropping once.
This is compact, but it is slightly less general because image and label dtypes often differ in real datasets. The shared-offset approach is more robust when labels are integer masks.
Using the Pattern in a tf.data Pipeline
Here is how the shared crop can fit into dataset preprocessing:
Notice the label resize uses nearest-neighbor interpolation. For masks and class labels, you usually do not want bilinear interpolation because it invents intermediate values.
Segmentation Masks Need Special Care
For image classification, a crop mismatch might just reduce accuracy. For segmentation, it directly corrupts the label. That is why synchronized transforms are non-negotiable for:
- segmentation masks
- depth maps
- optical flow
- keypoint heatmaps
- paired image-to-image translation targets
The same principle applies to flips, rotations, and resizing.
Common Pitfalls
One common mistake is calling tf.image.random_crop separately on the image and label and assuming equal size means equal crop location. It does not.
Another issue is resizing masks with bilinear interpolation before cropping. That can blur or invent class values. Use nearest-neighbor for label-like tensors.
Developers also sometimes use random augmentation layers independently on image and label. Unless the randomness is shared, the pair will drift apart.
Finally, if reproducibility matters, prefer stateless random APIs or explicit seeds rather than relying on global randomness and hoping the two calls stay synchronized.
Summary
- Image and label crops must share the exact same random offsets.
- The safest pattern is to sample offsets once and crop both tensors with
crop_to_bounding_box. - Stateless random APIs are useful for reproducible paired augmentation.
- Concatenation and one crop call can work when dtypes and shapes make that convenient.
- For masks and labels, keep interpolation and augmentation choices label-safe.
Related reading
- Tensorflow How to reduce memory footprint for inference only models?
- Tensorflow How to replace a node in a calculation graph?
- Tensorflow How to replace or modify gradient?
- tensorflow how to rotate an image for data augmentation?
- Tensorflow How to switch channels of a tensor from RGB to BGR?
- TensorFlow image operations for batches
- TensorFlow how to safely terminate training manually KeyboardInterrupt
- Tensorflow How to use a trained model in a application?
.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.