aisop/tests/TensorPreprocessing.Smoke/Program.cs

31 lines
1.8 KiB
C#

using System.Reflection;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using SopHelper.Engine.Inference;
var method = typeof(YoloDetector).Assembly.GetType("SopHelper.Engine.Inference.TensorPreprocessing")!
.GetMethod("FromRgb", BindingFlags.NonPublic | BindingFlags.Static)!;
using var parent = new Mat(5, 7, MatType.CV_8UC3, new Scalar(99, 98, 97));
using var roi = new Mat(parent, new Rect(1, 1, 3, 2));
var pixels = new[] { new Vec3b(0, 127, 255), new Vec3b(21, 42, 63), new Vec3b(1, 2, 3),
new Vec3b(4, 5, 6), new Vec3b(128, 129, 130), new Vec3b(254, 253, 252) };
for (var y = 0; y < 2; y++) for (var x = 0; x < 3; x++) roi.Set(y, x, pixels[y * 3 + x]);
if (roi.IsContinuous()) throw new Exception("Test must exercise padded row strides");
foreach (var contiguous in new[] { false, true })
{
using var source = contiguous ? roi.Clone() : new Mat(parent, new Rect(1, 1, 3, 2));
var tensor = (DenseTensor<float>)method.Invoke(null, new object[] { source })!;
if (!tensor.Dimensions.SequenceEqual(new[] { 1, 3, 2, 3 })) throw new Exception("Incorrect NCHW shape");
for (var y = 0; y < 2; y++) for (var x = 0; x < 3; x++)
{
var pixel = pixels[y * 3 + x];
if (tensor[0, 0, y, x] != pixel.Item0 / 255f || tensor[0, 1, y, x] != pixel.Item1 / 255f || tensor[0, 2, y, x] != pixel.Item2 / 255f)
throw new Exception("RGB order, normalization or row stride changed");
}
source.SetTo(Scalar.Black);
if (tensor[0, 2, 0, 0] != 1) throw new Exception("Tensor must own its normalized data");
// Restore the ROI because the non-contiguous case shares the parent buffer.
for (var y = 0; y < 2; y++) for (var x = 0; x < 3; x++) roi.Set(y, x, pixels[y * 3 + x]);
}
Console.WriteLine("PASS: RGB-to-NCHW normalization is exact for contiguous and padded Mats, preserves channel order and owns its data");