You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
using ConsoleApp10;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
string modelPath = "/Users/xuzhibin/Desktop/python/myScript/ssd300_vgg16.onnx";
using var session = new InferenceSession(modelPath);
var inputData=test.PreprocessImage("/Users/xuzhibin/Downloads/6ee927a0d4f2c9862a918798de175f5.jpg");
// 创建张量
var inputTensor = new DenseTensor<float>(inputData, new[] { 1, 3, 300, 300 });
// 设置输入
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor("input", inputTensor)
};
// 运行推理
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = session.Run(inputs);
// 获取输出
var boxes = results.FirstOrDefault(x => x.Name == "boxes").AsEnumerable<float>().ToArray();
var labels = results.FirstOrDefault(x => x.Name == "labels").AsEnumerable<long>().ToArray();
var scores = results.FirstOrDefault(x => x.Name == "scores").AsEnumerable<float>().ToArray();
// 输出前几个检测结果
Console.WriteLine("检测结果:");
for (int i = 0; i < Math.Min(5, labels.Length); i++)
{
Console.WriteLine($"Box: {boxes[i * 4 + 0]}, {boxes[i * 4 + 1]}, {boxes[i * 4 + 2]}, {boxes[i * 4 + 3]}");
Console.WriteLine($"Label: {labels[i]}");
Console.WriteLine($"Score: {scores[i]}");
}
using System.Drawing;
using System.Drawing.Imaging;
using SkiaSharp;
namespace ConsoleApp10;
public class test
{
public static float[] PreprocessImage(string imagePath)
{
// 读取图像为 SKBitmap
using var inputStream = File.OpenRead(imagePath);
using var originalBitmap = SKBitmap.Decode(inputStream);
// 创建新的 Bitmap,调整到模型需要的大小
using var resizedBitmap = originalBitmap.Resize(new SKImageInfo(300, 300), SKFilterQuality.High);
// 创建数据数组
var inputData = new float[1 * 3 * 300 * 300];
int index = 0;
// 遍历每个像素,将颜色值归一化到 [0, 1] 范围
for (int y = 0; y < resizedBitmap.Height; y++)
{
for (int x = 0; x < resizedBitmap.Width; x++)
{
var pixel = resizedBitmap.GetPixel(x, y);
inputData[index++] = pixel.Red / 255.0f;
inputData[index++] = pixel.Green / 255.0f;
inputData[index++] = pixel.Blue / 255.0f;
}
}
return inputData;
}
}
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: