优化:按行生成模型输入张量以减少逐像素原生调用

This commit is contained in:
tfarcraw 2026-11-08 22:22:30 +08:00
parent b61f14767b
commit 93a59735a0
5 changed files with 65 additions and 26 deletions

View File

@ -397,20 +397,7 @@ public class MediaPipeHandDetector : IDisposable
using var resized = new Mat();
Cv2.Resize(rgb, resized, new Size(size, size), 0, 0, InterpolationFlags.Area);
var tensor = new DenseTensor<float>([1, 3, size, size]);
for (var yy = 0; yy < size; yy++)
{
for (var xx = 0; xx < size; xx++)
{
var px = resized.At<Vec3b>(yy, xx);
tensor[0, 0, yy, xx] = px.Item0 / 255f;
tensor[0, 1, yy, xx] = px.Item1 / 255f;
tensor[0, 2, yy, xx] = px.Item2 / 255f;
}
}
return tensor;
return TensorPreprocessing.FromRgb(resized);
}
private static float IoU(DetRect a, DetRect b)

View File

@ -0,0 +1,29 @@
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
namespace SopHelper.Engine.Inference;
internal static class TensorPreprocessing
{
internal static unsafe DenseTensor<float> FromRgb(Mat rgb)
{
if (rgb.Type() != MatType.CV_8UC3) throw new ArgumentException("输入必须为 RGB 8 位三通道图像", nameof(rgb));
var width = rgb.Width;var height = rgb.Height;var plane = checked(width * height);
var tensor = new DenseTensor<float>([1, 3, height, width]);
var output = tensor.Buffer.Span;
for (var y = 0; y < height; y++)
{
// One native row lookup instead of a Mat.At call and tensor index calculation per pixel.
var row = (byte*)rgb.Ptr(y);
for (var x = 0; x < width; x++)
{
var target = y * width + x;var source = x * 3;
output[target] = row[source] / 255f;
output[plane + target] = row[source + 1] / 255f;
output[2 * plane + target] = row[source + 2] / 255f;
}
}
GC.KeepAlive(rgb);
return tensor;
}
}

View File

@ -123,18 +123,7 @@ public class YoloDetector : IDisposable
resized.CopyTo(roi);
}
var tensor = new DenseTensor<float>([1, 3, inputSize, inputSize]);
for (var y = 0; y < inputSize; y++)
{
for (var x = 0; x < inputSize; x++)
{
var px = canvas.At<Vec3b>(y, x);
tensor[0, 0, y, x] = px.Item0 / 255f;
tensor[0, 1, y, x] = px.Item1 / 255f;
tensor[0, 2, y, x] = px.Item2 / 255f;
}
}
var tensor = TensorPreprocessing.FromRgb(canvas);
var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor(InputName(), tensor) };

View File

@ -0,0 +1,30 @@
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");

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" /></ItemGroup>
</Project>