如何在 tensorflowjs 中将张量转换为 Uint8Array 数组
How to convert a tensor to a Uint8Array array in tensorflowjs
我使用model.predict()
通过tensorflow.js输出一个张量A(size:512*512*3),然后我将它整形为A.reshape(512*512*3) .但现在我想将这个张量转换为一个数组,以便我可以将它与 three.js
一起使用。如何解决这个问题?
要将张量转换为数组,您可以使用
data()
或 dataSync()
有一个扁平的类型数组
但目前支持的类型有float32
、int32
;因此相应的 typedArray 将是 Float32Array 和 Int32Array。 typedarray 构造函数可用于更改 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/tfjs@1.0.0"> </script>
</head>
<body>
</body>
</html>
我使用model.predict()
通过tensorflow.js输出一个张量A(size:512*512*3),然后我将它整形为A.reshape(512*512*3) .但现在我想将这个张量转换为一个数组,以便我可以将它与 three.js
一起使用。如何解决这个问题?
要将张量转换为数组,您可以使用
data()
或dataSync()
有一个扁平的类型数组
但目前支持的类型有float32
、int32
;因此相应的 typedArray 将是 Float32Array 和 Int32Array。 typedarray 构造函数可用于更改 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/tfjs@1.0.0"> </script>
</head>
<body>
</body>
</html>