无法识别导致错误的图像 - PIL.UnidentifiedImageError:无法识别图像文件

时间:2021-04-05 09:33:55

标签: keras deep-learning

在训练神经网络模型时,我收到以下错误:

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fd6342bdfb0>

我已将 PIL 版本更新为最新版本。我无法指出是哪个图像文件导致了问题。使用的所有图片文件均为JPG文件。

以下是我正在使用的代码。

from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True
                                  )
test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory(IMG_PATH_TRAIN,
                                                 target_size = (224,224),
                                                 batch_size = 32,
                                                 shuffle = False
                                                 #class_mode = 'categorical'
                                                )

test_set = test_datagen.flow_from_directory(IMG_PATH_TEST,
                                            target_size = (224,224),
                                            batch_size = 32,
                                            shuffle = False
                                            #class_mode = 'categorical'
                                           )
lr = 0.003
sgd = SGD(lr=lr, momentum=0.9, nesterov=False)
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)

input_shape = (224,224,3)
inputs = Input(input_shape)

def set_model(base_model):
  x =  base_model.output
  x = GlobalAveragePooling2D()(x)
  x = Dense(82, activation='softmax')(x)
  base_model = Model(inputs=inputs, outputs= [x])
  batch_size = 32
  
  for layer in base_model.layers:
    layer.trainable = True
  
  base_model.compile(loss=['categorical_crossentropy','categorical_crossentropy','categorical_crossentropy'],
                     loss_weights=[1,1,1],
                     optimizer= sgd,
                     metrics=['accuracy']) #, 'top_k_categorical_accuracy'])
  
  base_model.fit(training_set,
               steps_per_epoch=20991//batch_size,
               epochs=1, 
               validation_data=test_set, 
                             validation_steps=7456//batch_size, #test_samples // batch_size,
                             verbose=1)

  return base_model

base_model_inception = InceptionV3(include_top=False, weights=None, input_tensor = inputs)
base_model_inception = set_model(base_model_inception)

1 个答案:

答案 0 :(得分:0)

您是否检查过图像的大小和格式?某些图像的格式可能不正确,例如 RGB 与 RGBA。

另外,如果以gif格式读取图像,即P,那么TensorFlow库在数据生成过程中将无法对其进行转换,从而导致错误。