如何将所有图像转换为所有子文件夹并将其转换为h5文件?

时间:2020-03-01 13:28:14

标签: python numpy keras deep-learning h5py

在下面的代码中,我已经从代码和标签中所示的目录中读取了图像,并使用matplotlib能够绘制图像,但是我无法将所有这些数据保存在h5文件中。我有15个类(即15个文件夹)位于文件夹PlantVillage中。

train_path = '/home/snehil/Desktop/plantdisease/plantvillage/PlantVillage'

train_x = '/home/snehil/Desktop/plantdisease/plantvillage/PlantVillage/Pepper__bell___Bacterial_spot'

train_batches = ImageDataGenerator().flow_from_directory(
    train_path,
    target_size=(224, 224),
    classes=[
        'Pepper__bell___Bacterial_spot',
        'Pepper__bell___healthy', 
        'Potato___Early_blight',
        'Potato___healthy',
        'Potato___Late_blight', 
        'Tomato_Bacterial_spot',
        'Tomato_Early_blight',
        'Tomato_healthy',
        'Tomato_Late_blight',
        'Tomato_Leaf_Mold',
        'Tomato_Septoria_leaf_spot',
        'Tomato_Spider_mites_Two_spotted_spider_mite',
        'Tomato__Target_Spot',
        'Tomato__Tomato_mosaic_virus', 
        'Tomato__Tomato_YellowLeaf__Curl_Virus'
     ],
     batch_size=10
)


# plots images with labels within jupyter notebook
def plots(ims, figsize=(12, 6), rows=1, interp=False, titles=None):
    if type(ims[0]) is np.ndarray:
        ims = np.array(ims).astype(np.uint8)
        if (ims.shape[-1] != 3):
            ims = ims.transpose((0, 2, 3, 1))

    f = plt.figure(figsize=figsize)

    cols = len(ims) // rows if len(ims) % 2 == 0 else len(ims) // rows + 1

    for i in range(len(ims)):
        sp = f.add_subplot(rows, cols, i+1)
        sp.axis('Off')
        if titles is not None:
            sp.set_title(titles[i], fontsize=16)
        plt.imshow(ims[i], interpolation=None if interp else 'none')


imgs, labels = next(train_batches)
plots(imgs, titles=labels)

我已经尝试了这段代码,它只是在消耗我的所有RAM。

import h5py
h5_train = h5py.File("train_x.h5", 'w')
h5_train.create_dataset("data_train", data=np.array(train_batches))
print(h5_train)
h5_train.close()

0 个答案:

没有答案