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.niftyadmin.cn/n/5311938.html

相关文章

选择服务商搭建WiFi贴码小程序,有哪些注意事项呢?

随着移动互联网的快速发展&#xff0c;共享WiFi已经成为人们生活中不可或缺的一部分。在各种公共场所&#xff0c;如咖啡厅、餐厅、酒店、商场等&#xff0c;提供免费WiFi已经成为一种趋势。而WiFi贴码小程序的出现&#xff0c;为商家和用户提供了一个便捷的连接方式。那么&…

计算机毕业设计 | SpringBoot+vue移动端音乐网站 音乐播放器(附源码)

1&#xff0c;项目背景 随着计算机技术的发展&#xff0c;网络技术对我们生活和工作显得越来越重要&#xff0c;特别是现在信息高度发达的今天&#xff0c;人们对最新信息的需求和发布迫切的需要及时性。为了满足不同人们对网络需求&#xff0c;各种特色&#xff0c;各种主题的…

计算机网络——实验七

使用socket实现一个基于C/S架构的通信程序 &#xff08;1&#xff09;客户端发送给服务器请求&#xff0c;发送表征身份的用户名和密码("admin","123456")&#xff1b; &#xff08;2&#xff09;服务器根据客户端发来的信息验证身份&#xff0c;如果验证…

[情商-9]:如何让聊天更情绪感和更有趣?

目录 前言&#xff1a; 1、只谈当下&#xff0c;不谈未来 2、避免以自我为的需求为中心&#xff0c;而是以对方的需求为中心 3. 留一点神秘感&#xff0c;说不能说得太透&#xff0c;使用模糊和多义词 4.并非一直说话的人就是会聊天&#xff0c; 5、摆脱巨婴思维&#xf…

深入了解pnpm:一种高效的包管理工具

✨专栏介绍 在当今数字化时代&#xff0c;Web应用程序已经成为了人们生活和工作中不可或缺的一部分。而要构建出令人印象深刻且功能强大的Web应用程序&#xff0c;就需要掌握一系列前端技术。前端技术涵盖了HTML、CSS和JavaScript等核心技术&#xff0c;以及各种框架、库和工具…

C#.Net学习笔记——设计模式六大原则

***************基础介绍*************** 1、单一职责原则 2、里氏替换原则 3、依赖倒置原则 4、接口隔离原则 5、迪米特法原则 6、开闭原则 一、单一职责原则 举例&#xff1a;类T负责两个不同的职责&#xff1a;职责P1&#xff0c;职责P2。当由于职责P1需求发生改变而需要修…

卡码网Java基础课 | 6. 数组的倒序与隔位输出

卡码网Java基础课|6. 数组的倒序与隔位输出 数组ArrayList增强for循环6. 数组的倒序与隔位输出 数组 Java中的数组是一种用于存储相同数据类型的元素的数据结构。 相同数据类型的元素指的是数组中的所有元素都必须是相同的数据类型&#xff1b;固定大小&#xff0c;连续存储&…

使用即时设计绘制原型设计方便吗?和Axure RP相比怎么样?

对于原型设计&#xff0c;APP 和 Web 都是一样的&#xff0c;因为产品原型是用来确定需求的工具。我们使用这种工具的目的是为了快速迭代&#xff0c;从而深入挖掘和筛选产品的需求。 绘制原型&#xff0c;最重要的原则是&#xff1a;快速、清晰&#xff01; Axure 工具的优缺…