【问题标题】:How to import image dataset from folder with tensorflowio如何使用 tensorflowio 从文件夹中导入图像数据集
【发布时间】:2020-11-27 12:48:59
【问题描述】:

您好,我有来自共享文件夹的图像数据集。像这样的数据集路径:/media/sharing_folder/data 和数据文件夹有两个子文件夹,分别是“屏蔽”和“未屏蔽”。我尝试像这样导入数据:

data = []

def create_data():
    for category in CATEGORIES:
        path =  os.path.join(DATADIR, category) #path to masked or unmasked dir
        class_num = CATEGORIES.index(category)
        for img in os.listdir(path):
            try:
                img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                data.append([new_array, class_num])
            except Exception as e:
                pass
            
create_data()

但是,此导入运行非常缓慢。我想用 tensorflowio 导入数据。如何使用 tensorflowio 导入?

【问题讨论】:

    标签: tensorflow image-processing import deep-learning imagedata


    【解决方案1】:

    要正确显示您的代码,请开始新的一行。在键盘上按下左上角的键(1 键右侧的键)四次。然后创建一个新行并输入您的代码。完成输入代码后,重复按相同的键 上面引用了四次。这将关闭代码区域。这是你的代码

    data = []
    
    def create_data(): 
        for category in CATEGORIES: 
            path = os.path.join(DATADIR, category) #path to masked or unmasked dir 
            class_num = CATEGORIES.index(category) 
            for img in os.listdir(path): 
                try: img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE) 
                    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
                    data.append([new_array, class_num]) 
                except Exception as e: 
                    pass
    
    create_data()
    

    现在回答您的问题,我建议您使用 keras ImageDataGenerator。文档是here.

    split=.2 # set percentage of images to use for validation
    height=254 # set to desired image height
    width =254 # set to desired image width
    batch_size=32 # set to desired batch size
    seed = 123  # set to an arbitrary value
    data_dir=r'c: /media/sharing_folder/data'
    img_gen=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255,validation_split=split) 
    train_gen=img_gen.flow_from_directory(directory= data_dir,target_size=(height,width),
              color_mode='grayscale', class_mode=categorical, batch_size=batch_size,
              seed=seed, shuffle=True, subset='training)
    valid_gen=img_gen.flow_from_directory(directory= data_dir,target_size=(height,width),
              color_mode='grayscale', class_mode=categorical, batch_size=batch_size,
              seed=seed, shuffle=False, subset='validation') 
    

    然后编译您的模型并将损失用作 categorical_crossentropy。然后使用 model.fit 使用上面定义的生成器训练你的模型 关于验证,最好在 valid_gen 中设置 shuffle=False,以便为每个 epoch 以相同的顺序提供验证图像。

    【讨论】:

    • 嗨,格里。非常感谢您的回答。我有个问题。我想知道你为什么在valid_gen中做“shuffle=False”,为什么不使用test_datagen?
    • 查看我编辑的答案。如果你有一个单独的测试集,然后创建一个像 valid_gen 一样的 test_gen,但将它指向包含测试数据的目录。
    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多