[英]Extracting images from h5 file
我有保存到 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()
只是另一个问题,希望不是问题:/
第二个 h5 文件没有组或子组,当我尝试提取图像时,它向我显示此错误。 这些是深度图像。
imwrite function 中可能有一些错误,因为当我打印 IMAGE_arr 时它工作正常。
这是我的代码:
import h5py
import numpy as np
import cv2
save_dir = 'C:/Users.../depth_imgs'
with h5py.File('depth.h5', 'r') as hf:
image_ds = hf
for imagename in image_ds.keys():
IMAGE_arr = image_ds[imagename][()]
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
cv2.waitKey(1000)
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.