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_scorefloat* 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 scoreCv2.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;  //cxfloat cy = (pdata[1] - padh) * ratioh;   //cyfloat w = pdata[2] * ratiow;   //wfloat h = pdata[3] * ratioh;  //hint 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.hqwc.cn/news/266022.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

被忽悠选择那些价格昂贵的知识付费平台?我有才知识服务平台手把手教你如何正确选择!

在当今的知识经济时代&#xff0c;一个高效、便捷的知识服务平台对于企业和个人至关重要。然而&#xff0c;市面上的众多知识服务平台中&#xff0c;许多产品存在高昂的费用、无用功能的堆砌、无法定制化等问题&#xff0c;让用户进退两难&#xff0c;甚至被忽悠掉入使用陷阱。…

Leo赠书活动-13期 【以企业架构为中心的SABOE数字化转型五环法】文末送书

Leo赠书活动-13期 【以企业架构为中心的SABOE数字化转型五环法】文末送书 ✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客…

力扣77. 组合(java 回溯法)

Problem: 77. 组合 文章目录 题目描述思路解题方法复杂度Code 题目描述 思路 题目要求给出1-n中每k个数一组的所有组合&#xff0c;我们可以利用回溯&#xff0c;将其穷举出来&#xff0c;具体的&#xff1a; 1.以数字1-n为回溯的决策阶段&#xff0c;回溯的起始阶段为1 2.回溯…

外汇天眼:掌握这个技巧,你也能成为交易高手

在金融市场这个大潮中&#xff0c;外汇交易因其高杠杆、24小时交易等特点吸引着无数交易者。然而成功的交易并非易事&#xff0c;对于投资者来说&#xff0c;外汇交易市场是一个复杂且多变的市场&#xff0c;要在外汇市场中获得成功就需要扎实的外汇金融基础知识和独特的策略&a…

「实用教程」win32spl.dll文件的作用及修复方法分享

本文将为您详细介绍Win32spl.dll文件的作用、丢失原因以及提供5个修复教程&#xff0c;帮助您解决这一问题。 一、Win32spl.dll文件的作用 Win32spl.dll是一个动态链接库文件&#xff0c;它是Windows操作系统中的一个重要组件。该文件主要负责处理系统启动时的一些操作&#…

【LeetCode刷题】-- 118.杨辉三角

118.杨辉三角 class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> res new ArrayList<List<Integer>>();for(int i 0; i < numRows;i){List<Integer> ret new ArrayList<>();for(…

Docker中部署ElasticSearch 和Kibana,用脚本实现对数据库资源的未授权访问

图未保存&#xff0c;不过文章当中的某一步骤可能会帮助到您&#xff0c;那么&#xff1a;感恩&#xff01; 1、docker中拉取镜像 #拉取镜像 docker pull elasticsearch:7.7.0#启动镜像 docker run --name elasticsearch -d -e ES_JAVA_OPTS"-Xms512m -Xmx512m" -e…

入职字节外包一个月,我离职了。。。

有一种打工人的羡慕&#xff0c;叫做“大厂”。 真是年少不知大厂香&#xff0c;错把青春插稻秧。 但是&#xff0c;在深圳有一群比大厂员工更庞大的群体&#xff0c;他们顶着大厂的“名”&#xff0c;做着大厂的工作&#xff0c;还可以享受大厂的伙食&#xff0c;却没有大厂…

react Hooks(useRef、useMemo、useCallback)实现原理

Fiber 上篇文章fiber简单理解记录了react fiber架构&#xff0c;Hooks是基于fiber链表来实现的。阅读以下内容时建议先了解react fiber。 jsx -> render function -> vdom -> fiber树 -> dom vdom 转 fiber 的过程称为 recocile。diff算法就是在recocile这个过程…

Android渲染-AHardwareBuffer

本文主要从应用的角度介绍android的native层AHardwareBuffer创建纹理以及保存渲染数据。 HardwareBuffer 要介绍native层的AHardwareBuffer&#xff0c;就需要先从Java层的HardwareBuffer说起。Android官方对于HardwareBuffer介绍如下&#xff1a; HardwareBuffer wraps a na…

网络安全攻击预警/态势预测算法汇总

总结&#xff1a; 网络安全攻击预警/态势预测算法众多&#xff0c;主要包括&#xff1a; 基于统计学的算法&#xff1a;协方差矩阵、马尔可夫模型等&#xff1b; 基于机器学习的算法&#xff1a;贝叶斯网络、聚类算法、支持向量机SVM、遗传算法、层次分析法AHP、决策树等&am…

快应用实现横向滚动列表 (前端)

在快应用里&#xff0c;想要实现uview里面的这个效果 可以使用list组件&#xff0c;flex-direction这个属性是关键的 <template><div><list class"list" flex-direction"row" ><list-item type"listItem" class"item&…