C# Onnx 百度PaddleSeg发布的实时人像抠图PP-MattingV2

目录

效果

模型信息

项目

代码

下载


效果

图片源自网络侵删

模型信息

Inputs


name:img

tensor:Float[1, 3, 480, 640]


Outputs


name:sigmoid_5.tmp_0

tensor:Float[1, 1, 480, 640]


项目

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.65f;

int inpWidth;

int inpHeight;

int outHeight, outWidth;

Mat image;

string model_path = "";

SessionOptions options;

InferenceSession onnx_session;

Tensor<float> input_tensor;

Tensor<float> mask_tensor;

List<NamedOnnxValue> input_ontainer;

IDisposableReadOnlyCollection<DisposableNamedOnnxValue> 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<NamedOnnxValue>();

// 创建输出会话

options = new SessionOptions();

options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;

options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行

// 创建推理模型类,读取本地模型文件

model_path = "model/ppmattingv2_stdc1_human_480x640.onnx";

inpHeight = 480;

inpWidth = 640;

outHeight = 480;

outWidth = 640;

onnx_session = new InferenceSession(model_path, options);

// 创建输入容器

input_ontainer = new List<NamedOnnxValue>();

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

for (int c = 0; c < 3; c++)

{

for (int i = 0; i < inpHeight; i++)

{

for (int j = 0; j < inpWidth; j++)

{

float pix = ((byte*)(resize_image.Ptr(i).ToPointer()))[j * 3 + 2 - c];

input_tensor_data[c * inpHeight * inpWidth + i * inpWidth + j] = (float)(pix / 255.0);

}

}

}

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

//将 input_tensor 放入一个输入参数的容器,并指定名称

input_ontainer.Add(NamedOnnxValue.CreateFromTensor("img", 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<float>().ToArray();

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

mask_out *= 255;

mask_out.ConvertTo(mask_out, MatType.CV_8UC1);

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

Mat result_image = mask_out.Clone();

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

}

}

}

复制代码
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.65f;

        int inpWidth;
        int inpHeight;

        int outHeight, outWidth;

        Mat image;

        string model_path = "";

        SessionOptions options;
        InferenceSession onnx_session;
        Tensor<float> input_tensor;
        Tensor<float> mask_tensor;
        List<NamedOnnxValue> input_ontainer;

        IDisposableReadOnlyCollection<DisposableNamedOnnxValue> 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<NamedOnnxValue>();

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

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

            inpHeight = 480;
            inpWidth = 640;

            outHeight = 480;
            outWidth = 640;

            onnx_session = new InferenceSession(model_path, options);

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

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

            for (int c = 0; c < 3; c++)
            {
                for (int i = 0; i < inpHeight; i++)
                {
                    for (int j = 0; j < inpWidth; j++)
                    {
                        float pix = ((byte*)(resize_image.Ptr(i).ToPointer()))[j * 3 + 2 - c];
                        input_tensor_data[c * inpHeight * inpWidth + i * inpWidth + j] = (float)(pix / 255.0);
                    }
                }
            }

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

            //将 input_tensor 放入一个输入参数的容器,并指定名称
            input_ontainer.Add(NamedOnnxValue.CreateFromTensor("img", 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<float>().ToArray();

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

            mask_out *= 255;
            mask_out.ConvertTo(mask_out, MatType.CV_8UC1);

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

            Mat result_image = mask_out.Clone();

            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 天前
解决Visual Studio 2022编译工程速度慢的问题
开发语言·c++·ide·算法·计算机视觉·visual studio
THMAIL1 天前
深度学习从入门到精通 - 迁移学习实战:用预训练模型解决小样本难题
人工智能·python·深度学习·算法·机器学习·迁移学习
音视频牛哥1 天前
AI+ 行动意见解读:音视频直播SDK如何加速行业智能化
人工智能·音视频·人工智能+·ai+ 行动意见·rtsp/rtmp 播放器·低空经济视频链路·工业巡检视频传输
roman_日积跬步-终至千里1 天前
【软件架构设计(19)】软件架构评估二:软件架构分析方法分类、质量属性场景、软件评估方法发展历程
人工智能·分类·数据挖掘
.鱼子酱1 天前
机器学习 - 使用 ID3 算法从原理到实际举例理解决策树
算法·决策树·机器学习
镭眸1 天前
因泰立科技:用激光雷达重塑智能工厂物流生态
大数据·人工智能·科技
阿豪Jeremy1 天前
使用MS-SWIF框架对大模型进行SFT微调
人工智能
慧星云1 天前
双节模型创作大赛开赛啦:和魔多一起欢庆中秋国庆
人工智能·云计算·aigc
爆改模型1 天前
【ICCV2025】计算机视觉|即插即用|ESC:超越Transformer!即插即用ESC模块,显著提升图像超分辨率性能!
人工智能·计算机视觉·transformer
带娃的IT创业者1 天前
《AI大模型应知应会100篇》第69篇:大模型辅助的数据分析应用开发
人工智能·数据挖掘·数据分析