WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

The multi-GPU project's dataset class checks that every opened PIL image is in 'RGB' mode; grayscale, palette, RGBA, or CMYK images raise ValueError with the file path from __getitem__. Multi-GPU training needs uniform 3-channel tensors so DDP batches match across ranks.

Source

Thrown at pytorch_classification/train_multi_GPU/my_dataset.py:21

from torch.utils.data import Dataset


class MyDataSet(Dataset):
    """自定义数据集"""

    def __init__(self, images_path: list, images_class: list, transform=None):
        self.images_path = images_path
        self.images_class = images_class
        self.transform = transform

    def __len__(self):
        return len(self.images_path)

    def __getitem__(self, item):
        img = Image.open(self.images_path[item])
        # RGB为彩色图片,L为灰度图片
        if img.mode != 'RGB':
            raise ValueError("image: {} isn't RGB mode.".format(self.images_path[item]))
        label = self.images_class[item]

        if self.transform is not None:
            img = self.transform(img)

        return img, label

    @staticmethod
    def collate_fn(batch):
        # 官方实现的default_collate可以参考
        # https://github.com/pytorch/pytorch/blob/67b7e751e6b5931a9f45274653f4f653a4e6cdf6/torch/utils/data/_utils/collate.py
        images, labels = tuple(zip(*batch))

        images = torch.stack(images, dim=0)
        labels = torch.as_tensor(labels)
        return images, labels

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Convert on open: img = Image.open(path).convert('RGB') before the check.
  2. Sanitize the whole dataset to RGB ahead of training to avoid a mid-training rank crash.
  3. Log the offending path and skip it if skipping is acceptable, keeping batch counts consistent.

Example fix

// before
img = Image.open(self.images_path[item])
if img.mode != 'RGB':
    raise ValueError("image: {} isn't RGB mode.".format(self.images_path[item]))
// after
img = Image.open(self.images_path[item]).convert('RGB')
Defensive patterns

Strategy: validation

Validate before calling

from PIL import Image
bad = [p for p in images_path if Image.open(p).mode != 'RGB']
if bad:
    raise ValueError(f"non-RGB images will crash a DDP rank: {bad}")

Type guard

def is_rgb_image(path) -> bool:
    with Image.open(path) as img:
        return img.mode == 'RGB'

Try / catch

try:
    train_one_epoch(...)
except ValueError as e:
    if "isn't RGB mode" in str(e):
        logging.error("non-RGB file crashed this rank: %s", e)
    cleanup()
    raise

Prevention

When it happens

Trigger: Calling __getitem__ (via DataLoader iteration) on any image whose PIL img.mode != 'RGB', causing one rank to crash mid-epoch.

Common situations: Datasets containing grayscale photos, palettized PNGs, or RGBA images; in DDP one worker crashing also stalls the other ranks, making the failure appear as a hang.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/0087e709f24f64f9. Report an issue: GitHub.