Leon
Leon

Reputation: 53

Extracting images from h5 file

I have images that are saved into h5 file, so now I'm wondering is it possible to extract images from h5 file in a folder? I wrote this code but it doesn't work. It save an image in folder but can't open. You can see that on the picture.

dset.h5 contains of 5 images and I need to save that images. For now I'm trying to save just one (hiking_125.jpg).

enter image description here

`

 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)

`

Upvotes: 0

Views: 3991

Answers (1)

kcw78
kcw78

Reputation: 8046

You have a number of small errors in the code above.

This code snippet should work. It assumes dataset hf['image']['hiking_125.jpg'] is NumPy array for the image and does not need to be reshaped). Note code added to address issues displaying the image with 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()

You can extend the code above to export all images from dataset hf['image'] with the following. It's a small modification that uses a loop to create each file by getting the dataset names using the .keys() method.

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

Upvotes: 2

Related Questions