如何将 Byte[](解码为 PNG 或 JPG)转换为 Tensorflows Tensor



我正在尝试在Unity的项目中使用Tensorflowsharp。

我面临的问题是,对于转换,您通常使用第二个 Graph 将输入转换为张量。使用的函数DecodeJpg和DecodePng在Android上不受支持,那么如何将该输入转换为张量?

private static void ConstructGraphToNormalizeImage(out TFGraph graph, out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
    const int W = 224;
    const int H = 224;
    const float Mean = 117;
    const float Scale = 1;
    graph = new TFGraph();
    input = graph.Placeholder(TFDataType.String);
    output = graph.Cast(graph.Div(
        x: graph.Sub(
            x: graph.ResizeBilinear(
                images: graph.ExpandDims(
                    input: graph.Cast(
                        graph.DecodeJpeg(contents: input, channels: 3), DstT: TFDataType.Float),
                    dim: graph.Const(0, "make_batch")),
                size: graph.Const(new int[] { W, H }, "size")),
            y: graph.Const(Mean, "mean")),
        y: graph.Const(Scale, "scale")), destinationDataType);
}

其他解决方案似乎会产生不准确的结果。

也许以某种方式带有垫子对象?

和我的编辑:我在 Unity 中的 c# 中实现了一些 comparabel,它部分工作。它根本不准确。我将如何找出平均值?而且我找不到有关 rgb 订单的任何信息。?我对此真的很陌生,所以也许我只是忽略了它。(Tensorflow.org(使用在 1.4 中训练的 MobileNet。

  public TFTensor transformInput(Color32[] pic, int texturewidth, int textureheight)
    {
        const int W = 224;
        const int H = 224;
        const float imageMean = 128;
        const float imageStd = 128;
        float[] floatValues = new float[texturewidth * textureheight * 3];
        for (int i = 0; i < pic.Length; ++i)
        {
            var color = pic[i];
            var index = i * 3;
            floatValues[index] = (color.r - imageMean) / imageStd;
            floatValues[index + 1] = (color.g - imageMean) / imageStd;
            floatValues[index + 2] = (color.b - imageMean) / imageStd;
        }
        TFShape shape = new TFShape(1, W, H, 3);
        return TFTensor.FromBuffer(shape, floatValues, 0, floatValues.Length);
    }

与其输入字节数组然后使用 DecodeJpeg,不如馈送实际的浮点数组,你可以得到这样的结果:

https://github.com/tensorflow/tensorflow/blob/3f4662e7ca8724f760db4a5ea6e241c99e66e588/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowImageClassifier.java#L134

float[] floatValues = new float[inputSize * inputSize * 3];
int[] intValues = new int[inputSize * inputSize];
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < intValues.length; ++i) {
      final int val = intValues[i];
      floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
      floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
      floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
}
Tensor<Float> input = Tensors.create(floatValues);

为了使用"Tensors.create((",你至少需要有Tensorflow版本1.4。

在将图像放入@sladomic函数之前,您可能没有裁剪和缩放图像。

我设法将一个在Unity中使用TensorflowSharp进行对象分类的示例组合在一起。它适用于官方 Tensorflow Android 示例中的模型,也适用于我自训练的 MobileNet 模型。您所需要的只是替换模型并设置您的均值和标准,在我的例子中,它们都等于 224。

最新更新