当前位置: 首页 > article >正文

C# OpenCvSharp DNN 部署yolov4目标检测

目录

效果

项目

代码

下载


效果

项目

代码

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;

        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.5f;
            nmsThreshold = 0.4f;

            inpHeight = 416;
            inpWidth = 416;

            opencv_net = CvDnn.ReadNetFromDarknet("model/yolov4.cfg", "model/yolov4.weights");

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

        }

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

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

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

            //模型推理,读取推理结果
            var outNames = opencv_net.GetUnconnectedOutLayersNames();
            var outs = outNames.Select(_ => new Mat()).ToArray();

            dt1 = DateTime.Now;

            opencv_net.Forward(outs, outNames);

            dt2 = DateTime.Now;

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

            for (int i = 0; i < outs.Length; ++i)
            {
                float* data = (float*)outs[i].Data;
                for (int j = 0; j < outs[i].Rows; ++j, data += outs[i].Cols)
                {
                    Mat scores = outs[i].Row(j).ColRange(5, outs[i].Cols);

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

                    if (max_class_socre > confThreshold)
                    {
                        int centerX = (int)(data[0] * image.Cols);
                        int centerY = (int)(data[1] * image.Rows);
                        int width = (int)(data[2] * image.Cols);
                        int height = (int)(data[3] * image.Rows);
                        int left = centerX - width / 2;
                        int top = centerY - height / 2;

                        classIds.Add(classIdPoint.X);
                        confidences.Add((float)max_class_socre);
                        boxes.Add(new Rect(left, top, width, height));
                    }
                }
            }

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

            result_image = image.Clone();

            for (int i = 0; i < indices.Length; ++i)
            {
                int idx = indices[i];
                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, 1, new Scalar(0, 0, 255), 2);
            }

            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.kler.cn/a/230077.html

相关文章:

  • 单片机将图片数组调出来显示MPU8_8bpp_Memory_Write
  • linux模拟HID USB设备及wireshark USB抓包配置
  • 「Mac畅玩鸿蒙与硬件33」UI互动应用篇10 - 数字猜谜游戏
  • PointNet++论文复现
  • 太速科技-512-基于ZU19EG的4路100G 8路40G的光纤汇流计算卡
  • C#+数据库 实现动态权限设置
  • 揭秘:IT行业有哪些证书含金量高?
  • ThinkPHP6进阶教程:如何优雅地使用Auth模块进行权限验证
  • C++多线程学习[六]: 多线程之间的同步
  • seatunnel数据集成(二)数据同步
  • 简单指针运算c语言
  • JAVA中的main方法
  • 如何使用Docker部署DashDot服务器仪表盘并结合cpolar实现公网访问
  • Django连接Mysql
  • CSS是一门需要单独学习的技术吗?
  • STM32之USART
  • 敏捷开发的INVEST原则
  • Python 中的 os 模块常见方法
  • Leetcode 518 零钱兑换 II
  • GPTs保姆级教程之实践
  • 一周学会Django5 Python Web开发-Django5介绍及安装
  • npm 上传一个自己的应用(3) 在项目中导入及使用自己上传到NPM的工具
  • 【Vitis】HLS高层次综合的优势
  • 【Linux系统化学习】进程替换
  • 阿里云OSS对象存储
  • 大型装备制造企业案例分享——通过CRM系统管理全球业务