You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历Dataloader触发PIL.UnidentifiedImageError,非损坏图片的处理方法咨询

解决Dataloader遍历中PIL.UnidentifiedImageError的简易方法

1. 检查数据集路径与加载逻辑

  • 确认Dataloader读取的实际文件路径是否正确,避免路径拼接错误导致读取空文件或非图片文件。可以在Dataset的__getitem__方法中添加打印语句验证路径:
    print(f"Loading image: {img_path}")
    
  • 排查文件名是否含特殊字符(如空格、中文),这类情况可能引发路径解析异常,建议重命名相关文件。

2. 强制指定图片格式打开

即便扩展名是jpg,部分图片的实际编码可能存在差异,在Dataset的读取逻辑中强制指定格式或直接转换为RGB:

from PIL import Image

# 直接转换为RGB格式规避编码问题
img = Image.open(img_path).convert('RGB')
# 或者显式指定仅按JPEG格式解析
img = Image.open(img_path, formats=['JPEG'])

3. 添加异常捕获跳过异常图片

在Dataset的__getitem__中加入异常处理,遇到无法识别的图片直接跳过,避免中断整个遍历流程:

def __getitem__(self, idx):
    img_path = self.img_paths[idx]
    try:
        img = Image.open(img_path).convert('RGB')
        # 执行后续预处理逻辑
        return img, self.labels[idx]
    except Exception as e:
        print(f"Skip problematic image: {img_path}, error: {str(e)}")
        # 返回空白占位图与异常标记标签
        return Image.new('RGB', (224, 224)), -1

4. 更新Pillow版本

旧版本Pillow对部分JPEG编码的支持存在bug,升级到最新稳定版可解决这类兼容问题:

pip install --upgrade pillow

5. 批量重写统一图片编码

用脚本批量重新保存所有图片,统一为标准JPEG编码:

import os
from PIL import Image

dataset_dir = "你的数据集路径"
for filename in os.listdir(dataset_dir):
    if filename.lower().endswith(('.jpg', '.jpeg')):
        img_path = os.path.join(dataset_dir, filename)
        try:
            img = Image.open(img_path)
            img.save(img_path, format='JPEG', quality=95)
        except Exception as e:
            print(f"Failed to fix: {img_path}, error: {str(e)}")

内容的提问来源于stack exchange,提问作者santoku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:45:33