简体   繁体   English

如何将图像(Texture2D)转换为张量

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

I have c# TensorFlow.NET working in Unity.我有 c# TensorFlow.NET 在 Unity 中工作。 But it using an image from the file system.但它使用文件系统中的图像。 I want to be able to use an image from memory (Texture2D).我希望能够使用来自 memory (Texture2D) 的图像。

I tried to follow some examples of people using TensorFlowSharp.我尝试关注一些使用 TensorFlowSharp 的人的例子。 But that didn't work.但这没有用。

What am I doing wrong?我究竟做错了什么?

Note: with both functions, I am using the same image.注意:对于这两个功能,我使用的是相同的图像。 The image is 512x512.图像为 512x512。 but the result of both pictures is different.但两张照片的结果是不同的。

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

I ended up using this code from Shaqian: https://github.com/shaqian/TF-Unity/blob/master/TensorFlow/Utils.cs我最终使用了Shaqian的这段代码: https://github.com/shaqian/TF-Unity/blob/master/TensorFlow/Utils.cs

Add this script to your project and then you could use it like this:将此脚本添加到您的项目中,然后您可以像这样使用它:

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

Use Barracuda as step in between.使用梭子鱼作为中间步骤。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM