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

下载

源码下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/205421.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux运行jmeter报错java.sql.SQLException:Cannot create PoolableConnectionFactory

在性能测试过程中遇见1个问题&#xff0c;终于解决了&#xff0c;具体问题如下。 问题 在windows电脑写jmeter脚本连接数据库连接成功 然后把该脚本放到Linux服务器上面&#xff0c;并把jmeter mysql驱动放到服务器上面&#xff0c;修改jmeter的mysql驱动路径信息 注意&…

系统试运行方案

系统试运行的目的&#xff1a; 试运行目的通过既定时间段的试运行&#xff0c;全面考察项目建设成果。并通过试运行发现项目存在的问题&#xff0c;从而进一步完善项目建设内容&#xff0c;确保项目顺利通过竣工验收并平稳地移交给运行管理单位。通过实际运行中系统功能与性能的…

感恩节的习俗 Custom of Family Dinner

感恩节是美国最普遍庆祝的传统节日之一。在每年11月的第四个星期四&#xff0c;感恩节如期而至。Thanksgiving is one of the most universally celebrated traditional American holidays. Every year, Thanksgiving arrives on the fourth Thursday of November without fail…

JOSEF 静态中间继电器 ZJY-420 DC220V 板前接线,带底座 增加触点

系列型号&#xff1a; ZJY-400中间继电器&#xff1b;ZJY-600中间继电器&#xff1b; ZJY-800中间继电器&#xff1b;ZJY-020中间继电器&#xff1b; ZJY-040中间继电器&#xff1b;ZJY-060中间继电器&#xff1b; ZJY-006中间继电器&#xff1b;ZJY-008中间继电器&#xff1b;…

全国市政公用事业和邮政、电信业发展数据,shp/excel格式

随着城市化进程的加速和人们对城市生活品质要求的提高&#xff0c;市政公用事业和邮政、电信业发展越来越受到关注。 今天我们来分享全国市政公用事业和邮政、电信业发展数据&#xff0c;为读者呈现一个更加全面的行业发展图景。 首先了解下数据的基本信息&#xff0c;格式为s…

虚函数可不可以重载为内联 —— 在开启最大优化时gcc、clang和msvc的表现

下面是对该问题的一种常见回答&#xff1a; 首先&#xff0c;内联是程序员对编译器的一种建议&#xff0c;因此可以在在重载虚函数时在声明处加上inline关键字来修饰&#xff0c; 但是因为虚函数在运行时通过虚函数表&#xff0c;而内联函数在编译时进行代码嵌入&#xff0c;因…

NOIP2015提高组第二轮T1:能量项链

题目链接 [NOIP2006 提高组] 能量项链 题目描述 在 Mars 星球上&#xff0c;每个 Mars 人都随身佩带着一串能量项链。在项链上有 N N N 颗能量珠。能量珠是一颗有头标记与尾标记的珠子&#xff0c;这些标记对应着某个正整数。并且&#xff0c;对于相邻的两颗珠子&#xff0…

悄悄上线:CSS @starting-style 新规则

最近 Chrome 117&#xff0c;CSS 又悄悄推出了一个新的的规则&#xff0c;叫做starting-style。从名称上来看&#xff0c;表示定义初始样式。那么&#xff0c;具体是做什么的&#xff1f;有什么用&#xff1f;一起了解一下吧 一、快速了解 starting-style 通常做一个动画效果…

OpenLayers入门,OpenLayers6的WebGLPointsLayer图层样式和运算符详解,四种symbolType类型案例

专栏目录: OpenLayers入门教程汇总目录 前言 本章讲解使用OpenLayers6的WebGL图层显示大量点情况下,列举出所有WebGLPointsLayer图层所支持的所有样式运算符大全。 补充说明 本篇主要介绍OpenLayers6.x版本的webgl图层,OpenLayers7.x和OpenLayers8.x主要更新内容就是webgl…

NEJM一篇新文为例,聊聊孟德尔随机化研究mr

2019年3月14日&#xff0c;新英格兰医学杂志发表了一篇论著&#xff0c;Mendelian Randomization Study of ACLY and Cardiovascular disease, 即《ACLY和心血管疾病的孟德尔随机化研究》。与小咖在2017年1月9日报道的一篇发表在新英格兰医学的孟德尔随机化研究——精读NEJM&am…

英国国家量子计算中心与IBM签署重要协议!英国进入实用量子时代

​&#xff08;图片来源&#xff1a;网络&#xff09; 近日&#xff0c;英国国家量子计算中心&#xff08;NQCC&#xff09;与IBM达成了一项重要协议。根据该协议&#xff0c;NQCC将为英国研究人员提供IBM量子高级计划的云访问权限&#xff0c;其中包括IBM的量子计算系统舰队。…

溅射沉积镍薄膜的微观结构和应力演化

引言 众所周知&#xff0c;材料的宏观性质&#xff0c;例如硬度、热和电传输以及光学描述符与其微观结构特征相关联。通过改变加工参数&#xff0c;可以改变微结构&#xff0c;从而能够控制这些性质。在薄膜沉积的情况下&#xff0c;微结构特征&#xff0c;例如颗粒尺寸和它们…