CoderOnly
CoderOnly

Reputation: 1742

How can I visualise an image in h5 format data?

import h5py
f = h5py.File('the_file.h5', 'r')
one_data = f['key']
print(one_data.shape)
print(one_data.dtype)
print(one_data)

I use the code above to print the info. The print result is:

(320, 320, 3)
uint8
<HDF5 dataset "1458552843.750": shape (320, 320, 3), type "|u1">

Upvotes: 5

Views: 18331

Answers (3)

alanwilter
alanwilter

Reputation: 582

It can be even simpler:

pip install Pillow h5py

Then

import h5py
from PIL import Image

f = h5py.File('the_file.h5', 'r')
dset = f['key'][:]
img = Image.fromarray(dset.astype("uint8"), "RGB")
img.save("test.png")

Upvotes: 0

MF.OX
MF.OX

Reputation: 2546

The solution provided by jet works just fine, but has the drawback of needing to include OpenCV (cv2). In case you are not using OpenCV for anything else, it is a bit overkill to install/include it just for saving the file. Alternatively you can use imageio.imwrite (doc) which has lighter footprint, e.g.:

import imageio
import numpy as np
import h5py

f = h5py.File('the_file.h5', 'r')
dset = f['key']
data = np.array(dset[:,:,:])
file = 'test.png' # or .jpg
imageio.imwrite(file, data)

Installing imageio is as simple as pip install imageio.

Also, matplotlib.image.imsave (doc) provides similar image saving functionality.

Upvotes: 2

CoderOnly
CoderOnly

Reputation: 1742

import cv2
import numpy as np
import h5py
f = h5py.File('the_file.h5', 'r')
dset = f['key']
data = np.array(dset[:,:,:])
file = 'test.jpg'
cv2.imwrite(file, data)

Upvotes: 5

Related Questions