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

How to convert a image (Texture2D) to tensor

我有 c# TensorFlow.NET 在 Unity 中工作。但它使用文件系统中的图像。我希望能够使用内存中的图像 (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);

使用 Barracuda 作为中间步骤。

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