C#使用ONNX模型

该文章展示了如何在C#中加载和运行ONNX模型进行图像识别。首先,创建InferenceSession对象从ONNX模型文件读取模型。接着,读取并调整图像尺寸以适应模型要求,然后执行预处理步骤,包括调整大小、填充和减去像素均值。最后,运行模型并获取预测结果。
摘要由CSDN通过智能技术生成

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";


            // 读取图片
            // Read image
            using Image<Rgb24> image = Image.Load<Rgb24>(imageFilePath);

            // 改变图片大小至模型运算指定的大小
            // Resize image
            float ratio = 512f / Math.Min(image.Width, image.Height);
            image.Mutate(x => x.Resize((int)(512), (int)(512)));

            // Preprocess image
            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);

            // 对运行结果解析
            // Postprocess to get predictions
            var resultsArray = results.ToArray();
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值