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

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

The custom Dataset's __getitem__ opens each image with PIL and raises ValueError if img.mode is not 'RGB', because the pipeline (transforms like ToTensor/Normalize and the model's 3-channel input) assumes color images. Grayscale ('L'), palette ('P'), RGBA, or CMYK images are rejected with the offending file path in the message.

Source

Thrown at pytorch_classification/vision_transformer/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. Pre-convert all images to RGB: Image.open(p).convert('RGB').save(p) in a preprocessing pass.
  2. Convert inside the dataset instead of raising: change the check to img = img.convert('RGB').
  3. Clean the dataset by scanning modes first (a small script listing files where Image.open(p).mode != 'RGB').
  4. If the model should support grayscale, adapt transforms/model input channels rather than the loader.
  5. Filter out non-RGB files when building images_path/images_class lists.

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
def audit_rgb(paths):
    bad = [p for p in paths if Image.open(p).mode != 'RGB']
    if bad:
        print("non-RGB images:", bad[:10])
    return not bad

Type guard

def is_rgb(path) -> bool:
    from PIL import Image
    with Image.open(path) as im:
        return im.mode == 'RGB'

Try / catch

try:
    for img, label in loader:
        step(img, label)
except ValueError as e:
    logging.error("Dataset contains non-RGB image: %s", e)
    fix_modes(dataset_dir)

Prevention

When it happens

Trigger: Iterating the DataLoader over a dataset directory that contains any non-RGB image: black-and-white JPEGs, PNGs with alpha or palette mode, CMYK scans — the exception fires lazily during data loading when that item is fetched.

Common situations: Scraped or mixed-origin datasets containing grayscale photos; PNG screenshots saved with transparency; medical/thermal images in single-channel format; mixing ImageNet-style color data with a few grayscale samples.

Related errors


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