AsiaLootus
AsiaLootus

Reputation: 112

How to save a pyplot image as .h5 file in python and visualize with HDFView?

I'm facing this problem: I would like to save the plot I produced inside an .h5 file.

What I'm doing now is::

import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(10,10)
fig = plt.scatter(data[0],data[1])
plt.savefig('image.jpg')

then I create the .h5 file as follow:

import cv2
import h5py
image = cv2.imread("image.jpg")
with h5py.File("h5_file.h5", 'a') as hf:   
        Xset = hf.create_dataset(
            name="img", 
            data=image,
            shape=image.shape,
            maxshape=image.shape)

And, visualizing with HDFView, I can see the result as follow: enter image description here

I need to open it "as Image" and I can see a picture for each "table" of RGB.

What I need instead is the result of Tools>Convert Image to HDF5 in the HDFView, which is the following:

enter image description here

Any suggestion? Or any other h5 visualizer to be used?

Upvotes: 0

Views: 1225

Answers (1)

kcw78
kcw78

Reputation: 8046

The problem is not the HDF5 data. I copied your code and ran to create the 2 files. A comparison of the data (as NumPy arrays) shows them to be identical. The difference is the attributes:

  • When you read the image with cv2.imread() and save the data, no attributes are created.
  • When you use Tools>Convert Image to HDF5 to create the file, 5 attributes are added to the dataset. (Notice this dataset has a different file icon in HDFView.) The attributes are shown on the Object Attribute Info panel in HDFView and/or you can get them with the following code:

Code:

for k,v in ds2.attrs.items():
    print ('attr:',k,'=',v)

Output:

attr: CLASS = b'IMAGE'
attr: IMAGE_MINMAXRANGE = [  0 255]
attr: IMAGE_SUBCLASS = b'IMAGE_TRUECOLOR'
attr: IMAGE_VERSION = b'1.2'
attr: INTERLACE_MODE = b'INTERLACE_PIXEL'

You can add these attributes to your first file (created with cv2.imread() ) using the code below:

Xset.attrs.create('CLASS','IMAGE',dtype='S6')
Xset.attrs.create('IMAGE_MINMAXRANGE',[0, 255],dtype=np.uint8)      
Xset.attrs.create('IMAGE_SUBCLASS','IMAGE_TRUECOLOR',dtype='S16')
Xset.attrs.create('IMAGE_VERSION','1.2',dtype='S4')
Xset.attrs.create('INTERLACE_MODE','INTERLACE_PIXEL',dtype='S16')

Here is the image I see in HDFView after adding the attributes. It is almost the same - no more blurring, but the data point color is a different (gold vs blue). Not sure what causes that. Maybe something to do with the default pallete?

enter image description here

Upvotes: 1

Related Questions