C# OpenCvSharp DNN 部署YOLOV6目标检测

目录

效果

模型信息

项目

代码

下载


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

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

相关文章

[c++]—vector类___基础版(带你了解vector熟练掌握运用)

&#x1f469;&#x1f3fb;‍&#x1f4bb;作者:chlorine 目录 &#x1f393;标准库类型vector &#x1f393;定义和初始化vector的对象 &#x1f4bb;列表初始化vector对象 &#x1f4bb;创建指定数量的元素 &#x1f576;️值初始化 ❗列表初始化还是值初始化&#xf…

Vuex快速上手

一、Vuex 概述 目标&#xff1a;明确Vuex是什么&#xff0c;应用场景以及优势 1.是什么 Vuex 是一个 Vue 的 状态管理工具&#xff0c;状态就是数据。 大白话&#xff1a;Vuex 是一个插件&#xff0c;可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如&#xff1a;购…

DevEco Studio 3.1IDE环境配置(HarmonyOS 3.1)

DevEco Studio 3.1IDE环境配置&#xff08;HarmonyOS 3.1&#xff09; 一、安装环境 操作系统: Windows 10 专业版 IDE:DevEco Studio 3.1 SDK:HarmonyOS 3.1 二、环境安装 IDE下载地址&#xff1a;HUAWEI DevEco Studio和SDK下载和升级 | HarmonyOS开发者 IDE的安装就是…

关于uniapp X 的最新消息

uni-app x 是什么&#xff1f; uni-app x&#xff0c;是下一代 uni-app&#xff0c;是一个跨平台应用开发引擎。 uni-app x 没有使用js和webview&#xff0c;它基于 uts 语言。在App端&#xff0c;uts在iOS编译为swift、在Android编译为kotlin&#xff0c;完全达到了原生应用的…

计算机网络(三) | 数据链路层 PPP协议、广播CSMA/CD协议、集线器、交换器、扩展and高速以太网

文章目录 1 数据链路基本概念和问题1.1 基本概念1.2 基本问题&#xff08;1&#xff09;封装成帧&#xff08;2&#xff09;透明传输&#xff08;3&#xff09;差错控制 2.数据链路层协议2.1 点对点 PPP协议2.1.1 需要实现的2.1.2 PPP组成2.1.3 帧格式2.1.4 工作流程 2.2 广播 …

python:五种算法(HHO、WOA、GWO、PSO、GA)求解23个测试函数(python代码)

一、五种算法简介 1、哈里斯鹰优化算法HHO 2、鲸鱼优化算法WOA 3、灰狼优化算法GWO 4、粒子群优化算法PSO 5、遗传算法GA 二、5种算法求解23个函数 &#xff08;1&#xff09;23个函数简介 参考文献&#xff1a; [1] Yao X, Liu Y, Lin G M. Evolutionary programming …

树莓派,opencv,Picamera2利用舵机云台追踪人脸

一、需要准备的硬件 Raspiberry 4b两个SG90 180度舵机&#xff08;注意舵机的角度&#xff0c;最好是180度且带限位的&#xff0c;切勿选360度舵机&#xff09;二自由度舵机云台&#xff08;如下图&#xff09;Raspiberry CSI 摄像头 组装后的效果&#xff1a; 二、项目目标…

Unity之OpenXR+XR Interaction Toolkit接入微软VR设备Windows Mixed Reality

前言 Windows Mixed Reality 是 Microsoft 用于增强和虚拟现实体验的VR设备,如下图所示: 在国内,它的使用率很低,一把都是国外使用,所以适配起来是相当费劲。 这台VR设备只能用于串流Windows,启动后,会自动连接Window的Mixed Reality程序,然后打开微软的增强现实门户…

LAMP 搭建

目录 LAMP LAMP组成及作用 LAMP搭建实验举例&#xff0c;优先将防火墙和安全终端关闭&#xff0c;在一台虚拟机上操作 搭建 apache httpd服务 搭建 mysql服务 搭建 php服务 安装论坛 LAMP —— LAMP架构是目前成熟的企业网站应用模式之一&#xff0c;指的是协同工作的一…

记录汇川:自由口案例01-梯形图

H5U和FX5U通信&#xff1a;通过H5U区点亮FX5U的Y0-Y7 H5U配置 FX5U配置 02 0F 00 00 00 08 01 FF CRC校验码高 CRC校验码低 02:FX5U的站地址 0F:多个线圈写入 00 00:FX5U的MODBUS地址Y0开始 00 08&#xff1a;Y0 - Y7 FF:1111 1111 将Y0 - Y7全部点亮 主程序 MAIN: 记录汇川&a…

开源框架Apache NiFi调研

开源框架Apache NiFi调研 NiFi背景介绍一、什么是NiFi1.1 Apache NiFi特点&#xff1a;流管理、易用性、安全性、可扩展的体系结构和灵活的伸缩模型。1.2 Apache NiFi特性1.2 Apache NiFi核心概念1.3架构 二、NiFi的诞生&#xff0c;要致力于解决的问题有哪些&#xff1f;三、为…

DevEco Studio IDE 创建项目时候配置环境

DevEco Studio IDE 创建项目时候配置环境 一、安装环境 操作系统: Windows 10 专业版 IDE:DevEco Studio 3.1 SDK:HarmonyOS 3.1 二、在配置向导的时候意外关闭配置界面该如何二次配置IDE环境。 打开IDE的界面是这样的。 点击Create Project进行环境配置。 点击OK后出现如…

Mac安装DevEco Studio

下载 首先进入鸿蒙开发者官网&#xff0c;顶部导航栏选择开发->DevEco Studio 根据操作系统下载不同版本&#xff0c;其中Mac(X86)为英特尔芯片&#xff0c;Mac(ARM)为M芯片。 安装 下载完毕后&#xff0c;开始安装。 点击Agree 首次使用&#xff0c;请选择Do not impor…

037.Python面向对象_关于抽象类和抽象方法

我 的 个 人 主 页&#xff1a;&#x1f449;&#x1f449; 失心疯的个人主页 &#x1f448;&#x1f448; 入 门 教 程 推 荐 &#xff1a;&#x1f449;&#x1f449; Python零基础入门教程合集 &#x1f448;&#x1f448; 虚 拟 环 境 搭 建 &#xff1a;&#x1f449;&…

ssm基于MVC的舞蹈网站的设计与实现论文

摘 要 随着科学技术的飞速发展&#xff0c;社会的方方面面、各行各业都在努力与现代的先进技术接轨&#xff0c;通过科技手段来提高自身的优势&#xff0c;舞蹈网站当然也不能排除在外。舞蹈网站是以实际运用为开发背景&#xff0c;运用软件工程开发方法&#xff0c;采用Java技…

人体关键点检测2:Pytorch实现人体关键点检测(人体姿势估计)含训练代码

人体关键点检测2&#xff1a;Pytorch实现人体关键点检测(人体姿势估计)含训练代码 目录 人体关键点检测2&#xff1a;Pytorch实现人体关键点检测(人体姿势估计)含训练代码 1. 前言 2.人体关键点检测方法 (1)Top-Down(自上而下)方法 (2)Bottom-Up(自下而上)方法&#xff1…

(企业 / 公司项目) 企业项目如何使用jwt?

按照企业的项目然后写的小demo&#xff0c; 自己搞一个登录接口然后调用jwtUtil工具类 后端实现 创建一个通用模块common来实现jwt生成token 登录注册的基本实现逻辑思路 面试| ProcessOn免费在线作图,在线流程图,在线思维导图 注释挺详细的jwtUtil工具类&#xff0c; 封装的…

低功耗模式的通用 MCU ACM32F0X0 系列,具有高整合度、高抗干扰、 高可靠性的特点

ACM32F0X0 系列是一款支持多种低功耗模式的通用 MCU。集成 12 位 1.6 Msps 高精度 ADC 以及比 较器、运放、触控按键控制器、段式 LCD 控制器&#xff0c;内置高性能定时器、多路 UART、LPUART、SPI、I2C 等丰富的通讯外设&#xff0c;内建 AES、TRNG 等信息安全模块&#xff0…

Cannot find cache named ‘‘ for Builder Redis

当引入 Redissson 时&#xff0c;springCache 缓存机制失效 原因&#xff1a;springCache 默认使用本地缓存 Redisson 使用redis 缓存 最后都转成redis了。。。 总感觉哪不对 两者居然不共存

es6从url中获取想要的参数

第一种方法 很古老&#xff0c;通过 split 方法慢慢截取&#xff0c;可行是可行但是这个方法有一个弊端&#xff0c;因为 split 是分割成数组了&#xff0c;只能按照下标的位置获取值&#xff0c;所以就是参数位置一旦发生变化&#xff0c;那么获取到的值也就错位了 let user…
最新文章