我有保存到 h5 文件中的图像,所以现在我想知道是否可以从文件夹中的 h5 文件中提取图像?我写了这段代码,但它不起作用。它将图像保存在文件夹中但无法打开。你可以在图片上看到。
dset.h5 包含 5 个图像,我需要保存这些图像。现在我只想保存一个 (hiking_125.jpg)。
`
import h5py
import numpy as np
import cv2
save_dir = 'C:/Users.../depth'
with h5py.File('dset.h5', 'r') as hf:
IMAGE = hf['image']
print(IMAGE['hiking_125.jpg'])
print(IMAGE['hiking_125.jpg'].dtype)
#IMAGE = np.array(IMAGE)
item = []
item = np.array(IMAGE['hiking_125.jpg']).reshape(-1, 500, 600, 3)
cv2.imwrite(f"{save_dir}/.jpg", item)
cv2.imshow('Color image', item)
print(item)
`
上面的代码中有一些小错误。
这段代码应该可以工作。它假设数据集
hf['image']['hiking_125.jpg']
是图像的 NumPy 数组,不需要重新整形)。添加注释代码以解决使用 cv.imshow()
显示图像的问题。
save_dir = 'C:/Users.../depth'
with h5py.File('dset.h5', 'r') as hf:
imagename = 'hiking_125.jpg'
# get an array from the imagename dataset:
IMAGE_arr = hf['image'][imagename][()]
# create image from array
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
# post image to a window
cv2.imshow(f'Image: {imagename}', IMAGE_arr)
# keep window posted for 2500 msec
cv2.waitKey(2500)
# destroy CV2 window when done
cv2.destroyAllWindows()
您可以使用以下代码扩展上面的代码以从数据集
hf['image']
导出所有图像。这是一个小修改,它使用循环通过使用 .keys()
方法获取数据集名称来创建每个文件。
with h5py.File('dset.h5', 'r') as hf:
image_ds = hf['image']
for imagename in image_ds.keys():
# get an array from the imagename dataset:
IMAGE_arr = image_ds[imagename][()]
# create image from array
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
# post image to a window
cv2.imshow(f'Image: {imagename}', IMAGE_arr)
# keep window posted for 2500 msec
cv2.waitKey(2500)
# destroy CV2 window when done
cv2.destroyAllWindows()
有没有办法在没有“imagename”的情况下做到这一点?