Feb-08-2024, 09:38 AM
Some time ago, I used h5py to record pictures into a h5 file (very usefull and powerfull); in the following example:
(you can create a gif animated with ImageMagick for instance, but it's another topic)
Here after 2 screenshots of the picture into hdfview.
Maybe it add some features on your project.
Paul
- a basic image is created using matplotlib
- the image is saved into the h5 file as a picture (you can see it under hdfview for instance)
- the image is saved into the h5 file as an array
- the previous picture is recovered an saved locally into a gif image
(you can create a gif animated with ImageMagick for instance, but it's another topic)
Here after 2 screenshots of the picture into hdfview.
Maybe it add some features on your project.
Paul
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvas import os, h5py Path = str(os.getcwd()) ### 0) to create a fig plt.style.use('_mpl-gallery') # make data x = np.linspace(0, 10, 100) y = 4 + 2 * np.sin(2 * x) # plot fig, ax = plt.subplots(figsize=(16,16)) ax.plot(x, y, linewidth=2.0) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() ## 1) Convertion Matplotlib fig into aNumpyArray ---> mandatory to change the picture into a matrix canvas = FigureCanvas(fig) canvas.draw() FigArray = np.array(canvas.renderer.buffer_rgba()) ## 2) write directly a picture into the h5 file --> Note dataset is MANDATORY h5 = h5py.File(Path + '/test_picture.h5', 'w') ImageDataset = h5.create_dataset(name = "Example_picture", data = FigArray, dtype = 'uint8', compression = 'gzip') ImageDataset.attrs["CLASS"] = np.string_("IMAGE") ImageDataset.attrs["IMAGE_VERSION"] = np.string_("1.2") ImageDataset.attrs["IMAGE_SUBCLASS"] = np.string_("IMAGE_TRUECOLOR") ImageDataset.attrs["INTERLACE_MODE"] = np.string_("INTERLACE_MODE") ImageDataset.attrs["IMAGE_MINMAXRANGE"] = np.uint8(0.255) h5.close() ## 3) Write the fig into a basic array (the h5 file) h5 = h5py.File(Path + '/test_array.h5', 'w') NpArrays = h5.create_group('Fig') DatasetFigs = NpArrays.create_dataset(name = 'Example of array', data = FigArray, dtype='f', compression = 'gzip') h5.flush() h5.close() ## 4) array recovering => save into a gif file from PIL import Image as im with h5py.File(Path + '/test_picture.h5','r') as pict: data = pict.get('/Example_picture') Array = np.array(data) # array is converted int a picture Picture = im.fromarray(Array) Picture.save(Path + '/export.gif')