I am currently trying to port the code from https://github.com/AsuharietYgvar/AppleNeuralHash2ONNX/blob/master/nnhash.py to C# using Micrisoft.ML.OnnxRuntime. For Image loading I use SixLabors.ImageSharp.
So far loading the onnx session file works but I think I have trouble preprocessing the input image in a correct way. The original code does like so:
image = Image.open(sys.argv[3]).convert('RGB')
image = image.resize([360, 360])
arr = np.array(image).astype(np.float32) / 255.0
arr = arr * 2.0 - 1.0
arr = arr.transpose(2, 0, 1).reshape([1, 3, 360, 360])
And now I have trouble finding out how to transpose the image data array. My code so far is like this:
img.Mutate(x =>
{
x.Resize(new ResizeOptions
{
Size = new SixLabors.ImageSharp.Size(360, 360),
Mode = SixLabors.ImageSharp.Processing.ResizeMode.Stretch
});
});
Tensor<float> arr = new DenseTensor<float>(new int[] { 1, 3, 360, 360 });
for (int y = 0; y < img.Height; y++)
{
Span<Rgb24> pixelSpan = img.GetPixelRowSpan(y);
for (int x = 0; x < img.Width; x++)
{
arr[0, 0, y, x] = (pixelSpan[x].R / 255f * 2) - 1;
arr[0, 1, y, x] = (pixelSpan[x].G / 255f * 2) - 1;
arr[0, 2, y, x] = (pixelSpan[x].B / 255f * 2) - 1;
}
}
but it seems like setting the order/layout of the Tensor is wrong. The problem is, I cant find any transform
function in the Microsoft.ML.OnnxRuntime library to resemble the last line (arr.transpose(2, 0, 1).reshape([1, 3, 360, 360])
) in the original code.
So how could I correctly build the input image Tensor for Microsoft.ML.OnnxRuntime?