python - 避免在 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 时,都需要额外的时间来加载整个数据集
解决方案
您可以使用该方法读取每个图像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中。
推荐阅读
- javascript - 为主题切换器 vuejs 创建 vue mixin
- json - 在 Flutter 中将 xml2json 值提取到文本小部件
- android-intent - 是否可以在不同的意图中使用相同的训练短语?
- ruby - 在 Ubuntu 18.04 上安装 Ruby 2.6 - 捆绑程序路径错误
- r - R:蒙特卡洛模拟和正态分布的问题
- react-native - openDrawer() 未定义反应原生
- lambda-calculus - Beta 约简 Lambda 演算示例
- javascript - 如何在段落中获取单词的边界矩形,而只知道它的索引?
- java - Gradle:更改是springboot版本导致错误
- typescript - 打字稿类型不可分配给类型“符号”错误