Как кодировать файл .JPG из Tensor с помощью TensorFlowSharp? - PullRequest
0 голосов
/ 03 апреля 2019

Я хочу сохранить. 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 / Glass Scrip/Camera2picture.cs:71) UnityEngine.SetupCoroutine.InvokeMoveNext (перечислитель System.Collections.IEnumerator, System.IntPtr returnValueAddress) (по адресу /Users/builduser/buildslave/unity/build/Runtime/Export/Runtime/Export/or)*

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

Моя цель - найти способ сохранить тензор в файл изображения .JPG с помощью TensorFlowSharp, но, к сожалению, я много раз пытался найти решение, чтобы сделать это.

1 Ответ

0 голосов
/ 04 апреля 2019

В 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 байтов.

...