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

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

This ValueError is raised in MyDataSet.__getitem__ when a PIL image opened from disk has img.mode != 'RGB' (e.g. 'L' grayscale, 'RGBA', 'P' palette). The dataset deliberately rejects non-RGB images because the model's input transform pipeline expects 3-channel color images; feeding an 'L' or 'RGBA' image would break tensor shape/mean-normalization assumptions.

Source

Thrown at pytorch_classification/Test11_efficientnetV2/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 the offending image to RGB before training (open with PIL and .convert('RGB'), then re-save).
  2. Convert in code instead of on disk: replace the raise with img = img.convert('RGB') so any mode is normalized in __getitem__.
  3. Find the bad file: iterate self.images_path with Image.open(p).mode and print any path whose mode != 'RGB', then fix or remove it.

Example fix

// before
if img.mode != 'RGB':
    raise ValueError("image: {} isn't RGB mode.".format(self.images_path[item]))
// after
if img.mode != 'RGB':
    img = img.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:
    raise ValueError(f"Non-RGB images found: {bad[:5]}...")

Type guard

def is_rgb(path: str) -> bool:
    return Image.open(path).mode == 'RGB'

Try / catch

try:
    img, label = dataset[i]
except ValueError as e:
    if "isn't RGB mode" in str(e):
        path = str(e).split("'")[1]
        img, label = Image.open(path).convert('RGB'), dataset.images_class[i]
    else:
        raise

Prevention

When it happens

Trigger: Calling DataLoader iteration over a MyDataSet whose images_path contains a grayscale ('L'), palette ('P'), or RGBA image (e.g. a PNG with transparency or a single-channel JPEG/BMP). The check runs every time __getitem__ is called, i.e. at each batch fetch.

Common situations: Training a custom flower/classification dataset where the download contains mixed image formats; scanned documents or masks saved as grayscale PNGs; screenshots or web images with alpha channels (RGBA); icon files with palette mode ('P').

Related errors


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