How to load Image Masks Labels for Image Segmentation in Keras
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
For image segmentation, the input image is only half of the dataset. The real target is the mask, where each pixel stores a class label for the corresponding input pixel. Loading those masks correctly matters more than it does in image classification because resizing, interpolation, or channel handling mistakes can silently corrupt every label in the training set.
Organize Images and Masks as Paired Files
The safest layout is one image file and one mask file with matching names. For example:
With that structure, you can derive the mask path directly from the image path and keep the pairing deterministic.
Build a tf.data Pipeline
In Keras and TensorFlow, tf.data is the best tool for loading image and mask pairs. The important part is to decode masks as integer labels and resize them with nearest-neighbor interpolation.
Using method="nearest" for the mask is essential. Segmentation labels are discrete categories, not continuous image intensities.
Choose Between Integer Masks and One-Hot Masks
Most Keras segmentation models can train directly on integer mask labels when paired with a sparse loss such as SparseCategoricalCrossentropy. That is often simpler and more memory-efficient than expanding the mask to one-hot format.
If your model or loss expects one-hot masks, convert them inside the dataset pipeline:
The key is to know which label representation your loss function expects before you start training.
Keep Augmentation Synchronized
If you augment images, apply the same geometric transform to the mask. Rotating an image without rotating its mask creates invalid training pairs.
Color augmentations usually apply only to the image, while spatial transforms must stay synchronized between image and mask.
Common Pitfalls
The most damaging mistake is resizing masks with bilinear interpolation. That creates new pixel values that never existed in the label map, which turns clean class IDs into blended nonsense.
Another issue is reading masks as RGB when the dataset stores class IDs in a single channel. If the mask is really an indexed label image, keep it single-channel. If the dataset uses color-coded masks, add a conversion step that maps each color to a class ID.
Shape mismatches are also common. Many models expect masks of shape (height, width, 1) for sparse losses or (height, width, num_classes) for one-hot training. Check the final tensor shapes before starting a long training run.
Finally, verify that image and mask filenames are paired correctly. A perfectly valid pipeline can still train on garbage if 0007.png is accidentally matched with the mask for 0008.png.
Summary
- Store each image and mask as a deterministic pair.
- Load segmentation data with
tf.dataso reading, resizing, batching, and prefetching stay explicit. - Resize masks with nearest-neighbor interpolation, not bilinear interpolation.
- Match the mask representation to the loss function you plan to use.
- Apply geometric augmentations to images and masks together so labels remain aligned.
Related reading
- How to load new parts of Dataset dynamically during training of an Estimator?
- How to load only specific weights on Keras
- How to load only specific weights on Keras
- How to load sparse data with TensorFlow?
- How to locate multiple objects in the same image?
- How to locate multiple objects in the same image?
- How to load TF hub model from local system
- How to load the saved tokenizer from pretrained model
.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.