Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple Go module for writing a single array of 64 bit floating point numbers to a HDF5 formatted file (with attributes).
package main
import (
// generate an array of random numbers in range
func randomFloat64(low float64, high float64, size int) []float64 {
res := make([]float64, size)
for i := range res {
res[i] = low + rand.Float64() * (high - low)
return res
// write image data to HDF5 file
func writeImageData(fileName string, image []float64, height int, width int) {
// create a new HDF5 file
file, err := hdf5.CreateFile(fileName, hdf5.F_ACC_TRUNC)
if err != nil {
defer file.Close()
// create a Dataspace of size 'len(image)'
dims := []uint{uint(len(image))}
space, err := hdf5.CreateSimpleDataspace(dims, nil)
if err != nil {
panic("Failed to create image Dataspace")
// create a Datatype from the image type
dtype, err := hdf5.NewDatatypeFromValue(image[0])
if err != nil {
panic("Failed to create dtype")
// create the Dataset itself
dataset, err := file.CreateDataset("data", dtype, space)
// write the image data to the dataset
err = dataset.Write(&image)
if err != nil {
panic("Failed to write image data")
scalar, err := hdf5.CreateDataspace(hdf5.S_SCALAR)
if err != nil {
panic("Failed to create scalar dataspace")
var timestamp = time.Now().UnixNano() / 1000000000 // time in seconds
heightAttr, err := dataset.CreateAttribute("height", hdf5.T_NATIVE_UINT32, scalar)
heightAttr.Write(&height, hdf5.T_NATIVE_UINT32)
widthAttr, err := dataset.CreateAttribute("width", hdf5.T_NATIVE_UINT32, scalar)
widthAttr.Write(&width, hdf5.T_NATIVE_UINT32)
timeAttr, err := dataset.CreateAttribute("timestamp", hdf5.T_NATIVE_FLOAT, scalar)
timeAttr.Write(&timestamp, hdf5.T_NATIVE_FLOAT)
// close dataset & file
func main(){
height := 10
width := 10
arr := randomFloat64(0.0, 1.0, height * width)
writeImageData("alt.h5", arr, height, width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.