首页 > 解决方案 > 如何高效地将数千张高清照片加载到 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 数据框中以添加我将用来训练的标签一个分类器,我认为这可能是一种方法。

标签: pythonpython-3.xpandasnumpyimage-processing

解决方案


在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()

推荐阅读