有没有办法在Python中将包含.jpeg图像的文件夹转换为hdf5?我正在尝试建立一个用于图像分类的神经网络模型。谢谢!
处理和保存图像数据的方法有很多种。以下是读取 1 个文件夹中的所有图像文件并加载到 HDF5 文件中的方法的 2 种变体。此过程概要:
1ds_
)glob.iglob()
循环播放图像。然后做:
cv2.imread()
cv2.resize()
img_ds[cnt:cnt+1:,:,:]
这是一种方法。其他需要考虑的事项:
with/as:
和将数据保存到第二个 HDF5 的循环(前缀:nds_
).ppm
文件,因此您需要将glob函数修改为
使用*.jpg
。下面的简单版本(2021 年 3 月 16 日添加):
假设所有文件都位于当前文件夹中,并将所有调整大小的图像加载到一个数据集(名为“图像”)。请参阅前面的代码,了解第二种方法,该方法将每个图像加载到单独的数据集中而不调整大小。
import sys
import glob
import h5py
import cv2
IMG_WIDTH = 30
IMG_HEIGHT = 30
h5file = 'import_images.h5'
nfiles = len(glob.glob('./*.ppm'))
print(f'count of image files nfiles={nfiles}')
# resize all images and load into a single dataset
with h5py.File(h5file,'w') as h5f:
img_ds = h5f.create_dataset('images',shape=(nfiles, IMG_WIDTH, IMG_HEIGHT,3), dtype=int)
for cnt, ifile in enumerate(glob.iglob('./*.ppm')) :
img = cv2.imread(ifile, cv2.IMREAD_COLOR)
# or use cv2.IMREAD_GRAYSCALE, cv2.IMREAD_UNCHANGED
img_resize = cv2.resize( img, (IMG_WIDTH, IMG_HEIGHT) )
img_ds[cnt:cnt+1:,:,:] = img_resize
以下之前的代码(自 2021 年 3 月 15 日起):
import sys
import glob
import h5py
import cv2
IMG_WIDTH = 30
IMG_HEIGHT = 30
# Check command-line arguments
if len(sys.argv) != 3:
sys.exit("Usage: python load_images_to_hdf5.py data_directory model.h5")
print ('data_dir =', sys.argv[1])
data_dir = sys.argv[1]
print ('Save model to:', sys.argv[2])
h5file = sys.argv[2]
nfiles = len(glob.glob(data_dir + '/*.ppm'))
print(f'Reading dir: {data_dir}; nfiles={nfiles}')
# resize all images and load into a single dataset
with h5py.File('1ds_'+h5file,'w') as h5f:
img_ds = h5f.create_dataset('images',shape=(nfiles, IMG_WIDTH, IMG_HEIGHT,3), dtype=int)
for cnt, ifile in enumerate(glob.iglob(data_dir + '/*.ppm')) :
img = cv2.imread(ifile, cv2.IMREAD_COLOR)
# or use cv2.IMREAD_GRAYSCALE, cv2.IMREAD_UNCHANGED
img_resize = cv2.resize( img, (IMG_WIDTH, IMG_HEIGHT) )
img_ds[cnt:cnt+1:,:,:] = img_resize
# load each image into a separate dataset (image NOT resized)
with h5py.File('nds_'+h5file,'w') as h5f:
for cnt, ifile in enumerate(glob.iglob(data_dir + '/*.ppm')) :
img = cv2.imread(ifile, cv2.IMREAD_COLOR)
# or use cv2.IMREAD_GRAYSCALE, cv2.IMREAD_UNCHANGED
img_ds = h5f.create_dataset('images_'+f'{cnt+1:03}', data=img)
您可以通过在 Python 中使用 HDFql 执行以下操作来解决您的问题(HDFql 还支持 C、C++、Java、C#、R 和 Fortran):
import HDFql
folder = "/home/dummy/images/"
HDFql.execute("create and use file images.h5")
HDFql.execute("show file \"%s\"" % folder)
while HDFql.cursor_next() == HDFql.SUCCESS:
file = HDFql.cursor_get_char()
print("File found: \"%s\"" % file)
HDFql.execute("create dataset \"%s\" values from binary file \"%s%s\"" % (file, folder, file))
HDFql.execute("close file")