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?
1 Answer
To convert a tensor to an array, You can use
data()ordataSync()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>
3 Comments
YifanLu
Is data() OK? Because dataSync() will block the UI thread until the values are ready, which can cause performance issues.
edkeveked
You can use
data()YifanLu
After executing the data() function, is there any way to get the data after it is executed? Such as callback