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

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

Dataset.__getitem__ opens each image with PIL and requires mode 'RGB'. Grayscale ('L'), palette ('P'), CMYK, or RGBA images are rejected with a ValueError so the transform pipeline (which assumes 3 channels) never receives an incompatible tensor.

Source

Thrown at pytorch_classification/ConvNeXt/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, e.g. img.convert('RGB') after opening.
  2. Pre-batch-convert all dataset images to RGB with a script or ImageMagick (mogrify -format png -define png:color-mode=8).
  3. Filter non-RGB files out of the dataset directory before building the dataset.
  4. If grayscale images are legitimate, change the check to img = img.convert('RGB') instead of raising.

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
for p in image_paths:
    with Image.open(p) as im:
        if im.mode != "RGB":
            print(f"non-RGB: {p} ({im.mode})")

Type guard

def is_rgb(img) -> bool:
    return getattr(img, "mode", None) == "RGB"

Try / catch

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

Prevention

When it happens

Trigger: Iterating the DataLoader where the dataset folder contains a grayscale PNG, a palette-mode GIF, or an RGBA image; path comes from self.images_path.

Common situations: Mixed image sources: scanned documents saved as grayscale, screenshots with alpha channel, webp/gif files converted by PIL to 'P' mode.

Related errors


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