• C# Onnx PP-HumanSeg 人像分割


    目录

    效果

    模型信息

    项目

    代码

    下载


    效果

    图片源自网络侵删 

    模型信息

    Inputs
    -------------------------
    name:x
    tensor:Float[1, 3, 192, 192]
    ---------------------------------------------------------------

    Outputs
    -------------------------
    name:tf.identity
    tensor:Float[1, 192, 192, 2]
    ---------------------------------------------------------------

    项目

    VS2022

    .net framework 4.8

    OpenCvSharp 4.8

    Microsoft.ML.OnnxRuntime 1.16.2

    代码

    using Microsoft.ML.OnnxRuntime.Tensors;
    using Microsoft.ML.OnnxRuntime;
    using OpenCvSharp;
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Linq;
    using System.Drawing;

    namespace Onnx_Demo
    {
        public partial class frmMain : Form
        {
            public frmMain()
            {
                InitializeComponent();
            }

            string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
            string image_path = "";

            DateTime dt1 = DateTime.Now;
            DateTime dt2 = DateTime.Now;

            float conf_threshold = 0.9f;

            int inpWidth;
            int inpHeight;

            int outHeight, outWidth;

            Mat image;

            string model_path = "";

            SessionOptions options;
            InferenceSession onnx_session;
            Tensor input_tensor;
            List input_ontainer;

            IDisposableReadOnlyCollection result_infer;
            DisposableNamedOnnxValue[] results_onnxvalue;

            private void button1_Click(object sender, EventArgs e)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = fileFilter;
                if (ofd.ShowDialog() != DialogResult.OK) return;

                pictureBox1.Image = null;
                pictureBox2.Image = null;
                textBox1.Text = "";

                image_path = ofd.FileName;
                pictureBox1.Image = new System.Drawing.Bitmap(image_path);
                image = new Mat(image_path);
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                // 创建输入容器
                input_ontainer = new List();

                // 创建输出会话
                options = new SessionOptions();
                options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
                options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

                // 创建推理模型类,读取本地模型文件
                model_path = "model/model_float32.onnx";

                inpHeight = 192;
                inpWidth = 192;

                outHeight = 192;
                outWidth = 192;

                onnx_session = new InferenceSession(model_path, options);

                // 创建输入容器
                input_ontainer = new List();

                image_path = "test_img/1.jpg";
                pictureBox1.Image = new Bitmap(image_path);

            }

            private unsafe void button2_Click(object sender, EventArgs e)
            {
                if (image_path == "")
                {
                    return;
                }
                textBox1.Text = "检测中,请稍等……";
                pictureBox2.Image = null;
                System.Windows.Forms.Application.DoEvents();

                image = new Mat(image_path);

                Mat resize_image = new Mat();
                Cv2.Resize(image, resize_image, new OpenCvSharp.Size(inpWidth, inpHeight));

                float[] input_tensor_data = new float[1 * 3 * inpWidth * inpHeight];
                int row = resize_image.Rows;
                int col = resize_image.Cols;
                for (int c = 0; c < 3; c++)
                {
                    for (int i = 0; i < inpHeight; i++)
                    {
                        for (int j = 0; j < inpWidth; j++)
                        {
                            byte pix = ((byte*)(resize_image.Ptr(i).ToPointer()))[j * 3 + c];
                            input_tensor_data[c * row * col + i * col + j] = (float)((pix / 255.0-0.5)/0.5);
                        }
                    }
                }

                input_tensor = new DenseTensor(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });

                //将 input_tensor 放入一个输入参数的容器,并指定名称
                input_ontainer.Add(NamedOnnxValue.CreateFromTensor("x", input_tensor));

                dt1 = DateTime.Now;
                //运行 Inference 并获取结果
                result_infer = onnx_session.Run(input_ontainer);
                dt2 = DateTime.Now;

                //将输出结果转为DisposableNamedOnnxValue数组
                results_onnxvalue = result_infer.ToArray();

                float[] mask = results_onnxvalue[0].AsTensor().ToArray();

                Mat mask_out = new Mat(outHeight, outWidth, MatType.CV_32FC2, mask);

                Cv2.Resize(mask_out, mask_out, new OpenCvSharp.Size(image.Cols, image.Rows));

                Mat result_image = image.Clone();

                for (int h = 0; h < result_image.Rows; h++)
                {
                    for (int w = 0; w < result_image.Cols; w++)
                    {
                        float pix = mask_out.At(h, w);
                        if (pix > conf_threshold)
                        {
                            Vec3b vec3B = result_image.At(h, w);

                            vec3B.Item0 = 0;
                            vec3B.Item1 = 255;
                            vec3B.Item2 = 0;

                            result_image.Set(h, w, vec3B);
                        }
                    }
                }

                if (pictureBox2.Image != null)
                {
                    pictureBox2.Image.Dispose();
                }

                pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());
                textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";

                mask_out.Dispose();
                image.Dispose();
                resize_image.Dispose();
                result_image.Dispose();
            }

            private void pictureBox2_DoubleClick(object sender, EventArgs e)
            {
                Common.ShowNormalImg(pictureBox2.Image);
            }

            private void pictureBox1_DoubleClick(object sender, EventArgs e)
            {
                Common.ShowNormalImg(pictureBox1.Image);
            }
        }
    }

    1. using Microsoft.ML.OnnxRuntime.Tensors;
    2. using Microsoft.ML.OnnxRuntime;
    3. using OpenCvSharp;
    4. using System;
    5. using System.Collections.Generic;
    6. using System.Windows.Forms;
    7. using System.Linq;
    8. using System.Drawing;
    9. namespace Onnx_Demo
    10. {
    11. public partial class frmMain : Form
    12. {
    13. public frmMain()
    14. {
    15. InitializeComponent();
    16. }
    17. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
    18. string image_path = "";
    19. DateTime dt1 = DateTime.Now;
    20. DateTime dt2 = DateTime.Now;
    21. float conf_threshold = 0.9f;
    22. int inpWidth;
    23. int inpHeight;
    24. int outHeight, outWidth;
    25. Mat image;
    26. string model_path = "";
    27. SessionOptions options;
    28. InferenceSession onnx_session;
    29. Tensor<float> input_tensor;
    30. List<NamedOnnxValue> input_ontainer;
    31. IDisposableReadOnlyCollection<DisposableNamedOnnxValue> result_infer;
    32. DisposableNamedOnnxValue[] results_onnxvalue;
    33. private void button1_Click(object sender, EventArgs e)
    34. {
    35. OpenFileDialog ofd = new OpenFileDialog();
    36. ofd.Filter = fileFilter;
    37. if (ofd.ShowDialog() != DialogResult.OK) return;
    38. pictureBox1.Image = null;
    39. pictureBox2.Image = null;
    40. textBox1.Text = "";
    41. image_path = ofd.FileName;
    42. pictureBox1.Image = new System.Drawing.Bitmap(image_path);
    43. image = new Mat(image_path);
    44. }
    45. private void Form1_Load(object sender, EventArgs e)
    46. {
    47. // 创建输入容器
    48. input_ontainer = new List<NamedOnnxValue>();
    49. // 创建输出会话
    50. options = new SessionOptions();
    51. options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;
    52. options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行
    53. // 创建推理模型类,读取本地模型文件
    54. model_path = "model/model_float32.onnx";
    55. inpHeight = 192;
    56. inpWidth = 192;
    57. outHeight = 192;
    58. outWidth = 192;
    59. onnx_session = new InferenceSession(model_path, options);
    60. // 创建输入容器
    61. input_ontainer = new List<NamedOnnxValue>();
    62. image_path = "test_img/1.jpg";
    63. pictureBox1.Image = new Bitmap(image_path);
    64. }
    65. private unsafe void button2_Click(object sender, EventArgs e)
    66. {
    67. if (image_path == "")
    68. {
    69. return;
    70. }
    71. textBox1.Text = "检测中,请稍等……";
    72. pictureBox2.Image = null;
    73. System.Windows.Forms.Application.DoEvents();
    74. image = new Mat(image_path);
    75. Mat resize_image = new Mat();
    76. Cv2.Resize(image, resize_image, new OpenCvSharp.Size(inpWidth, inpHeight));
    77. float[] input_tensor_data = new float[1 * 3 * inpWidth * inpHeight];
    78. int row = resize_image.Rows;
    79. int col = resize_image.Cols;
    80. for (int c = 0; c < 3; c++)
    81. {
    82. for (int i = 0; i < inpHeight; i++)
    83. {
    84. for (int j = 0; j < inpWidth; j++)
    85. {
    86. byte pix = ((byte*)(resize_image.Ptr(i).ToPointer()))[j * 3 + c];
    87. input_tensor_data[c * row * col + i * col + j] = (float)((pix / 255.0-0.5)/0.5);
    88. }
    89. }
    90. }
    91. input_tensor = new DenseTensor<float>(input_tensor_data, new[] { 1, 3, inpHeight, inpWidth });
    92. //input_tensor 放入一个输入参数的容器,并指定名称
    93. input_ontainer.Add(NamedOnnxValue.CreateFromTensor("x", input_tensor));
    94. dt1 = DateTime.Now;
    95. //运行 Inference 并获取结果
    96. result_infer = onnx_session.Run(input_ontainer);
    97. dt2 = DateTime.Now;
    98. //将输出结果转为DisposableNamedOnnxValue数组
    99. results_onnxvalue = result_infer.ToArray();
    100. float[] mask = results_onnxvalue[0].AsTensor<float>().ToArray();
    101. Mat mask_out = new Mat(outHeight, outWidth, MatType.CV_32FC2, mask);
    102. Cv2.Resize(mask_out, mask_out, new OpenCvSharp.Size(image.Cols, image.Rows));
    103. Mat result_image = image.Clone();
    104. for (int h = 0; h < result_image.Rows; h++)
    105. {
    106. for (int w = 0; w < result_image.Cols; w++)
    107. {
    108. float pix = mask_out.At<float>(h, w);
    109. if (pix > conf_threshold)
    110. {
    111. Vec3b vec3B = result_image.At<Vec3b>(h, w);
    112. vec3B.Item0 = 0;
    113. vec3B.Item1 = 255;
    114. vec3B.Item2 = 0;
    115. result_image.Set<Vec3b>(h, w, vec3B);
    116. }
    117. }
    118. }
    119. if (pictureBox2.Image != null)
    120. {
    121. pictureBox2.Image.Dispose();
    122. }
    123. pictureBox2.Image = new System.Drawing.Bitmap(result_image.ToMemoryStream());
    124. textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";
    125. mask_out.Dispose();
    126. image.Dispose();
    127. resize_image.Dispose();
    128. result_image.Dispose();
    129. }
    130. private void pictureBox2_DoubleClick(object sender, EventArgs e)
    131. {
    132. Common.ShowNormalImg(pictureBox2.Image);
    133. }
    134. private void pictureBox1_DoubleClick(object sender, EventArgs e)
    135. {
    136. Common.ShowNormalImg(pictureBox1.Image);
    137. }
    138. }
    139. }

    下载

    源码下载

  • 相关阅读:
    LeetCode34.在排序数组中查找元素的第一个和最后一个位置
    【AI】数学基础——最优化
    Excel - 插入空白行
    【软考】12.3 质量管理/风险管理
    【深度学习实验】线性模型(三):使用Pytorch实现简单线性模型:搭建、构造损失函数、计算损失值
    HarmonyOS系统中内核实现NFC无线通信的方法
    46.Java正则表达式
    设计模式(19)命令模式
    【JavaSpring】Aop切入点表达式
    Python 常用基础模块(四):sys模块
  • 原文地址:https://blog.csdn.net/lw112190/article/details/134519517