C# OpenCvSharp DNN 部署yoloX

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署yoloX

效果

模型信息

Inputs
-------------------------
name:images
tensor:Float[1, 3, 640, 640]
---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:Float[1, 8400, 85]
---------------------------------------------------------------

项目

代码

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace OpenCvSharp_DNN_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 prob_threshold;
        float nms_threshold;

        float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };

        int[] input_shape = new int[] { 640, 640 };   // height, width

        float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
        float scale = 1.0f;

        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        public Mat Normalize(Mat src)
        {
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return src;
        }

        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 Bitmap(image_path);
            image = new Mat(image_path);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            prob_threshold = 0.6f;
            nms_threshold = 0.6f;

            modelpath = "model/yolox_s.onnx";

            inpHeight = 640;
            inpWidth = 640;

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            class_names = new List<string>();
            StreamReader sr = new StreamReader("model/coco.names");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                class_names.Add(line);
            }
            num_class = class_names.Count();

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

        }

        Mat ResizeImage(Mat srcimg)
        {

            float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
            scale = r;
            int unpad_w = (int)(r * srcimg.Cols);
            int unpad_h = (int)(r * srcimg.Rows);
            Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
            Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
            Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
            re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
            return outMat;
        }


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

            image = new Mat(image_path);

            Mat dstimg = ResizeImage(image);

            dstimg = Normalize(dstimg);

            BN_image = CvDnn.BlobFromImage(dstimg);

            //配置图片输入数据
            opencv_net.SetInput(BN_image);

            //模型推理,读取推理结果
            Mat[] outs = new Mat[] { new Mat() };
            string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();

            dt1 = DateTime.Now;

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

            int num_proposal = outs[0].Size(1);
            outs[0] = outs[0].Reshape(0, num_proposal);

            float* pdata = (float*)outs[0].Data;

            int row_ind = 0;
            int nout = num_class + 5;

            List<Rect> boxes = new List<Rect>();
            List<float> confidences = new List<float>();
            List<int> classIds = new List<int>();

            for (int n = 0; n < 3; n++)
            {
                int num_grid_x = (int)(inpWidth / stride[n]);
                int num_grid_y = (int)(inpHeight / stride[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].Cols);

                        double minVal, max_class_socre;
                        OpenCvSharp.Point minLoc, classIdPoint;
                        // Get the value and location of the maximum score
                        Cv2.MinMaxLoc(scores, out minVal, out max_class_socre, out minLoc, out classIdPoint);

                        int class_idx = classIdPoint.X;

                        float cls_score = pdata[5 + class_idx];
                        float box_prob = box_score * cls_score;
                        if (box_prob > prob_threshold)
                        {
                            float x_center = (pdata[0] + j) * stride[n];
                            float y_center = (pdata[1] + i) * stride[n];
                            float w = (float)(Math.Exp(pdata[2]) * stride[n]);
                            float h = (float)(Math.Exp(pdata[3]) * stride[n]);
                            float x0 = x_center - w * 0.5f;
                            float y0 = y_center - h * 0.5f;

                            classIds.Add(class_idx);
                            confidences.Add(box_prob);
                            boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
                        }

                        pdata += nout;
                        row_ind++;
                    }
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];

                // adjust offset to original unpadded
                float x0 = box.X / scale; ;
                float y0 = box.Y / scale; ;
                float x1 = (box.X + box.Width) / scale;
                float y1 = (box.Y + box.Height) / scale;

                // clip
                x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
                y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
                x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
                y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
            }

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

        }

        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 OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace OpenCvSharp_DNN_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 prob_threshold;
        float nms_threshold;

        float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };

        int[] input_shape = new int[] { 640, 640 };   // height, width

        float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
        float scale = 1.0f;

        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        public Mat Normalize(Mat src)
        {
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return src;
        }

        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 Bitmap(image_path);
            image = new Mat(image_path);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            prob_threshold = 0.6f;
            nms_threshold = 0.6f;

            modelpath = "model/yolox_s.onnx";

            inpHeight = 640;
            inpWidth = 640;

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            class_names = new List<string>();
            StreamReader sr = new StreamReader("model/coco.names");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                class_names.Add(line);
            }
            num_class = class_names.Count();

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

        }

        Mat ResizeImage(Mat srcimg)
        {

            float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
            scale = r;
            int unpad_w = (int)(r * srcimg.Cols);
            int unpad_h = (int)(r * srcimg.Rows);
            Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
            Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
            Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
            re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
            return outMat;
        }


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

            image = new Mat(image_path);

            Mat dstimg = ResizeImage(image);

            dstimg = Normalize(dstimg);

            BN_image = CvDnn.BlobFromImage(dstimg);

            //配置图片输入数据
            opencv_net.SetInput(BN_image);

            //模型推理,读取推理结果
            Mat[] outs = new Mat[] { new Mat() };
            string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();

            dt1 = DateTime.Now;

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

            int num_proposal = outs[0].Size(1);
            outs[0] = outs[0].Reshape(0, num_proposal);

            float* pdata = (float*)outs[0].Data;

            int row_ind = 0;
            int nout = num_class + 5;

            List<Rect> boxes = new List<Rect>();
            List<float> confidences = new List<float>();
            List<int> classIds = new List<int>();

            for (int n = 0; n < 3; n++)
            {
                int num_grid_x = (int)(inpWidth / stride[n]);
                int num_grid_y = (int)(inpHeight / stride[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].Cols);

                        double minVal, max_class_socre;
                        OpenCvSharp.Point minLoc, classIdPoint;
                        // Get the value and location of the maximum score
                        Cv2.MinMaxLoc(scores, out minVal, out max_class_socre, out minLoc, out classIdPoint);

                        int class_idx = classIdPoint.X;

                        float cls_score = pdata[5 + class_idx];
                        float box_prob = box_score * cls_score;
                        if (box_prob > prob_threshold)
                        {
                            float x_center = (pdata[0] + j) * stride[n];
                            float y_center = (pdata[1] + i) * stride[n];
                            float w = (float)(Math.Exp(pdata[2]) * stride[n]);
                            float h = (float)(Math.Exp(pdata[3]) * stride[n]);
                            float x0 = x_center - w * 0.5f;
                            float y0 = y_center - h * 0.5f;

                            classIds.Add(class_idx);
                            confidences.Add(box_prob);
                            boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
                        }

                        pdata += nout;
                        row_ind++;
                    }
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];

                // adjust offset to original unpadded
                float x0 = box.X / scale; ;
                float y0 = box.Y / scale; ;
                float x1 = (box.X + box.Width) / scale;
                float y1 = (box.Y + box.Height) / scale;

                // clip
                x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
                y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
                x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
                y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
            }

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

        }

        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.mfbz.cn/a/302101.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Showroom Environment gallery

展示厅环境-画廊 PBR包中的所有纹理。它们适用于URP和内建。在标准状态下,所有内容都是在URP下配置的。如果你有整个场景“粉红色”,请更改渲染设置。 简单的画廊内部,配有用于照片和图片的画布。非常适合您的虚拟画廊或展厅。此套餐包含一个展厅,您可以在其中展示您的作品…

python总结-生成器与迭代器

生成器与迭代器 生成器生成器定义为什么要有生成器创建生成器的方式一(生成器表达式) 创建生成器的方式二(生成器函数)生成器函数的工作原理总结 迭代器概念可迭代对象和迭代器区别for循环的本质创建一个迭代器 动态添加属性和方法运行过程中给对象、类添加属性和方法types.Met…

我想从Spring Cloud Alibaba开始聊聊架构的本质?

另外我的新书RocketMQ消息中间件实战派上下册&#xff0c;在京东已经上架啦&#xff0c;目前都是5折&#xff0c;非常的实惠。 https://item.jd.com/14337086.html​编辑https://item.jd.com/14337086.html “RocketMQ消息中间件实战派上下册”是我既“Spring Cloud Alibaba微…

【Helm 及 Chart 快速入门】01、Helm 基本概念及仓库管理

目录 一、为何需要 Helm 二、什么是 Helm 三、Helm 核⼼概念 四、Helm 架构 五、Helm 安装 六、Helm 仓库管理 6.1 查看仓库 6.2 添加仓库 6.3 更新仓库 6.4 删除仓库 一、为何需要 Helm 在早期的 Linux 系统中&#xff0c;维护和安装软件包是⼀件极其麻烦的…

【赠书第16期】码上行动:用ChatGPT学会Python编程

文章目录 前言 1 ChatGPT简介 2 Python编程简介 3 使用ChatGPT学习Python编程 4 如何使用ChatGPT学习Python编程 5 推荐图书 6 粉丝福利 前言 随着人工智能技术的不断发展&#xff0c;聊天机器人已经成为我们日常生活和工作中不可或缺的一部分。其中&#xff0c;ChatGP…

Android系统的启动流程

Android系统启动流程大致可以概括为以下的几个步骤&#xff1a; 电源启动BootLoader启动Linux内核启动init进程启动Zygote进程启动SystemServer进程启动Launcher启动 关键的进程及其作用&#xff1a; init进程 init进程是Android系统中用户空间的第一个进程&#xff0c;进程号…

leetcode 每日一题 2023年12月28日 收集巧克力

题目 2735. 收集巧克力 给你一个长度为 n、下标从 0 开始的整数数组 nums&#xff0c;nums[i] 表示收集位于下标 i 处的巧克力成本。每个巧克力都对应一个不同的类型&#xff0c;最初&#xff0c;位于下标 i 的巧克力就对应第 i 个类型。 在一步操作中&#xff0c;你可以用成…

每个程序员都该学习的5种开发语言

我曾在某处读到过&#xff08;可能在《代码大全》&#xff0c;但我不敢确定&#xff09;&#xff0c;程序员应该每年学习一门新的编程语言。但如果做不到&#xff0c;我建议&#xff0c;你至少学习以下5种开发语言&#xff0c;以便你在职业生涯有很好的表现。 每个公司都喜爱精…

【数据结构】数据结构中应用题大全(完结)

自己在学习过程中总结了DS中几乎所有的应用题&#xff0c;可以用于速通期末考/考研/各种考试。很多方法来源于B站大佬&#xff0c;底层原理本文不做过多介绍&#xff0c;建议自己研究。例题大部分选自紫皮严书。pdf版在主页资源 一、递归时间/空间分析 1.时间复杂度的分析 设…

润和软件HopeStage与永中Office完成产品兼容性互认证

近日&#xff0c;江苏润和软件股份有限公司&#xff08;以下简称“润和软件”&#xff09;HopeStage 操作系统与永中软件股份有限公司&#xff08;以下简称“永中软件”&#xff09;永中Office办公软件完成产品兼容性测试。 测试结果表明&#xff1a;企业级通用操作系统HopeSta…

2023量子科技十大人物(团队) | 光子盒年度系列

今年&#xff0c;是量子科学与技术的又一个丰收年&#xff0c;学术研究团体和科技公司纷纷庆祝在量子计算、量子通信和量子计量学以及基础量子科学方面取得的重大成就。面对如此多令人兴奋的进展&#xff0c;我们不能不为这些进展庆祝——而所有这些的一切&#xff0c;都离不开…

如何编写高效的正则表达式?

正则表达式&#xff08;Regular Expression&#xff0c;简称regex&#xff09;是一种强大的文本处理技术&#xff0c;广泛应用于各种编程语言和工具中。本文将从多个方面介绍正则表达式的原理、应用和实践&#xff0c;帮助你掌握这一关键技术。 正则可视化 | 一个覆盖广泛主题…

为什么网络安全从业者都考CISP-PTE

网络an全从业者考取CISP-PTE证书的原因&#x1f447; 1️⃣高度认可 &#x1f48e;CISP-PTE证书是中国信息an全测评中心认证颁发&#xff0c;是国家对信息an全人员资质的zui高认可&#xff0c;具有很高的含金量。 对于网络an全从业者来说&#xff0c;可以证明自己具备规划测试方…

【python、pytorch】

什么是Pytorch Pytorch是一个基于Numpy的科学计算包&#xff0c;向它的使用者提供了两大功能。作为Numpy的替代者&#xff0c;向用户提供使用GPU强大功能的能力。做为一款深度学习的平台&#xff0c;向用户提供最大的灵活性和速度。 基本元素操作 Tenors张量&#xff1a;张量…

企业如何选择可靠的文件传输软件?曝光6招内行方法

随着企业内部对于文件传输需求的增加&#xff0c;原先传统的传输方式逐渐不再适合传输要求&#xff0c;无论是内部协作还是外部合作&#xff0c;企业都需要高效、安全、稳定的文件传输软件来支持业务的顺利进行。 然而&#xff0c;市面上的文件传输软件众多&#xff0c;不同的软…

redis数据结构源码分析——string

前面的文章大体讲解了redis的几种数据类型&#xff0c;针对设计表巧妙的数据类型&#xff0c;后续会出几篇文章单独讲解下&#xff0c;那么本篇文章针对string的源码进行讲解。 文章目录 字符串的三种编码sds结构sds的设计思想和优势sds API解析sdsnewlen&#xff08;创建字符…

Linux源码解读

Linux内核源码是一个开源的操作系统内核&#xff0c;由著名的开发者林纳斯托瓦兹(Linus Torvalds)于1991年在芬兰赫尔辛基大学发布。Linux内核的源代码由一系列的C语言程序文件组成&#xff0c;这些文件包含了操作系统内核所需的所有功能&#xff0c;包括内存管理、进程调度、文…

嘴尚绝:卤味市场未来发展潜力无限,谁将成为下一个风口?

随着人们生活水平的提高&#xff0c;卤味作为一种美味的小吃&#xff0c;越来越受到消费者的喜爱。在餐饮市场上&#xff0c;卤味市场也呈现出越来越繁荣的景象。那么&#xff0c;卤味市场未来发展如何呢&#xff1f;今天&#xff0c;我们就来探讨一下这个问题。 一、消费升级推…

【漏洞复现】Hikvision SPON IP网络对讲广播系统存在命令执行漏洞CVE-2023-6895

漏洞描述 Hikvision Intercom Broadcasting System是中国海康威视(Hikvision)公司的一个对讲广播系统。 Hikvision Intercom Broadcasting System是中国海康威视(Hikvision)公司的一个对讲广播系统。Hikvision Intercom Broadcasting System 3.0.3_20201113_RELEASE(HIK)版…

【Vue3】2-3 : 选项式API的编程风格与优势

本书目录&#xff1a;点击进入 一、选项式API - 三大优势 ▶ 只有一个参数&#xff0c;不会出现参数顺序的问题&#xff0c;随意调整配置的位置 传入的是一个对象&#xff0c;没有参数顺序问题 对比反面教材&#xff1a; ▶ 非常清晰&#xff0c;语法化特别强 ▶ 非常…
最新文章