使用 Python 将单张 JPG 图片转换为 HDF5 文件的完整步骤和代码示例:
步骤说明
- 读取 JPG 图片:使用
PIL
或OpenCV
库读取图片为 NumPy 数组。 - 创建 HDF5 文件:用
h5py
将数组写入 HDF5 文件,并添加元数据(可选)。
完整代码示例
import h5py
from PIL import Image
import numpy as np
# 1. 读取 JPG 图片为 NumPy 数组
image_path = "example.jpg" # 替换为你的图片路径
with Image.open(image_path) as img:
image_array = np.array(img) # 转换为形状 (height, width, channels) 的数组
# 2. 创建 HDF5 文件并写入数据
with h5py.File("image_to_hdf5.h5", "w") as f:
# 写入图片数组
dset = f.create_dataset("image_data", data=image_array)
# 添加元数据(可选)
dset.attrs["format"] = "RGB" # 假设是 RGB 图片
dset.attrs["original_size"] = img.size # 图片原始尺寸 (width, height)
dset.attrs["description"] = "Converted from JPG to HDF5"
print("转换完成!HDF5 文件已保存为 image_to_hdf5.h5")
验证 HDF5 文件内容
# 读取 HDF5 文件并检查数据
with h5py.File("image_to_hdf5.h5", "r") as f:
dset = f["image_data"]
print("数据形状:", dset.shape) # 例如 (height, width, 3)
print("元数据:", dict(dset.attrs))
# 提取数据并显示(可选)
recovered_image = dset[:]
from matplotlib import pyplot as plt
plt.imshow(recovered_image)
plt.show()
关键注意事项
-
依赖库安装:
pip install h5py pillow matplotlib
h5py
:读写 HDF5 文件。PIL
/pillow
:读取 JPG 图片。matplotlib
(可选):验证图片数据。
-
数据形状:
- JPG 图片通常为
(height, width, channels)
,例如 RGB 图片为(H, W, 3)
,灰度图为(H, W)
。 - 确保写入 HDF5 的数组形状与读取时一致。
- JPG 图片通常为
-
扩展场景:
- 批量图片存储:可将多张图片保存在不同数据集或分组中。
- 压缩存储:添加
compression="gzip"
参数节省空间:f.create_dataset("image_data", data=image_array, compression="gzip")
HDF5 文件结构示例
生成的 image_to_hdf5.h5
文件将包含:
/image_data # 数据集(存储图片像素数据)
attrs:
"format": "RGB"
"original_size": (width, height)
"description": "Converted from JPG to HDF5"
通过这种方式,你可以高效地将图片数据(包括元信息)存储在 HDF5 文件中,适用于科学计算或机器学习场景。