C#使用ONNX模型
var onnxModelPath = @"F:\D\AI_Model\LZ\weights\best.onnx";
using var session = new InferenceSession(onnxModelPath);
string _inputName = session.InputMetadata.Keys.First();
string imageFilePath = @"D:\\dataset\\LZ\\images\\train\\20230710152804042_6.jpg";
using Image<Rgb24> image = Image.Load<Rgb24>(imageFilePath);
float ratio = 512f / Math.Min(image.Width, image.Height);
image.Mutate(x => x.Resize((int)(512), (int)(512)));
var paddedHeight = (int)(Math.Ceiling(image.Height / 32f) * 32f);
var paddedWidth = (int)(Math.Ceiling(image.Width / 32f) * 32f);
Tensor<float> input = new DenseTensor<float>(new[] { 1,3, paddedHeight, paddedWidth });
var mean = new[] { 102.9801f, 115.9465f, 122.7717f };
for (int y = paddedHeight - image.Height; y < image.Height; y++)
{
image.ProcessPixelRows(im =>
{
var pixelSpan = im.GetRowSpan(y);
for (int x = paddedWidth - image.Width; x < image.Width; x++)
{
input[0,0, y, x] = pixelSpan[x].B - mean[0];
input[0,1, y, x] = pixelSpan[x].G - mean[1];
input[0,2, y, x] = pixelSpan[x].R - mean[2];
}
});
}
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor(_inputName, input)
};
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = session.Run(inputs);
var resultsArray = results.ToArray();