如何解决无法识别图像文件<_io.BytesIO对象在0x 0C910BD0>错误?



我下载了用于在keras中训练模型的图像(我使用扩展从谷歌图像中收集了它们(。然后我用代码来调整大小。

from PIL import Image
import os, sys
path = "C:\Users\Администратор\AppData\Local\Programs\Python\Python36-32\1\"
out = "C:\Users\Администратор\AppData\Local\Programs\Python\Python36-32\1_resized\"

dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((36,36), Image.ANTIALIAS)
imResize.save(out + item, 'JPEG', quality=90)
resize()

然后运行主代码。

import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import os
import keras 
import joblib
from keras.preprocessing.image import ImageDataGenerator

train_images = 'C:\Users\Администратор\AppData\Local\Programs\Python\Python36-32\train_images'
model = keras.Sequential([
keras.layers.Flatten(input_shape=(36, 36, 3)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
datagen = ImageDataGenerator(rescale = 1. /255)
train_generator = datagen.flow_from_directory(
train_images,
target_size = (36,36),
batch_size = 4,
class_mode = 'binary')
model.fit(np.array(train_generator), epochs=10, validation_split = 0.1)

错误(cmd(。

C:UsersАдминистратор>C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32image_guess.py
Using Theano backend.
WARNING (theano.configdefaults): g++ not available, if using conda: `conda install m2w64-toolchain`
C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packagestheanoconfigdefaults.py:560: UserWarning: DeprecationWarning: there is no c++ compiler.This is deprecated and with Theano 0.11 a c++ compiler will be mandatory
warnings.warn("DeprecationWarning: there is no c++ compiler."
WARNING (theano.configdefaults): g++ not detected ! Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string.
WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
Found 339 images belonging to 2 classes.
Traceback (most recent call last):
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32image_guess.py", 
line 32, in <module>
model.fit(np.array(train_generator), epochs=10, validation_split = 0.1)
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packageskeras_preprocessingimageiterator.py", 
line 104, in __next__
return self.next(*args, **kwargs)
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packageskeras_preprocessingimageiterator.py", 
line 116, in next
return self._get_batches_of_transformed_samples(index_array)
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packageskeras_preprocessingimageiterator.py", 
line 230, in _get_batches_of_transformed_samples
interpolation=self.interpolation)
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packageskeras_preprocessingimageutils.py", 
line 114, in load_img
img = pil_image.open(io.BytesIO(f.read()))
File "C:UsersАдминистраторAppDataLocalProgramsPythonPython36-32libsite-packagesPILImage.py", 
line 2944, in open
"cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0C910BD0>

我在文件夹中发现了一个损坏的图像,代码如下。通过删除它,问题得到了解决。

import glob
from PIL import Image
imagepath = 'C:\Users\Администратор\AppData\Local\Programs\Python\Python36-32\train_images\' 
imgs_names = glob.glob(imagepath+'\*.jpg')
for imgname in imgs_names: 
img = Image.open(imgname) 
if img is None:     
print(imgname)

最新更新