PIL.UnidentifiedImageError: cannot identify image file与 load image file is truncated问题

训练模型画混淆矩阵时,出现 load image file is truncated(490 bytes…)问题,应该是图像损坏了,但是肉眼也看不出来是哪张图片,490bytes也没办法定位图片位置。

最开始报错是load image file is truncated
解决办法:

在代码最前面加上这两行,是用来跳过损坏图片的
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

加上这两行后我的报错信息变成了PIL.UnidentifiedImageError: cannot identify image file
然后用下面的代码找出损坏图片,依次删掉

import os
import shutil
import warnings
import cv2
import io
from PIL import Image
warnings.filterwarnings("error", category=UserWarning)
base_dir = os.path.join(image_path, "test")#这里改成自己的图片路径
i=0
def is_read(file):
    try:
        imgFile=Image.open(file)
        return True
    except Exception:
        return False

for parent,dirs,files in os.walk(base_dir):
    for file in files:
        if not is_read(os.path.join(parent,file)):
            print(os.path.join(parent,file))
            # os.remove(os.path.join(parent,file))
            #这一行用来删掉损坏图片
            i=i+1
print(i)
#最后会依次输出损坏图片的路径
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值