如何解决如何在TensorflowJs中将张量解码为base64?
我正在开发使用TensorflowJs的React Native应用程序。我正在使用cameraWithTensors
包中的tfjs-react-native
,它为我提供的图像为int32
类型的张量。我想将这些张量数据转换为base64,以便可以在应用程序中进行渲染。
不知何故,我找到了一种将base64数据转换为张量的解决方案,如下所示,但我不能相反。我找到了decodJpeg
个方法tfjs docs,但是它对面不可用。我尝试了许多解决方案,但没有一个起作用。
URItoTensor = async URI => {
const imgB64 = await FileSystem.readAsStringAsync(URI,{
encoding: FileSystem.EncodingType.Base64,});
const imgBuffer = tf.util.encodeString(imgB64,'base64').buffer;
const unit8 = new Uint8Array(imgBuffer)
const tensor = decodeJpeg(unit8);
return tensor;
}
解决方法
您可以使用toPixels将张量转换为画布,然后使用canvas.toDataURL
获得base64编码
const canvas = document.createElement('canvas');
canvas.width = tensor.shape.width
canvas.height = tensor.shape.height
await tf.browser.toPixels(tensor,canvas);
canvas.toDataURL() // will return the base64 encoding
以上内容将在浏览器中运行,但不适用于react-native。 React-native具有binaryToBase64
可以从类型数组转换;
const bytes = tensor.dataSync(); // can also use the async .data
const encoded = binaryToBase64(bytes); // base64 string
更新
encodeString
不是用于将base64转换为下划线表示为图像的张量的方法。 EncodeString仅将字符串编码为typedArray。这是将图像加载到张量的方法。甚至之前都不需要使用base64字符串。
// Load an image as a Uint8Array
const response = await fetch('path/of/image',{},{ isBinary: true });
const imageDataArrayBuffer = await response.arrayBuffer();
cosnt imageData = new Uint8Array(imageDataArrayBuffer);
// Decode image data to a tensor
const tensor = decodeJpeg(imageData);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。