Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a tensor to a Uint8Array array in tensorflowjs

I use model.predict()to output a tensor A(size:512*512*3) by tensorflow.js and then I reshape it to A.reshape(512*512*3). But now I want to convert this tensor to an array so I can use it with three.js. How to solve this problem?

like image 773
YifanLu Avatar asked Sep 11 '26 18:09

YifanLu


1 Answers

To convert a tensor to an array, You can use

  • data() or dataSync() to have a flatten typedarray

But currently the supported types are float32, int32; therefore the corresponding typedArray will be Float32Array and Int32Array. The typedarray constructors can be used to change the type of the typedarray

a = tf.tensor([1, 2, 3, 4])

buffer = a.dataSync().buffer

console.log(new Uint8Array(buffer))

console.log(new Uint16Array(buffer))

console.log(new Float32Array(buffer))

// To retrieve easily uint8 type, one can cast the tensor to `int32`

a = tf.tensor([1, 2, 3, 4], undefined, 'int32')

console.log(a.dtype)

buffer = a.dataSync().buffer
console.log(new Uint8Array(buffer))
console.log(new Float32Array(buffer))
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>
like image 178
edkeveked Avatar answered Sep 14 '26 06:09

edkeveked