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 asserts it is mode 'RGB'. If a source image is grayscale ('L'), palette ('P'), RGBA or CMYK, the dataset refuses to return it because downstream transforms and the network assume 3 channels. The error is raised eagerly on first access of the offending item.
Source
Thrown at pytorch_classification/Test8_densenet/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
- Convert the image before use: img.convert('RGB') after Image.open (and before the mode check or transform)
- Pre-process the dataset offline, re-encoding every image as RGB JPEG/PNG
- Convert only in the transform pipeline, e.g. add transforms.Lambda(lambda im: im.convert('RGB')) or transforms.ConvertImageDtype after mode conversion
Example fix
// before
img = Image.open(self.images_path[item])
if img.mode != 'RGB':
raise ValueError("image: {} isn't RGB mode.".format(self.images_path[item]))
// after
img = Image.open(self.images_path[item])
if img.mode != 'RGB':
img = img.convert('RGB') Defensive patterns
Strategy: validation
Validate before calling
from PIL import Image
for p in dataset.images_path:
if Image.open(p).mode != 'RGB':
print('non-RGB:', p) Type guard
def is_rgb_image(img) -> bool:
return img.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('image: ')[1].split(' ')[0]
img = Image.open(path).convert('RGB')
else:
raise Prevention
- Always call img.convert('RGB') in dataset __getitem__ rather than raising
- Audit datasets with a pre-flight script listing non-RGB files
- Standardize image format to RGB JPEG during dataset ingestion
When it happens
Trigger: Iterating a DataLoader over a directory containing a grayscale (jpg/png), 8-bit palette PNG, RGBA PNG, or CMYK JPEG; the file whose mode != 'RGB' raises ValueError when that index is fetched.
Common situations: Scraped or scanned datasets mixing color and grayscale photos; PNG screenshots with alpha channel; icons saved as palette images; images converted by tools that silently keep mode 'L' or 'P'.
Related errors
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/209d659aa78e3e79.
Report an issue: GitHub.