【问题标题】:UnidentifiedImageError: cannot identify image fileUnidentifiedImageError:无法识别图像文件
【发布时间】:2020-09-05 13:14:56
【问题描述】:

你好我正在用TensorFlow和Keras训练一个模型,数据集是从https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765下载的

这是一个 zip 文件夹,我在以下目录中拆分:

.
├── test
│   ├── Cat
│   └── Dog
└── train
    ├── Cat
    └── Dog

Test.cat和test.dog每个文件夹1000张jpg照片,train.cat和traing.dog每个文件夹11500张jpg照片。

加载是用这段代码做的:

batch_size = 16

# Data augmentation and preprocess
train_datagen = ImageDataGenerator(rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    validation_split=0.20) # set validation split

# Train dataset
train_generator = train_datagen.flow_from_directory(
    'PetImages/train',
    target_size=(244, 244),
    batch_size=batch_size,
    class_mode='binary',
    subset='training') # set as training data

# Validation dataset
validation_generator = train_datagen.flow_from_directory(
    'PetImages/train',
    target_size=(244, 244),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation') # set as validation data

test_datagen = ImageDataGenerator(rescale=1./255)
# Test dataset
test_datagen = test_datagen.flow_from_directory(
    'PetImages/test')

模型正在使用以下代码进行训练:

history = model.fit(train_generator,
                    validation_data=validation_generator,
                    epochs=5)

我得到以下输入:

Epoch 1/5
1150/1150 [==============================] - ETA: 0s - loss: 0.0505 - accuracy: 0.9906

但是当时代处于这一点时,我收到以下错误:

UnidentifiedImageError: 无法识别图像文件 <_io.bytesio>

我该如何解决这个问题才能完成训练?

谢谢

【问题讨论】:

  • 这很可能是因为您的数据集包含生成器无法读取的文件。如果有任何扩展名错误或文件损坏的图像,请尝试检查您的数据集。
  • 有没有什么功能可以检查这个,每个文件夹都有很多图片。谢谢
  • 代码有效吗?

标签: python tensorflow keras


【解决方案1】:

我不知道这是否仍然相关,但对于将来会遇到同样问题的人:

在这种特定情况下,dog_cat 数据集中有两个损坏的文件:

  • cats/666.jpg
  • dogs/11702.jpg

只需删除它们即可。

【讨论】:

  • 谢谢!我正在使用这个数据集,这为我节省了很多时间!
【解决方案2】:

试试这个功能,看看图片格式是否正确。

import os
from PIL import Image
folder_path = 'data\img'
extensions = []
for fldr in os.listdir(folder_path):
    sub_folder_path = os.path.join(folder_path, fldr)
    for filee in os.listdir(sub_folder_path):
        file_path = os.path.join(sub_folder_path, filee)
        print('** Path: {}  **'.format(file_path), end="\r", flush=True)
        im = Image.open(file_path)
        rgb_im = im.convert('RGB')
        if filee.split('.')[1] not in extensions:
            extensions.append(filee.split('.')[1])
    

【讨论】:

    【解决方案3】:

    我以前遇到过这个问题。所以我开发了一个 python 脚本来测试有效图像文件的训练和测试目录。文件扩展名必须是 jpg、png、bmp 或 gif 之一,因此它首先检查正确的扩展名。然后它尝试使用 cv2 读取图像。如果它没有输入有效的图像,则会创建一个异常。在每种情况下,都会打印出错误的文件名。最后,一个名为 bad_list 的列表包含错误文件路径的列表。注意目录必须是名称'test'和'train'

    import os
    import cv2
    bad_list=[]
    dir=r'c:\'PetImages'
    subdir_list=os.listdir(dir) # create a list of the sub directories in the directory ie train or test
    for d in subdir_list:  # iterate through the sub directories train and test
        dpath=os.path.join (dir, d) # create path to sub directory
        if d in ['test', 'train']:
            class_list=os.listdir(dpath) # list of classes ie dog or cat
           # print (class_list)
            for klass in class_list: # iterate through the two classes
                class_path=os.path.join(dpath, klass) # path to class directory
                #print(class_path)
                file_list=os.listdir(class_path) # create list of files in class directory
                for f in file_list: # iterate through the files
                    fpath=os.path.join (class_path,f)
                    index=f.rfind('.') # find index of period infilename
                    ext=f[index+1:] # get the files extension
                    if ext  not in ['jpg', 'png', 'bmp', 'gif']:
                        print(f'file {fpath}  has an invalid extension {ext}')
                        bad_list.append(fpath)                    
                    else:
                        try:
                            img=cv2.imread(fpath)
                            size=img.shape
                        except:
                            print(f'file {fpath} is not a valid image file ')
                            bad_list.append(fpath)
                           
    print (bad_list)
                        
        
      
    

    【讨论】:

      【解决方案4】:

      您的图像可能已损坏。在数据预处理步骤,尝试使用Image.open()查看是否可以打开所有图片。

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 2022-12-17
        • 2021-12-28
        • 1970-01-01
        • 2020-05-26
        • 2017-09-11
        • 2015-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多