首页 > 解决方案 > 避免在 Pycharm IDE 中多次加载图像数据集(仅加载一次)

问题描述

我正在使用 Keras/Tensorflow 解决图像分类问题。问题是,由于我使用的是像 Pycharm 这样的 IDE(我也使用 Jupyter Notebook),我很想知道是否有任何方法可以只从目录中加载数据集一次,然后当我重新运行整个.py文件,我只使用已加载数据中的图像?

labels = ['rugby', 'soccer']
img_size = 224
def get_data(data_dir):
    data = [] 
    for label in labels: 
        path = os.path.join(data_dir, label)
        class_num = labels.index(label)
        for img in os.listdir(path):
            try:
                img_arr = cv2.imread(os.path.join(path, img))[...,::-1] #convert BGR to RGB format
                resized_arr = cv2.resize(img_arr, (img_size, img_size)) # Reshaping images to preferred size
                data.append([resized_arr, class_num])
            except Exception as e:
                print(e)
    return np.array(data)
Now we can easily fetch our train and validation data.


train = get_data('../input/traintestsports/Main/train')
val = get_data('../input/traintestsports/Main/test')

每次调用 get_data 时,都需要额外的时间来加载整个数据集

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


您可以使用该方法读取每个图像cv2.imread(),并使用该np.save()方法保存所有图像(放入单个数组)以将数据保存为二进制文件,.npy格式为:

import cv2
import numpy as np

imgs = ['image1.png', 'image2.png', 'image3.png', 'image4.png']

# Map each str to cv2.imread, convert map object to list, and convert list to array
arr = np.array(list(map(cv2.imread, imgs))) 

np.save('data.npy', arr)

当您要访问数据时,可以使用以下np.load()方法:

import numpy as np

arr = np.load('data.npy')

您可以通过命令提示符命令安装(OpenCV) :cv2

pip install opencv-python

numpy

pip install numpy

如果您有更复杂的数据类型,您可以使用该pickle.dump()方法将已消毒的数据保存到文件中:

import pickle

data = {"data": ['test', 1, 2, 3]} # Replace this with your dataset

with open("data.pickle", "wb") as f:
    pickle.dump(data, f)

当您要访问数据时,可以使用以下pickle.load()方法:

import pickle

with open("data.pickle", "rb") as f:
    data = pickle.load(f)

print(data)

输出:

{'data': ['test', 1, 2, 3]}

pickle模块内置于python中。


推荐阅读