今日工作总遇到需要C#中布置分割模型的需求,在此记录一下。
首先先看待部署模型的格式
以下是代码,输出是将得到的结果按二维数组输出
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML.OnnxRuntime.Tensors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.Fonts;
//using SixLabors.Fonts;
//using System.Drawing;
namespace Microsoft.ML.OnnxRuntime.Sample
{
class Program
{
public static void Main(string[] args)
{
onnxtest(args);
static int[,] onnxtest(string[] args)
{
// Read paths
string modelFilePath = @"D:\ZihaoLi\ONNXDeploy\output.onnx";
string imageFilePath = @"D:\ZihaoLi\ONNXDeploy\Camera0.bmp";
// Read image
using Image<Rgb24> image = SixLabors.ImageSharp.Image.Load<Rgb24>(imageFilePath);
// Resize image
image.Mutate(x => x.Resize(512, 512));
// Preprocess image
Tensor<float> input = new DenseTensor<float>(new[] { 1, 3, image.Height, image.Width });
for (int y = 0; y < image.Height; y++)
{
image.ProcessPixelRows(im =>
{
var pixelSpan = im.GetRowSpan(y);
for (int x = 0; x < image.Width; x++)
{
input[0, 0, y, x] = ((pixelSpan[x].R) / 255f - 0.5f) / 0.5f;
input[0, 1, y, x] = ((pixelSpan[x].G) / 255f - 0.5f) / 0.5f;
input[0, 2, y, x] = ((pixelSpan[x].B) / 255f - 0.5f) / 0.5f;
}
});
}
// Setup inputs and outputs
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor("x", input)
};
// Run inference
using var session = new InferenceSession(modelFilePath);
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = session.Run(inputs);
var Test = results.ToList()[0].AsTensor<long>().ToArray<long>();
int[,] res = new int[512, 512]; //RES为结果数组
int tmp = 0;
foreach (int i in Test)
{
res[tmp / 512, tmp % 512] = i;
tmp++;
}
for(int i = 0; i < 512; i++)
{
for(int j = 0; j < 512; j++)
{
if(res[i,j] == 1)
{
Console.WriteLine((i, j));
}
}
}
return (res);
}
}
}
}
因为第一次用C#部署,对于如何对图片进行处理,包括结果图mask与原图的叠加还不是很熟悉,如果有懂这方面的朋友欢迎指教~