【问题标题】:Tensorflow Keras error: Unknown image file format. One of JPEG, PNG, GIF, BMP requiredTensorflow Keras 错误:未知的图像文件格式。需要 JPEG、PNG、GIF、BMP 之一
【发布时间】:2021-04-02 21:30:03
【问题描述】:

我正在训练一个分类器,我确保所有图片都是 jpg,但仍然会发生此错误: InvalidArgumentError:未知的图像文件格式。需要 JPEG、PNG、GIF、BMP 之一。 [[{{node decode_image/DecodeImage}}]] [[IteratorGetNext]] [Op:__inference_train_function_1481]

我尝试在较小的数据集上进行训练,而且它们都是 jpg 并且没有问题

这是代码:

import numpy as np
import tensorflow as tf
from tensorflow import keras

dataset = keras.preprocessing.image_dataset_from_directory(
  '/content/drive/MyDrive/fi_dataset/train', batch_size=64, image_size=(200, 200))

dense = keras.layers.Dense(units=16)
inputs = keras.Input(shape=(None, None, 3))

from tensorflow.keras import layers

x = CenterCrop(height=150, width=150)(inputs)
x = Rescaling(scale=1.0 / 255)(x)

x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x)
x = layers.MaxPooling2D(pool_size=(3, 3))(x)
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x)
x = layers.MaxPooling2D(pool_size=(3, 3))(x)
x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x)

x = layers.GlobalAveragePooling2D()(x)

num_classes = 1
outputs = layers.Dense(num_classes, activation="sigmoid")(x)

model = keras.Model(inputs=inputs, outputs=outputs)

data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype("float32")
processed_data = model(data)

model.compile(optimizer='adam',
              loss='binary_crossentropy',
               metrics=[keras.metrics.binary_accuracy],)

history=model.fit(dataset, epochs=10)

【问题讨论】:

    标签: python image tensorflow keras google-colaboratory


    【解决方案1】:

    实际上它可能有一个扩展名 jpg 但在说 tiff 格式。为了更进一步,您可以添加一些代码...

    如果您想检查图像类型,而不是扩展名,请尝试上面的代码修改版本:

    import os
    import cv2
    import imghdr
    
    def check_images( s_dir, ext_list):
        bad_images=[]
        bad_ext=[]
        s_list= os.listdir(s_dir)
        for klass in s_list:
            klass_path=os.path.join (s_dir, klass)
            print ('processing class directory ', klass)
            if os.path.isdir(klass_path):
                file_list=os.listdir(klass_path)
                for f in file_list:               
                    f_path=os.path.join (klass_path,f)
                    tip = imghdr.what(f_path)
                    if ext_list.count(tip) == 0:
                      bad_images.append(f_path)
                    if os.path.isfile(f_path):
                        try:
                            img=cv2.imread(f_path)
                            shape=img.shape
                        except:
                            print('file ', f_path, ' is not a valid image file')
                            bad_images.append(f_path)
                    else:
                        print('*** fatal error, you a sub directory ', f, ' in class directory ', klass)
            else:
                print ('*** WARNING*** you have files in ', s_dir, ' it should only contain sub directories')
        return bad_images, bad_ext
    
    source_dir =r'c:\temp\people\storage'
    good_exts=['jpg', 'png', 'jpeg', 'gif', 'bmp' ] # list of acceptable extensions
    bad_file_list, bad_ext_list=check_images(source_dir, good_exts)
    if len(bad_file_list) !=0:
        print('improper image files are listed below')
        for i in range (len(bad_file_list)):
            print (bad_file_list[i])
    else:
        print(' no improper image files were found')
    

    Python 的标准库中有许多模块,其中一个有帮助的是 imghdr。它使您可以识别文件、字节流或类似路径的对象中包含的图像类型。 imghdr 可以识别以下图像类型:rgbgifpbmpgmppm、tiffrastxbmjpeg / jpgbmppngwebpexr

    【讨论】:

    • 非常感谢,这个库(imghdr)运行良好
    【解决方案2】:

    当您说您确定它们是 jpg 时,您是如何验证的?仅仅因为扩展名是 .jpg 并不意味着该文件是真正的 jpg 图像。我建议你运行下面的代码,看看哪个图像可能有缺陷。

    import os
    import cv2
    def check_images( s_dir, ext_list):
        bad_images=[]
        bad_ext=[]
        s_list= os.listdir(s_dir)
        for klass in s_list:
            klass_path=os.path.join (s_dir, klass)
            print ('processing class directory ', klass)
            if os.path.isdir(klass_path):
                file_list=os.listdir(klass_path)
                for f in file_list:               
                    f_path=os.path.join (klass_path,f)
                    index=f.rfind('.')
                    ext=f[index+1:].lower()
                    if ext not in ext_list:
                        print('file ', f_path, ' has an invalid extension ', ext)
                        bad_ext.append(f_path)
                    if os.path.isfile(f_path):
                        try:
                            img=cv2.imread(f_path)
                            shape=img.shape
                        except:
                            print('file ', f_path, ' is not a valid image file')
                            bad_images.append(f_path)
                    else:
                        print('*** fatal error, you a sub directory ', f, ' in class directory ', klass)
            else:
                print ('*** WARNING*** you have files in ', s_dir, ' it should only contain sub directories')
        return bad_images, bad_ext
    
    source_dir =r'c:\temp\people\storage'
    good_exts=['jpg', 'png', 'jpeg', 'gif', 'bmp' ] # list of acceptable extensions
    bad_file_list, bad_ext_list=check_images(source_dir, good_exts)
    if len(bad_file_list) !=0:
        print('improper image files are listed below')
        for i in range (len(bad_file_list)):
            print (bad_file_list[i])
    else:
        print(' no improper image files were found')
    

    即使这样可能还不够,因为它会检查文件的扩展名。 实际上它可能有一个扩展名 jpg,但它是 tiff 格式。 为了更进一步,您可以添加一些代码,如果扩展名不在 您可以读取图像的良好扩展名列表,如果它有效,请使用 cv2 将其转换为 jpg,然后将其写回文件。

    【讨论】:

    • 谢谢你的代码,但我运行了它,它说没有找到不正确的图像文件,可能是什么问题
    • 我使用此代码转换图像格式并解决了问题再次感谢您! from PIL import Image img = Image.open('error p/norm418.jpg') img.save('error p/norm418.jpeg')
    • 太棒了!谢谢。我在处理 ~1500 JPG 时遇到了问题,得到了同样的错误。戳各种 JPG,没有一个看起来很糟糕。原来我没有手动检查足够近。但是,运行您的代码发现文件以某种方式损坏。再次感谢。
    猜你喜欢
    • 2021-09-12
    • 2021-08-01
    • 2023-01-16
    • 2021-09-17
    • 2019-10-10
    • 1970-01-01
    • 2010-09-29
    • 2020-01-03
    • 2018-05-04
    相关资源
    最近更新 更多