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

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

Identical to error 21 but in the EfficientNet Test9 dataset: MyDataSet.__getitem__ validates every image is PIL mode 'RGB' before applying transforms, because EfficientNet expects 3-channel input. Non-RGB images (grayscale, palette, RGBA) raise ValueError on access.

Source

Thrown at pytorch_classification/Test9_efficientNet/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 load: img.convert('RGB') before the check/transform
  2. Batch-convert the dataset offline to RGB with PIL or ImageMagick (mogrify)
  3. Add a conversion in the transform pipeline so the check never trips

Example fix

// before
img = Image.open(self.images_path[item])
if img.mode != 'RGB':
    raise ValueError(...)
// 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 dataset.images_path if Image.open(p).mode != 'RGB']
if bad:
    print('convert these to RGB first:', bad)

Type guard

def is_rgb_image(img) -> bool:
    return img.mode == 'RGB'

Try / catch

try:
    for epoch in range(epochs):
        for img, label in loader:
            ...
except ValueError as e:
    if "isn't RGB mode" in str(e):
        path = str(e).split('image: ')[1].split(' ')[0]
        Image.open(path).convert('RGB').save(path)

Prevention

When it happens

Trigger: DataLoader iterating a flower/imagenet folder where any jpg/png has mode 'L', 'P', 'RGBA' or 'CMYK'; the ValueError fires when __getitem__ is called for that sample.

Common situations: Mixed-quality scraped datasets; grayscale scans; RGBA PNGs saved by screenshot tools; palette-mode GIFs converted to PNG without mode change.

Related errors


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