簡體   English   中英

如何將圖像(Texture2D)轉換為張量

[英]How to convert a image (Texture2D) to tensor

我有 c# TensorFlow.NET 在 Unity 中工作。 但它使用文件系統中的圖像。 我希望能夠使用來自 memory (Texture2D) 的圖像。

我嘗試關注一些使用 TensorFlowSharp 的人的例子。 但這沒有用。

我究竟做錯了什么?

注意:對於這兩個功能,我使用的是相同的圖像。 圖像為 512x512。 但兩張照片的結果是不同的。

// Doesn't work
private NDArray FromTextureToNDArray(Texture2D texture) {
    Color32[] pixels = texture.GetPixels32();

    byte[] floatValues = new byte[(texture.width * texture.height) * 3];

    for (int i = 0; i < pixels.Length; i++) {
        var color = pixels[i];

        floatValues[i * 3] = color.r;
        floatValues[i * 3 + 1] = color.g;
        floatValues[i * 3 + 2] = color.b;
    }

    Shape shape = new Shape(1, texture.width, texture.height, 3);
    NDArray image = new NDArray(floatValues, shape);

    return image;
}

// Works
private NDArray ReadFromFile(string fileName) {
    var graph = new Graph().as_default();

    // Change image
    var file_reader = tf.read_file(fileName, "file_reader");
    var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");

    var casted = tf.cast(decodeJpeg, TF_DataType.TF_UINT8);
    var dims_expander = tf.expand_dims(casted, 0);
    using (var sess = tf.Session(graph)) {
        return sess.run(dims_expander);
    }
}

我最終使用了Shaqian的這段代碼: https://github.com/shaqian/TF-Unity/blob/master/TensorFlow/Utils.cs

將此腳本添加到您的項目中,然后您可以像這樣使用它:

// Get image
byte[] imageData = Utils.DecodeTexture(texture, texture.width, texture.height, 0, Flip.VERTICAL);
Shape shape = new Shape(1, texture.width, texture.height, 3);
NDArray image = new NDArray(imageData, shape);

使用梭子魚作為中間步驟。

var encoder = new Unity.Barracuda.TextureAsTensorData(your_2d_texture);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM