【问题标题】:How to decode a tensor into base64 in TensorflowJs?如何在 TensorflowJs 中将张量解码为 base64?
【发布时间】:2020-10-15 07:14:23
【问题描述】:

我正在开发一个使用 TensorflowJs 的反应原生应用程序。我正在使用来自tfjs-react-native 包的cameraWithTensors,它将图像作为int32 类型的张量提供给我。我想将这些张量数据转换为 base64,以便在应用程序中呈现它。

不知何故,我找到了一种将 base64 数据转换为张量的解决方案,如下所示,但我不能反其道而行之。我找到了decodJpeg 方法 tfjs 文档,但它相反不可用。我尝试了很多解决方案,但都没有奏效。

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;
    }

【问题讨论】:

    标签: react-native base64 decode tensor tensorflow.js


    【解决方案1】:

    您可以使用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 可以从 typedarray 转换;

    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);
    

    【讨论】:

    • 感谢您的帮助,但它不起作用,因为变量 document 不适用于 React Native。我正在开发一个移动应用程序。你能帮我解决这个问题吗?
    • 不!那也不行……对这件事太厌倦了。我只想在我的应用中显示我的图像。
    • 不是错误,但是当我在 Image 类的源中作为 uri 传递时,编码的 base64 不显示任何内容。在我上面的代码中,当我将 unit8 数组转换回 base64 时,它再次运行良好,但 decodeJpeg 方法后的张量却不行。
    • 是否需要在解码字符串的开头附加"data:image/png;base64,"?您是否也尝试过使用tf.decodeString (bytes, 'base64')
    • 是的!我尝试了所有解决方案,但都没有奏效。我分别交叉检查了原始数组和base64以及转换后的数组和base64,但它们是不同的。我尝试使用 png、jpg、jpeg 等附加 data:image..,但它仍然无法正常工作,这非常令人失望。我什至尝试反转 decodeJpeg 方法:(
    猜你喜欢
    • 2021-01-25
    • 2020-01-24
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多