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

image: {} isn't RGB mode.

Error message

image: {} isn't RGB mode.

What it means

MyDataSet.__getitem__ opens each image with PIL and requires mode 'RGB' before applying transforms; if a file is grayscale ('L'), palette ('P'), CMYK, or RGBA, the loader raises ValueError naming the offending path. Models in this project expect 3-channel input, so non-RGB images are rejected eagerly.

Source

Thrown at pytorch_classification/mini_imagenet/my_dataset.py:40

        csv_path = os.path.join(root_dir, csv_name)
        assert os.path.exists(csv_path), "file:'{}' not found.".format(csv_path)
        csv_data = pd.read_csv(csv_path)
        self.total_num = csv_data.shape[0]
        self.img_paths = [os.path.join(images_dir, i)for i in csv_data["filename"].values]
        self.img_label = [self.label_dict[i][0] for i in csv_data["label"].values]
        self.labels = set(csv_data["label"].values)

        self.transform = transform

    def __len__(self):
        return self.total_num

    def __getitem__(self, item):
        img = Image.open(self.img_paths[item])
        # RGB为彩色图片,L为灰度图片
        if img.mode != 'RGB':
            raise ValueError("image: {} isn't RGB mode.".format(self.img_paths[item]))
        label = self.img_label[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 at load time: img = Image.open(path).convert('RGB') before the mode check.
  2. Pre-scan the dataset and re-encode offending images to RGB (e.g. with PIL or ImageMagick).
  3. If grayscale data is legitimate, drop the strict check and rely on transforms.ToTensor/Normalize configured for the actual channel count.

Example fix

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

Strategy: validation

Validate before calling

from PIL import Image
bad = [p for p in img_paths if Image.open(p).mode != 'RGB']
if bad:
    raise ValueError(f"non-RGB images in dataset: {bad[:10]}")

Type guard

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

Try / catch

try:
    for images, labels in train_loader:
        ...  # train step
except ValueError as e:
    if "isn't RGB mode" in str(e):
        logging.error("convert this file to RGB and re-run: %s", e)
    raise

Prevention

When it happens

Trigger: Iterating the DataLoader so __getitem__ is invoked on an image whose PIL img.mode != 'RGB' (e.g. .png with palette, .jpg saved as grayscale, RGBA screenshots).

Common situations: Mixed-format datasets scraped from the web, grayscale medical/scan images in a color folder, PNG images with transparency, images saved by tools that default to P or L mode.

Related errors


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