【问题标题】:UnknownError: OSError: image file is truncated (30 bytes not processed):UnknownError: OSError: 图像文件被截断(未处理 30 个字节):
【发布时间】:2021-12-15 21:28:55
【问题描述】:

我正在尝试训练模型。我有近 150 个课程,我正在使用 ImageDataGenerator 来扩充我的数据集。我还使用模型检查点和 csvlogger 来保存权重。当我开始训练时,它在第一个时期的某个时刻给了我一个错误。如果有帮助,我使用的图像是灰度图像。

这是我的代码:

batch_size = 2000
epochs = 10

    # Augments dataset 10x
train_batches = ImageDataGenerator(preprocessing_function=preprocess_func, horizontal_flip=True, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, fill_mode='nearest') \
    .flow_from_directory(directory=train_path, target_size=image_size, classes=dataset_classes, batch_size=5, color_mode='grayscale')
valid_batches = ImageDataGenerator(preprocessing_function=preprocess_func, horizontal_flip=True, width_shift_range=0.15, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, fill_mode='nearest') \
    .flow_from_directory(directory=valid_path, target_size=image_size, classes=dataset_classes, batch_size=5, color_mode='grayscale')
test_batches = ImageDataGenerator(preprocessing_function=preprocess_func, horizontal_flip=True, width_shift_range=0.15, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, fill_mode='nearest') \
    .flow_from_directory(directory=test_path, target_size=image_size, classes=dataset_classes, batch_size=5, color_mode='grayscale')

这是我的回调:

    from keras.callbacks import ModelCheckpoint, CSVLogger

checkpoint_path = "/content/drive/MyDrive/Colab Notebooks/Datasets/Experiment/weights_improvements-epoch:{epoch:02d}-val_accuracy:{val_accuracy:.2f}.hdf5"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights
cp_callback = ModelCheckpoint(checkpoint_path,
                              verbose=1,
                              monitor='val_accuracy',
                              mode='max',
                              save_best_only=True,
                              save_weights_only=True)

log_folder = '/content/drive/MyDrive/Colab Notebooks/Datasets/Experiment'
log_path = os.path.join(log_folder, 'FSLR_logs.csv')
log_csv = CSVLogger(log_path, separator=',', append=False)

callback_list = [cp_callback, log_csv]

拟合模型:

# Compile the layers into one model and create a connection
model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])

# Train the model with the new callback
history = model.fit(x=train_batches,
                    validation_data=valid_batches,
                    batch_size=batch_size,
                    epochs=epochs,
                    callbacks=callback_list)

我收到的错误是这样的:

纪元 1/10 3428/4128 [========================>......] - ETA:26:10 - 损失:4.8299 - 准确度:0.0078 -------------------------------------------------- ------------------------- UnknownError Traceback(最近一次调用 最后)在() 4 批次大小=批次大小, 5个时期=时期, ----> 6 个回调=callback_list)

6 帧 /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py 在 quick_execute(op_name, num_outputs, 输入, attrs, ctx, name) 58 ctx.ensure_initialized() 59 张量 = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, ---> 60 个输入、属性、num_outputs) 61 除了 core._NotOkStatusException 作为 e: 62 如果名称不是无:

UnknownError: OSError: image file is truncated (30 bytes not 已处理)回溯(最近一次调用最后一次):

文件 “/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/script_ops.py”, 第 249 行,在 调用 ret = func(*args)

文件 “/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py”, 第 645 行,在包装器中 返回函数(*args, **kwargs)

文件 "/usr/local/lib/python3.7/dist-packages/tensorflow/python/data/ops/dataset_ops.py", 第 892 行,在 generator_py_func 中 values = next(generator_state.get_iterator(iterator_id))

文件 "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", 第 822 行,在 Wrapped_generator 中 对于 generator_fn() 中的数据:

文件 "/usr/local/lib/python3.7/dist-packages/keras/engine/data_adapter.py", 第 948 行,在 generator_fn 中 产量 x[i]

文件 "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", 第 65 行,在 getitem 中 return self._get_batches_of_transformed_samples(index_array)

文件 "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/iterator.py", 第 230 行,在 _get_batches_of_transformed_samples 插值=self.interpolation)

文件 “/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/utils.py”, 第 138 行,在 load_img 中 img = img.resize(width_height_tuple, 重采样)

文件“/usr/local/lib/python3.7/dist-packages/PIL/Image.py”,行 1886 年,调整大小 self.load()

文件“/usr/local/lib/python3.7/dist-packages/PIL/ImageFile.py”,行 247,加载中 "(%d 个字节未处理)" % len(b)

OSError: 图像文件被截断(30 字节未处理)

[[{{node PyFunc}}]] [[IteratorGetNext]] [操作:__inference_train_function_1029]

函数调用栈:train_function

我尝试在训练两个课程时使用相同的代码,并且效果很好。当我在所有 140 多个课程中使用它时,我不知道为什么它不起作用。

有人可以向我解释这个问题吗?我的学校项目有点需要这个。提前谢谢!

编辑: 我已经运行此代码来验证所有图像。它没有找到任何损坏的文件。

import os
from os import listdir
from PIL import Image

categ = ['Train', 'Valid', 'Test']
dataset = '/content/drive/MyDrive/Colab Notebooks/Datasets/FSLR_Application_Dataset'

for cat in categ:
  img_path = os.path.join(dataset, cat)
  for foldername in listdir(img_path):
    sign_path = os.path.join(img_path, foldername)
    print(sign_path)
    for sign in listdir(sign_path):
      if sign.endswith('.jpg'):
        try:
          img = Image.open(os.path.join(sign_path, sign)) # open the image file
          img.verify() # verify that it is, in fact an image
        except (IOError, SyntaxError) as e:
          print('Bad file:', sign) # print out the names of corrupt files

【问题讨论】:

  • 您的某个图像文件可能已损坏并触发错误。
  • 我已经运行了代码来使用 PIL.Image.verify 验证图像,数据集似乎没有问题。
  • 抛出的异常是OSError,您没有在验证码中捕获该异常,这就是您找不到损坏图像的原因。
  • 添加OSError异常后,程序也没有发现图片中的错误。尽管我刚刚意识到 Keras 正在使用 PIL,并且在 stackoverflow 中看到了相关问题的答案,但即使我没有直接使用该模块,我也必须运行 ImageFile.LOAD_TRUNCATED_IMAGES = True。我只是认为那些和我有同样问题的人直接在他们的代码中使用 PIL。

标签: python tensorflow keras conv-neural-network image-preprocessing


【解决方案1】:

我在查找有缺陷的图像文件时遇到了类似的问题。 ImageDataGenerator 使用 PIL。生成器没有检测到图像文件中的错误,如果它有它会打印一条警告消息。所以我建议你尝试使用 PIL 以外的东西来检测有缺陷的图像文件。尝试使用 cv2 我发现它有时会检测到 PIL 没有检测到的错误。具体

import cv2
your code but replace 
img = Image.open(os.path.join(sign_path, sign)) # open the image file
          img.verify() # verify that it is, in fact an image
        except (IOError, SyntaxError) as e:
          print('Bad file:', sign) # print out the names of corrupt files
with 
bad_file_list=[]
bad_count=0
try:
    img.cv2.imread(os.path.join(sign_path, sign)
    shape=img.shape # this will throw an error if the img is not read correctly
except:
    bad_file_list.append(os.path.join(sign_path, sign))
    bad_count +=1

如果发现坏文件,则在循环外打印出来

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 2016-09-29
    • 2012-10-10
    • 2020-04-24
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多