C# OpenCvSharp DNN 部署YOLOV6目标检测

news2024/9/20 4:40:13

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署YOLOV6目标检测

效果

模型信息

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

Outputs
-------------------------
name:outputs
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 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.3f;
            nmsThreshold = 0.5f;
            modelpath = "model/yolov6s.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/image3.jpg";
            pictureBox1.Image = new Bitmap(image_path);

        }

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

        Mat ResizeImage(Mat srcimg, out int newh, out int neww, out int top, out int left)
        {
            int srch = srcimg.Rows, srcw = srcimg.Cols;
            top = 0;
            left = 0;
            newh = inpHeight;
            neww = inpWidth;
            Mat dstimg = new Mat();
            if (srch != srcw)
            {
                float hw_scale = (float)srch / srcw;
                if (hw_scale > 1)
                {
                    newh = inpHeight;
                    neww = (int)(inpWidth / hw_scale);
                    Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
                    left = (int)((inpWidth - neww) * 0.5);
                    Cv2.CopyMakeBorder(dstimg, dstimg, 0, 0, left, inpWidth - neww - left, BorderTypes.Constant);
                }
                else
                {
                    newh = (int)(inpHeight * hw_scale);
                    neww = inpWidth;
                    Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
                    top = (int)((inpHeight - newh) * 0.5);
                    Cv2.CopyMakeBorder(dstimg, dstimg, top, inpHeight - newh - top, 0, 0, BorderTypes.Constant);
                }
            }
            else
            {
                Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh));
            }
            return dstimg;
        }

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

            int newh = 0, neww = 0, padh = 0, padw = 0;
            Mat dstimg = ResizeImage(image, out newh, out neww, out padh, out padw);

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

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

            //模型推理,读取推理结果
            Mat[] outs = new Mat[3] { new Mat(), 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(0);
            int nout = outs[0].Size(1);

            if (outs[0].Dims > 2)
            {
                num_proposal = outs[0].Size(1);
                nout = outs[0].Size(2);
                outs[0] = outs[0].Reshape(0, num_proposal);
            }

            float ratioh = 1.0f * image.Rows / newh, ratiow = 1.0f * image.Cols / neww;
            int n = 0, row_ind = 0; ///cx,cy,w,h,box_score,class_score
            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 (n = 0; n < num_proposal; n++)
            {
                float box_score = pdata[4];

                if (box_score > confThreshold)
                {
                    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 *= box_score;

                    int class_idx = classIdPoint.X;

                    float cx = (pdata[0] - padw) * ratiow;  //cx
                    float cy = (pdata[1] - padh) * ratioh;   //cy
                    float w = pdata[2] * ratiow;   //w
                    float h = pdata[3] * ratioh;  //h

                    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.3f;
            nmsThreshold = 0.5f;
            modelpath = "model/yolov6s.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/image3.jpg";
            pictureBox1.Image = new Bitmap(image_path);

        }

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

        Mat ResizeImage(Mat srcimg, out int newh, out int neww, out int top, out int left)
        {
            int srch = srcimg.Rows, srcw = srcimg.Cols;
            top = 0;
            left = 0;
            newh = inpHeight;
            neww = inpWidth;
            Mat dstimg = new Mat();
            if (srch != srcw)
            {
                float hw_scale = (float)srch / srcw;
                if (hw_scale > 1)
                {
                    newh = inpHeight;
                    neww = (int)(inpWidth / hw_scale);
                    Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
                    left = (int)((inpWidth - neww) * 0.5);
                    Cv2.CopyMakeBorder(dstimg, dstimg, 0, 0, left, inpWidth - neww - left, BorderTypes.Constant);
                }
                else
                {
                    newh = (int)(inpHeight * hw_scale);
                    neww = inpWidth;
                    Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
                    top = (int)((inpHeight - newh) * 0.5);
                    Cv2.CopyMakeBorder(dstimg, dstimg, top, inpHeight - newh - top, 0, 0, BorderTypes.Constant);
                }
            }
            else
            {
                Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh));
            }
            return dstimg;
        }

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

            int newh = 0, neww = 0, padh = 0, padw = 0;
            Mat dstimg = ResizeImage(image, out newh, out neww, out padh, out padw);

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

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

            //模型推理,读取推理结果
            Mat[] outs = new Mat[3] { new Mat(), 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(0);
            int nout = outs[0].Size(1);

            if (outs[0].Dims > 2)
            {
                num_proposal = outs[0].Size(1);
                nout = outs[0].Size(2);
                outs[0] = outs[0].Reshape(0, num_proposal);
            }

            float ratioh = 1.0f * image.Rows / newh, ratiow = 1.0f * image.Cols / neww;
            int n = 0, row_ind = 0; ///cx,cy,w,h,box_score,class_score
            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 (n = 0; n < num_proposal; n++)
            {
                float box_score = pdata[4];

                if (box_score > confThreshold)
                {
                    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 *= box_score;

                    int class_idx = classIdPoint.X;

                    float cx = (pdata[0] - padw) * ratiow;  //cx
                    float cy = (pdata[1] - padh) * ratioh;   //cy
                    float w = pdata[2] * ratiow;   //w
                    float h = pdata[3] * ratioh;  //h

                    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.coloradmin.cn/o/1312128.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

搭建个人智能家居 开篇(搭建Home Assistant)

搭建个人智能家居 开篇&#xff08;搭建Home Assistant&#xff09; 前言Home Assistant搭建Home AssistantUbuntu系统搭建Windows系统搭建VM安装方法VirtualBox安装方法&#xff1a; 配置Home Assistant控制页面 前言 随着科技的进步、发展&#xff0c;物联网给我们的生活带来…

Axure的安装及界面基本功能介绍

目录 一. Axure概述 二. Axure安装 2.1 安装包下载 2.2 安装步骤 三. Axure功能介绍​ 3.1 工具栏介绍 3.1.1 复制&#xff0c;剪切及粘贴 3.1.2 选择模式和连接 3.1.3 插入形状 3.1.4 点&#xff08;编辑控点&#xff09; 3.1.5 置顶和置底 3.1.6 组合和取消组合 …

双向无线功率传输系统MATLAB仿真

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; 模型简介&#xff1a; 初级侧转换器通过双向 AC/DC 转换器从电网获取电力&#xff0c;并由直流线电压 Vin 供电&#xff0c;而拾波侧被视为连接到 EV&#xff0c;并由连接到任一存储的单独直流源 Vout 表示或…

express 下搞一个 websocket 长连接

安装模块 npm i express npm i express-ws 新建文件app.js 先安排源码 监听端口 7777 var express require(express) var app express() require(express-ws)(app)var port 7777 var clientObject {} app.ws(/, (client, req) > {// 连接var key req.socket.re…

TypeScript【枚举、联合类型函数_基础、函数_参数说明 、类的概念、类的创建】(二)-全面详解(学习总结---从入门到深化)

文章目录 枚举 联合类型 函数_基础 函数_参数说明 类的概念 类的创建 枚举 枚举&#xff08;Enum&#xff09;类型用于取值被限定在一定范围内的场景&#xff0c;比如一周只能有七天&#xff0c;颜色限定为红绿蓝等 枚举例子 枚举使用 enum 关键字来定义 enum Days {…

locust 压测 websocket

* 安装 python 3.8 https://www.python.org/ py --version * 安装 locust pip install locust2.5.1 -i http://pypi.douban.com/simple/ pip install locust2.5.1 -i https://pypi.mirrors.ustc.edu.cn/simple/ locust -V 备注&#xff1a;-i 是切换下载源 * 安装依赖 pip ins…

一篇文章讲透TCP/IP协议

1 OSI 7层参考模型 2 实操连接百度 nc连接百度2次&#xff0c;使用命令netstat -natp查看就会重新连接一次百度 请求百度 3 三次握手、socket 应用层协议控制长连接和短连接 应用层协议->传输控制层&#xff08;TCP UDP&#xff09;->TCP&#xff08; 面向连接&am…

超声波清洗机应该怎样使用?清洁能力强超声波清洗机推荐

其实超声波清洗机使用方法非常简单&#xff0c;只需要将清洁物品放进超声波清洗机内&#xff0c;加入水打开开关即可开始使用&#xff0c;不需要太复杂操作就可以开启清洗&#xff0c;等待个数分钟就可以得到一个干干净净的物品被清洗完毕&#xff01;可见现在科技进步&#xf…

在Node.js中MongoDB更新数据的方法

本文主要介绍在Node.js中MongoDB更新数据的方法。 目录 Node.js中MongoDB更新数据使用原生 MongoDB 驱动程序更新数据使用 Mongoose 更新数据 Node.js中MongoDB更新数据 在Node.js中&#xff0c;可以使用原生的 MongoDB 驱动程序或者使用 Mongoose 来更新 MongoDB 数据。 下面…

Redis设计与实现之字典

目录 一、字典 1、 字典的应用 实现数据库键空间 用作Hash类型键的其中一种底层实现 2、字典的实现 哈希表实现 哈希算法 3、创建新字典 4、添加键值对到字典 5、添加新元素到空白字典 6、添加新键值对时发生碰撞处理 7、添加新键值对时触发了 rehash操作 Note:什么…

SpringIOC之FilterType

博主介绍&#xff1a;✌全网粉丝5W&#xff0c;全栈开发工程师&#xff0c;从事多年软件开发&#xff0c;在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战&#xff0c;博主也曾写过优秀论文&#xff0c;查重率极低&#xff0c;在这方面有丰富的经验…

MySQL事务与MVCC详解

前置概念之事务 在开始MVCC的讨论之前&#xff0c;我们必须了解一些关于事务的概念。 什么是事务 现在我们开发的一个功能需要进行操作多张表&#xff0c;假如我们遇到以下几种情况: 某个逻辑报错数据库连接中断某台服务器突然宕机… 这时候我们数据库执行的操作可能才到一…

从零开始搭建企业管理系统(七):RBAC 之用户管理

RBAC 之用户管理 创建表&#xff08;Entity&#xff09;用户表角色表权限表用户角色表关系注解ManyToMany 角色权限表 接口开发UserControllerUserServiceUserServiceImplUserRepository 问题解决update 更新问题懒加载问题JSON 循环依赖问题 根据上一小结对表的设计&#xff0…

2020年AMC8数学竞赛真题的典型考点和详细解析

从战争中学习战争。 对于2024年1月19日的AMC8竞赛&#xff0c;如何备考和冲刺取得更好的成绩&#xff1f;六分成长建议通过反复刷真题&#xff0c;来掌握AMC8的出题方式、考点和解题思路&#xff0c;并且对自己前期的学习查漏补缺&#xff0c;这是最快的方式。 如何提高刷真题…

5G边缘网关如何助力打造隧道巡检机器人

我国已建成全世界里程最长的公路网、铁路网&#xff0c;是国民经济发展与国家现代化的重要支撑。我国幅员辽阔&#xff0c;地理环境复杂&#xff0c;公路/铁路的延伸也伴随着许多隧道的建设&#xff0c;由于隧道所穿越山体的地质条件复杂&#xff0c;对于隧道的监测、管理与养护…

HarmonyOS保存应用数据

数据管理 1 概述 在移动互联网蓬勃发展的今天&#xff0c;移动应用给我们生活带来了极大的便利&#xff0c;这些便利的本质在于数据的互联互通。因此在应用的开发中数据存储占据了非常重要的位置&#xff0c;HarmonyOS应用开发也不例外。 本文将为您介绍HarmonyOS提供的数据管…

Excel公式逆天了--使用公式修改其他单元格格式

想必连VBA小白都知道&#xff0c;VBA编程中有两种过程&#xff1a;Sub和Function&#xff08;有时称为UDF&#xff0c;User Defined Function&#xff09;&#xff0c;二者最明显的区别在于Function可以提供返回值&#xff0c;并且在Excel公式可以调用Function。 多数VBA图书都…

言简意赅的 el-table 跨页多选

步骤一 在<el-table>中:row-key"getRowKeys"和selection-change"handleSelectionChange" 在<el-table-column>中type"selection"那列&#xff0c;添加:reserve-selection"true" <el-table:data"tableData"r…

Linux Shell——(函数)

shell函数 1. 函数定义2. 调用函数 总结 最近学习了shell脚本&#xff0c;记录一下shell函数相关语法 1. 函数定义 语法&#xff1a; [funciton] functionname [()] { 语句 [return] } 函数使用前必须先定义funciton关键字是可选的return关键字也是可选的&#xff0c;如果没有…

ChatGPT如何做科研??

2023年我们进入了AI2.0时代。微软创始人比尔盖茨称ChatGPT的出现有着重大历史意义&#xff0c;不亚于互联网和个人电脑的问世。360创始人周鸿祎认为未来各行各业如果不能搭上这班车&#xff0c;就有可能被淘汰在这个数字化时代&#xff0c;如何能高效地处理文本、文献查阅、PPT…