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

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

相关文章

大数据技术10:Flink从入门到精通

导语&#xff1a;前期入门Flink时&#xff0c;可以直接编写通过idea编写Flink程序&#xff0c;然后直接运行main方法&#xff0c;无需搭建环境。我碰到许多初次接触Flink的同学&#xff0c;被各种环境搭建、提交作业、复杂概念给劝退了。前期最好的入门方式就是直接上手写代码&…

Java SPI机制学习

最近阅读源码时看到了SPI加载类的方式 这里学习一下 SPI Service Provider Interface 服务提供接口 API和SPI区别 API是接口和实现类均有服务提供方负责 服务调用方更多是一种主动调用 只是调用SDK来实现某个功能&#xff1b;接口的归属权在于服务提供方 SPI是接口在调用方…

N体问题-MATLAB 中的数值模拟

一、说明 万有引力是宇宙普适真理&#xff0c;当计算两个物体的引力、质量、距离的关系是经典万有引力物理定律&#xff0c;然而面向复杂问题&#xff0c;比如出现三个以上物体的相互作用&#xff0c;随时间的运动力学&#xff0c;这种数学模型将是更高级的思维方法。本文将阐述…

jsp文件引用的css修改后刷新不生效问题

问题 在对 JavaWeb 项目修改的过程中&#xff0c;发现修改了 jsp 文件引入的 css 文件的代码后页面的样式没有更新的问题。 原因 导致这个问题的原因可能是因为浏览器缓存的问题。 解决方法 下面介绍两种解决方法&#xff0c;供大家参考&#xff1a; 1、给 link 标签的 c…

软件测试(接口测试业务场景测试)

软件测试 手动测试 测试用例8大要素 编号用例名称&#xff08;标题&#xff09;模块优先级预制条件测试数据操作步骤预期结果 接口测试&#xff08;模拟http请求&#xff09; 接口用例设计 防止漏测方便分配工具&#xff0c;评估工作量和时间接口测试测试点 功能 单接口业…

css的Grid布局

1.简单布局 .grid { display: grid; grid-template-columns: 1fr 2fr 1fr; 布局样式 column-gap: 24px; 列间距 row-gap: 24px; 行间距 } 2.排列布局 center垂直方向居中对其 end靠下对齐 3.水平方向对齐 center居中 end靠右对齐 space-between两段对齐 4.对…

使用BeautifulSoup 4和Pillow合并网页图片到一个PDF:一种高效的方式来处理网页图像

背景 ​ 网页上的培训材料&#xff0c;内容全是PPT页面图片。直接通过浏览器打印&#xff0c;会存在只打印第一页&#xff0c;并且把浏览器上无效信息也打印出来情况。但目标是希望将页面图片全部打印为pdf形式。 实现方案 利用网页“另存为”&#xff0c;将页面内所有图片资…

Windows安全基础——Windows WMI详解

Windows安全基础——WMI篇 1. WMI简介 WMI&#xff08;Windows Management Instrumentation, Windows管理规范&#xff09;是Windows 2000/XP管理系统的核心&#xff0c;属于管理数据和操作的基础模块。设计WMI的初衷是达到一种通用性&#xff0c;通过WMI操作系统、应用程序等…

构建智能外卖跑腿小程序:技术实践与代码示例

在快节奏的现代生活中&#xff0c;外卖跑腿服务已成为人们日常生活中不可或缺的一部分。为了提供更智能、高效的外卖跑腿体验&#xff0c;本文将深入探讨构建一款智能外卖跑腿小程序所需的关键技术&#xff0c;并提供相应的代码示例。 1. 地理位置服务的整合 外卖跑腿小程序…

nodejs微信小程序+python+PHP个性化服装搭配系统APP-计算机毕业设计推荐 android

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性&#xff1a;…

Ubuntu22.04安装和卸载软件的命令行

一、安装 sudo apt install xxx 二、卸载 sudo apt remove xxx 三、卸载依赖包(可选) 第二步软件卸载之后&#xff0c;有一些依赖包没有被卸载。可以使用sudo apt autoremove xxx来卸载。如果不卸载应该也没什么影响

【开源】基于Vue和SpringBoot的高校学院网站

项目编号&#xff1a; S 020 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S020&#xff0c;文末获取源码。} 项目编号&#xff1a;S020&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 学院院系模块2.2 竞赛报名模块2.3 教…

Python爬取酷我音乐

&#x1f388; 博主&#xff1a;一只程序猿子 &#x1f388; 博客主页&#xff1a;一只程序猿子 博客主页 &#x1f388; 个人介绍&#xff1a;爱好(bushi)编程&#xff01; &#x1f388; 创作不易&#xff1a;喜欢的话麻烦您点个&#x1f44d;和⭐&#xff01; &#x1f388;…

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来设置字符间距…

【Maven教程】(十二):版本管理 ——版本号定义约定及相关概念,自动化版本发布与创建分支,GPG签名 ~

Maven 版本管理 1️⃣ 版本管理的概念2️⃣ Maven 的版本号定义约定3️⃣ 主干、标签与分支4️⃣ 自动化版本发布5️⃣ 自动化创建分支6️⃣ GPG签名6.1 GPG 及其基本使用6.2 Maven GPG Plugin &#x1f33e; 总结 一个健康的项目通常有一个长期、合理的版本演变过程。例如JUn…

Nginx访问FTP服务器文件的时效性/安全校验

背景 FTP文件服务器在我们日常开发中经常使用&#xff0c;在项目中我们经常把FTP文件下载到内存中&#xff0c;然后转为base64给前端进行展示。如果excel中也需要导出图片&#xff0c;数据量大的情况下会直接返回一个后端的开放接口地址&#xff0c;然后在项目中对接口的参数进…

Golang 使用 Template 引擎构建漂亮的邮件内容并且完成邮件发送

背景 邮件是常见的触达用户的途径&#xff0c;本文详细介绍基于 golang 的模版引擎构建漂亮的邮件内容&#xff0c;并且发送给模板用户。 思路 go 内置了 html/template 模块&#xff0c;类似 ejs 模块引擎。利用 template 能力可以将变量动态的注入到HTML字符串中&#xff…

迅为RK3568开发板使用OpenCV处理图像(颜色转换)

1 颜色转换 本小节代码在配套资料“iTOP-3568 开发板\03_【iTOP-RK3568 开发板】指南教程 \04_OpenCV 开发配套资料\05”目录下&#xff0c;如下图所示&#xff1a; cv2.cvtColor()函数功能&#xff1a; 将一幅图像从一个色彩空间转换到另一个色彩空间。 函数原型&#xff…

5G CPE可代替宽带,解决断网问题

最近某运营商就玩起了套餐&#xff0c;断用户的网。 老百姓对宽带半知不解&#xff0c;网络断了没法上网&#xff0c;很着急。因为相信运营商&#xff0c;维修人员怎么说&#xff0c;老百姓就怎么办呗&#xff0c;直到最后才发现自己上当&#xff0c;但钱都给了。 截至2023年9月…

Django讲课笔记02:Django环境搭建

文章目录 一、学习目标二、相关概念&#xff08;一&#xff09;Python&#xff08;二&#xff09;Django 三、环境搭建&#xff08;一&#xff09;安装Python1. 从官方网站下载最新版本的Python2. 运行安装程序并按照安装向导进行操作3. 勾选添加到路径复选框4. 完成安装过程5.…
最新文章