WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError
image: {} isn't RGB mode.
Error message
image: {} isn't RGB mode. What it means
The Swin Transformer dataset class opens images with PIL and enforces mode 'RGB' before transforming; grayscale ('L'), palette ('P'), RGBA or CMYK files trigger ValueError with the file path. Swin's preprocessing expects 3-channel input, so non-RGB images fail fast in __getitem__.
Source
Thrown at pytorch_classification/swin_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
- Convert on load: img = Image.open(path).convert('RGB') instead of raising.
- Audit and re-encode the dataset to RGB with a one-off script or ImageMagick (mogrify).
- If grayscale is valid for your use case, relax the check and adapt transforms/normalization accordingly.
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]).convert('RGB') Defensive patterns
Strategy: validation
Validate before calling
from PIL import Image
bad = [p for p in images_path if Image.open(p).mode != 'RGB']
if bad:
print("non-RGB images, re-encode or convert:", bad) 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 to RGB: %s", e)
raise Prevention
- Use Image.open(path).convert('RGB') in __getitem__
- Audit dataset image modes with a pre-flight script
- Re-encode PNGs with alpha/palette to RGB JPEG
- Keep transforms consistent with 3-channel input
When it happens
Trigger: Sampling the DataLoader so __getitem__ runs on an image whose PIL img.mode != 'RGB' (grayscale JPEG, palettized PNG, RGBA screenshot, CMYK TIFF).
Common situations: Web-scraped image folders with mixed encodings, PNGs with alpha channel, images converted by tools to P or L mode, flower-photo datasets containing grayscale shots.
Related errors
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- dataset have {} classes, but input {}
- dataset have {} classes, but input {}
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/5be093b5ba73481d.
Report an issue: GitHub.