方法适用于大部分PIL读取图片后出现的报错,核心思路是要先定位到报错图片位置然后修复或者绕过,如果无法找到那就参考方案3。


方案1:批量检测,然后重新下载原图

代码参考:【Bug解决】OSError: image file is truncated (7 bytes not processed)

from distutils.log import error
import os
from PIL import Image

def is_valid_image(path):
    '''
    check .jpg image
    '''
    try:
        isValid = True
        fileObj = open(path, 'rb')  # open image with binary format
        buf = fileObj.read()
        if not buf.startswith(b'\xff\xd8'):  # start with '\xff\xd8'
            isValid = False
        elif buf[6:10] in (b'JFIF', b'Exif'):
            if not buf.rstrip(b'\0\r\n').endswith(b'\xff\xd9'):  # end with '\xff\xd9'
                isValid = False
        else:
            try:
                Image.open(fileObj).verify()
            except Exception as e:
                isValid = False
    except Exception as e:
        print('Can\'t open file: {}'.format(path))
        return

    if not isValid:
        print('{} is damaged.'.format(path))
    return
    
if __name__=='__main__':
    dataPath = 'E:/Paper With Code & Datasets/COCO 2014/train2014'
    imgList = os.listdir(dataPath)
    for img in imgList:
        path = os.path.join(dataPath, img)
        is_valid_image(path)

注意这里的dataPath路径填你自己的coco路径
运行上述代码报错结果如下:
E:/Paper With Code & Datasets/COCO 2014/train2014\COCO_train2014_000000167126.jpg is damaged.

打开浏览器输入:
http://images.cocodataset.org/train2014/COCO_train2014_000000167126.jpg

下载 更换 搞定!


方案2:跳过损坏图片

添加位置要看你项目的具体实现了,所以最好用方案1,一劳永逸。

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True  # 允许加载截断的图片

方案3:cv2.imwrite

使用cv2.imwrite将问题图片或所有图片复写一遍,虽然问题图片损坏部分不会得到修复但也不会报错。

import os
import cv2
import json
from pycocotools.coco import COCO
def repair_coco_dataset(annotation_file, image_dir, output_dir):# 创建输出目录
# 加载COCO标注
coco = COCO(annotation_file)
# 获取所有图像ID
img_ids = coco.getImgIds()
# 用于存储新图像路径的列表
new_image_paths = []

for img_id in img_ids:
    # 获取图像信息
    img_info = coco.loadImgs(img_id)[0]
    original_path = os.path.join(image_dir, img_info['file_name'])
    
    # 读取图像
    img = cv2.imread(original_path)
    if img is None:
        print(f"无法读取图像: {original_path}")
        continue
    
    # 新图像路径
    new_path = os.path.join(output_dir, img_info['file_name'])
    
    # 使用cv2.imwrite保存图像(这会自动修复一些损坏的图像)
    success = cv2.imwrite(new_path, img)
    
    if success:
        new_image_paths.append(new_path)
    else:
        print(f"无法保存图像: {new_path}")

print(f"处理完成,共处理了{len(new_image_paths)}张图像")
return new_image_paths
Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐