训练模型画混淆矩阵时,出现 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)
#最后会依次输出损坏图片的路径