python - 如何高效地将数千张高清照片加载到 pandas df 并转换为 HDF?
问题描述
我想将数千张动物图像加载到 pandas df 中,添加功能并可能转换为 HDF。
我尝试使用以下方法cv2.imread()
import cv2
import os
import numpy as np
import pandas as pd
def images_to_hdf(folder_path, label):
"""
Save a folder of images to hdf format.
Args:
folder_path: Path to folder containing images.
label: A string of the image content.
Return:
None
"""
image_data = [np.array(cv2.imread(folder_path + img)) for img in os.listdir(folder_path)]
data = pd.DataFrame()
data['Images'] = image_data
data['Label'] = label
data.to_hdf(path, key)
但是仅读取 100 张图像加上一个错误(太多数值无法存储......)需要超过 1 分钟的时间,我确信这是一种非常低效的方法。
我尝试np.fromfile()
而不是cv2.imread()
它的速度超快(我不太确定它的作用),但它返回 rank1 数组,我希望将图像 3 维数据存储在 pd 数据框中以添加我将用来训练的标签一个分类器,我认为这可能是一种方法。
解决方案
在h5py的帮助下,您可以直接将图像和标签保存到 hdf5 文件中(不使用 pandas)。这是一个如何做到这一点的例子(从这里改编):
import os
import glob
import cv2
import h5py
import numpy as np
def images_to_hdf5(images_path='/path/to/images',
label=0,
hdf5_path='/path/to/hdf5_file/file.hdf5'):
image_names = glob.glob(os.path.join(images_path, '*.jpg'))
n = len(image_names)
labels = [label]*n
hdf5_file = h5py.File(hdf5_path, mode='w')
hdf5_file.create_dataset("Images", (n, 3, 224, 224), np.int8)
hdf5_file.create_dataset("Labels", (n,), np.int8)
hdf5_file["Labels"][...] = labels
for i, image_name in enumerate(image_names):
img = cv2.imread(image_name)
img = cv2.resize(img, (224, 224)) # shape (224, 224, 3)
img = np.rollaxis(img, 2)[None] # shape (1, 3, 224, 224)
hdf5_file["Images"][i, ...] = img
hdf5_file.close()
打开它:
hdf5_file = h5py.File(hdf5_path, "r")
要访问例如第一个图像和标签:
hdf5_file["Images"][0]
hdf5_file["Labels"][0]
#hdf5_file.close()
推荐阅读
- rabbitmq - 在 RabbitMQ 中按属性或标头获取消息
- python - 如何使用 pytube 下载 YouTube 视频片段?
- json - C++ Builder 10.2 Tokyo > JSON > 用 JsonValue->Free() 替换 JSONvalue 导致“访问冲突”
- git - git add -p 和 git add --patch 有什么区别?
- node.js - 在 bcryptjs 中加密和解密
- python - 根据特定列值绘制熊猫数据框的多行的快速方法
- javascript - 使用 Goggle Classroom API 的课程及其学生列表
- python-3.x - 迭代 df 中的行并使用匹配行的列操作结果插入新行
- c# - 如何使用 dapper OracleDynamicParameters() 从过程中获取价值?
- debugging - 捕获定期错误的问题