C# OnnxRuntime 推理 常用前处理方法

static float[] mean = { 0.485f, 0.456f, 0.406f };
static float[] std = { 0.229f, 0.224f, 0.225f };
 
public static void Normalize(Mat src)
{
    src.ConvertTo(src, MatType.CV_32FC3,  1.0 / 255 );
 
    Mat[] bgr = src.Split();
    for (int i = 0; i < bgr.Length; ++i)
    {
        bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1 / std[i], (0.0 - mean[i]) / std[i]);
    }
 
    Cv2.Merge(bgr, src);
 
    foreach (Mat channel in bgr)
    {
        channel.Dispose();
    }
}
 
public static float[] ExtractMat(Mat src)
{
    OpenCvSharp.Size size = src.Size();
    int channels = src.Channels();
    float[] result = new float[size.Width * size.Height * channels];
    GCHandle resultHandle = default;
    try
    {
        resultHandle = GCHandle.Alloc(result, GCHandleType.Pinned);
        IntPtr resultPtr = resultHandle.AddrOfPinnedObject();
        for (int i = 0; i < channels; ++i)
        {
             Mat cmat =  new Mat(
                src.Height, src.Width,
                MatType.CV_32FC1,
                resultPtr + i * size.Width * size.Height * sizeof(float));
 
            Cv2.ExtractChannel(src, cmat, i);
            cmat.Dispose();
        }
    }
    finally
    {
        resultHandle.Free();
    }
 
    return result;
}

你可能感兴趣的:(C#,Onnx,AI,c#,计算机视觉,开发语言)