0

我要保存。JPG来自张量的图像文件,带有TensorFlowSharp. 我试图GetValue()获取张量的值,但我总是遇到一个问题InvalidCastException: Specified cast is not valid.

统一显示的问题如下:

InvalidCastException:指定的强制转换无效。TensorFlowModel.CallTFmodel.CallTFmodel_Start (System.Byte[] originalbytes, System.String SendPathName) (在 Assets/Sample/Glass/Scripts/CallTFmodel.cs:84) Camera2picture+d__9.MoveNext () (在 Assets/Sample/Glass/Scripts /Camera2picture.cs:71) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (在 /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

var runner = session.GetRunner();

// "input", "ps";
runner.AddInput(graph["images"][0], tensorNormalized).Fetch(graph["Tanh"][0]); 
var output = runner.Run();
var result = output[0];

// the issue is happened here. 
byte[] result_bytes = (byte[])result.GetValue(jagged:true); 
// my target is to use GetValue() to transform tensor to array with type byte.
// this line is to write the byte array to a image file.
File.WriteAllBytes(SendPathName, result_bytes); 

我的目标是找到一种使用 TensorFlowSharp 将张量保存为 .JPG 图像文件的方法,但不幸的是,我尝试了很多次都找不到解决方案。

4

1 回答 1

0

在 TensorflowSharp 中,您可以这样做:

    private byte[] TensorToBitmap(TFTensor image)
    {
        var graph = new TFGraph();
        var input = graph.Placeholder(TFDataType.Float);
        var output = graph.Cast(input, TFDataType.UInt8);
        output = graph.EncodeJpeg(output);

        using (var session = new TFSession(graph))
        {
            var result = session.Run(
                inputs: new[] { input },
                inputValues: new[] { image },
                outputs: new[] { output });

            var tensor = result[0];
            byte[] buffer = new byte[(int)tensor.TensorByteSize - 10];
            System.Runtime.InteropServices.Marshal.Copy(tensor.Data + 10, buffer, 0, buffer.Length);
            return buffer;
        }
    }

我不知道为什么,但你必须跳过前 10 个字节。

于 2019-04-04T08:03:20.113 回答