如何使用TensorFlowSharp从Tensor编码.JPG文件?

时间:2019-04-03 14:16:46

标签: c# unity3d tensorflowsharp

我想使用JPG从Tensor保存。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枚举器,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图像文件的方法,但不幸的是,我尝试了很多次都找不到解决方法。

1 个答案:

答案 0 :(得分: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个字节。