C# OpenCvSharp DNN 部署FastestDet

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署FastestDet

效果

模型信息

Inputs
-------------------------
name:input.1
tensor:Float[1, 3, 512, 512]
---------------------------------------------------------------

Outputs
-------------------------
name:761
tensor:Float[1024, 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 confThreshold;
        float nmsThreshold;
        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        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)
        {
            confThreshold = 0.8f;
            nmsThreshold = 0.35f;
            modelpath = "model/FastestDet.onnx";

            inpHeight = 512;
            inpWidth = 512;

            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/4.jpg";
            pictureBox1.Image = new Bitmap(image_path);

        }

        float sigmoid(float x)
        {
            return (float)(1.0 / (1 + Math.Exp(-x)));
        }

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

            dt1 = DateTime.Now;

            BN_image = CvDnn.BlobFromImage(image, 1 / 255.0, new OpenCvSharp.Size(inpWidth, inpHeight), new Scalar(0, 0, 0), false, false);

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

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

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

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

            int i = 0, j = 0, row_ind = 0; //box_score, xmin,ymin,xamx,ymax,class_score
            int num_grid_x = 32;
            int num_grid_y = 32;
            float* pdata = (float*)outs[0].Data;

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

            for (i = 0; i < num_grid_y; i++)
            {
                for (j = 0; j < num_grid_x; j++)
                {
                    Mat scores = outs[0].Row(row_ind).ColRange(5, nout);
                    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);
                    max_class_socre *= pdata[0];
                    if (max_class_socre > confThreshold)
                    {
                        int class_idx = classIdPoint.X;
                        float cx = (float)((Math.Tanh(pdata[1]) + j) / (float)num_grid_x);  //cx
                        float cy = (float)((Math.Tanh(pdata[2]) + i) / (float)num_grid_y);   //cy
                        float w = sigmoid(pdata[3]);   //w
                        float h = sigmoid(pdata[4]);  //h

                        cx *= image.Cols;
                        cy *= image.Rows;
                        w *= image.Cols;
                        h *= image.Rows;

                        int left = (int)(cx - 0.5 * w);
                        int top = (int)(cy - 0.5 * h);

                        confidences.Add((float)max_class_socre);
                        boxes.Add(new Rect(left, top, (int)w, (int)h));
                        classIds.Add(class_idx);
                    }
                    row_ind++;
                    pdata += nout;
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];
                Cv2.Rectangle(result_image, new OpenCvSharp.Point(box.X, box.Y), new OpenCvSharp.Point(box.X + box.Width, box.Y + box.Height), new Scalar(0, 0, 255), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(box.X, box.Y - 5), HersheyFonts.HersheySimplex, 0.75, new Scalar(0, 0, 255), 1);
            }

            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 confThreshold;
        float nmsThreshold;
        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        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)
        {
            confThreshold = 0.8f;
            nmsThreshold = 0.35f;
            modelpath = "model/FastestDet.onnx";

            inpHeight = 512;
            inpWidth = 512;

            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/4.jpg";
            pictureBox1.Image = new Bitmap(image_path);

        }

        float sigmoid(float x)
        {
            return (float)(1.0 / (1 + Math.Exp(-x)));
        }

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

            dt1 = DateTime.Now;

            BN_image = CvDnn.BlobFromImage(image, 1 / 255.0, new OpenCvSharp.Size(inpWidth, inpHeight), new Scalar(0, 0, 0), false, false);

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

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

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

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

            int i = 0, j = 0, row_ind = 0; //box_score, xmin,ymin,xamx,ymax,class_score
            int num_grid_x = 32;
            int num_grid_y = 32;
            float* pdata = (float*)outs[0].Data;

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

            for (i = 0; i < num_grid_y; i++)
            {
                for (j = 0; j < num_grid_x; j++)
                {
                    Mat scores = outs[0].Row(row_ind).ColRange(5, nout);
                    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);
                    max_class_socre *= pdata[0];
                    if (max_class_socre > confThreshold)
                    {
                        int class_idx = classIdPoint.X;
                        float cx = (float)((Math.Tanh(pdata[1]) + j) / (float)num_grid_x);  //cx
                        float cy = (float)((Math.Tanh(pdata[2]) + i) / (float)num_grid_y);   //cy
                        float w = sigmoid(pdata[3]);   //w
                        float h = sigmoid(pdata[4]);  //h

                        cx *= image.Cols;
                        cy *= image.Rows;
                        w *= image.Cols;
                        h *= image.Rows;

                        int left = (int)(cx - 0.5 * w);
                        int top = (int)(cy - 0.5 * h);

                        confidences.Add((float)max_class_socre);
                        boxes.Add(new Rect(left, top, (int)w, (int)h));
                        classIds.Add(class_idx);
                    }
                    row_ind++;
                    pdata += nout;
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];
                Cv2.Rectangle(result_image, new OpenCvSharp.Point(box.X, box.Y), new OpenCvSharp.Point(box.X + box.Width, box.Y + box.Height), new Scalar(0, 0, 255), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(box.X, box.Y - 5), HersheyFonts.HersheySimplex, 0.75, new Scalar(0, 0, 255), 1);
            }

            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/5255564.html

相关文章

Python-docx 深入word源码 自定义字符间距

代码和实现效果 from docx import Document from docx.oxml import OxmlElement from docx.oxml.ns import qn from docx.shared import Pt# 调整pt设置字间距 def SetParagraphCharSpaceByPt(run, pt1):通过修改word源码方式, 添加w:spacing标签直接通过调整pt来设置字符间距…

perl处理json的序列化和反序列化

perl可以使用JSON模块很方便的处理json的序列化和反序列化。先来一段简单的例子&#xff1a; #! /usr/bin/perl use v5.14; use JSON; use IO::File;my $info {id > 1024,desc > hello world,arry > [1, 2, 3, 4, 5],obj > {char > [ A, B, C ]} };say to_jso…

管理类联考——数学——真题篇——按知识分类——代数

文章目录 2023真题(2023-09)-代数-一元二次方程-注意绝对值的有效性真题(2023-17)-代数-一元二次方程-举反例真题(2023-18)-数列-等比数列真题(2023-24)-数列-等比数列2022真题(2022-03)-代数-整式-因式分解真题(2022-19)-数列-等比数列真题(2022-21)-数列-等比数…

Rust 学习

Rust 官网&#xff1a;https://www.rust-lang.org/zh-CN/ 1、Rust 简介 Rust 是一门注重安全&#xff08;safety&#xff09;、速度&#xff08;speed&#xff09;和并发&#xff08;concurrency&#xff09;的现代系统编程语言。Rust 通过内存安全来实现以上目标&#xff0c;但…

【清晰明了】Jenkins邮件发送配置

自带邮件插件 首先要知道的是jenkins是自带邮件插件的&#xff0c;且不支持卸载。 下面开始配置自带邮件插件。 配置默认邮件管理员 系统管理 --> 系统配置&#xff0c;进行如下配置&#xff1a; 不配置管理员邮件地址报错如下 jakarta.mail.internet.AddressException:…

C#随笔 | List.Sort()使用小计

1、使用List.Sort()对基本数值类型数据进行排序 案例&#xff1a;对存放int数据的List进行排序 其实C#中的List的Sort函数中的比较函数CompareTo有三种结果 1, -1 ,0分别代表大&#xff0c;小&#xff0c;相等。默认List的排序是升序排序。 举个例子&#xff1a;在比较函数Co…

做数据分析为何要学统计学(10)——如何进行时间序列分析

时间序列是由随时间变化的值构成&#xff0c;如产品销量、气温数据等等。通过对时间序列展开分析&#xff0c;能够回答如下问题&#xff1a; &#xff08;1&#xff09;被研究对象的活动特征是否有周期性&#xff08;也称季节性&#xff09;&#xff08;2&#xff09;被研究对…

服务器数据恢复—raid5少盘状态下新建raid5如何恢复原raid5数据?

服务器数据恢复环境&#xff1a; 一台服务器上搭建了一组由5块硬盘组建的raid5阵列&#xff0c;服务器上层存放单位重要数据&#xff0c;无备份文件。 服务器故障&分析&#xff1a; 服务器上raid5有一块硬盘掉线&#xff0c;外聘运维人员在没有了解服务器具体情况下&#x…