'Load and process 3D image volume saved in hdf5 file format via vanilla JS

How can I load and process a 3D image volume, saved as an hdf5 file, directly in the frontend using JS?



Solution 1:[1]

This can be achieved using jsfive and numjs.

The following code cuts an 124x124 image, at z=10, y0=0, y1=124, x0=0, x1=124, from a volume of dimension 20x1400x700 (z,y,x). The 3D volume is stored in the h5 file under the key 'main'. The implementation uses a callback that provides more flexibility and makes the h5 file available outside the async function.

$(document).ready(function() {

  $("#datafile").change(async function loadData() {
    const reader = new FileReader();
    let file = $("#datafile")[0].files[0]
    let file_name = file.name
    reader.readAsArrayBuffer($("#datafile")[0].files[0]);
    reader.onload = () => storeResults(reader.result, file_name);
  })

  // callback function
  function storeResults(result, file_namet) {
    f = new hdf5.File(result, file_namet);
    let array = f.get('main').value
    // jsfive can only return 1D arrays from a read operation -> use numjs to reconstruct the 3D volume
    array = nj.array(array).reshape(20, 1400, 700)
    // slicing a 124x124 image from the volume
    // use reshape to drop the channel dimension 1x124x124 -> 124x124
    let img = array.slice([10, 11], [0, 124], [0, 124]).reshape(124, 124)
    // convert to image and save to canvas
    let resized = nj.images.resize(img, 124, 124)
    let $original = document.getElementById('original');
    $original.width = 124;
    $original.height = 124;
    nj.images.save(resized, $original);
    console.log("done")
  }

})
<!DOCTYPE html>
<html lang="eng">

<head>
  <!-- Import JQuery -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <!-- Import JSFive -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/hdf5.js"></script>
  <!-- Import NumJs-->
  <script src="https://cdn.jsdelivr.net/gh/nicolaspanel/[email protected]/dist/numjs.min.js"></script>
</head>

<body>
  <div>
    <h3>Original image (h<span id="h"></span>, w<span id="w"></span>)</h3>
    <canvas id="original" width=64 height=64></canvas>
  </div>

  <input type="file" id="datafile" name="file">

  <!-- Import main JS -->
  <script src="app.js"></script>
</body>

</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1