C# OpenCvSharp DNN 部署yolov3目标检测

news/2024/7/10 0:52:27 标签: dnn, YOLO, 目标检测, 人工智能, c#, 神经网络, opencv

目录

效果

yolov3.cfg

项目

代码

下载


C# OpenCvSharp DNN 部署yolov3目标检测

效果

yolov3.cfg

[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=16
subdivisions=1
width=416
height=416
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1

learning_rate=0.001
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1

[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky

# Downsample

[convolutional]
batch_normalize=1
filters=64
size=3
stride=2
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=32
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

# Downsample

[convolutional]
batch_normalize=1
filters=128
size=3
stride=2
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

# Downsample

[convolutional]
batch_normalize=1
filters=256
size=3
stride=2
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

# Downsample

[convolutional]
batch_normalize=1
filters=512
size=3
stride=2
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear


[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

# Downsample

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=2
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky

[shortcut]
from=-3
activation=linear

######################

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky

[convolutional]
size=1
stride=1
pad=1
filters=255
activation=linear


[yolo]
mask = 6,7,8
anchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326
classes=80
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1


[route]
layers = -4

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[upsample]
stride=2

[route]
layers = -1, 61



[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=512
activation=leaky

[convolutional]
size=1
stride=1
pad=1
filters=255
activation=linear


[yolo]
mask = 3,4,5
anchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326
classes=80
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1



[route]
layers = -4

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[upsample]
stride=2

[route]
layers = -1, 36



[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=256
activation=leaky

[convolutional]
size=1
stride=1
pad=1
filters=255
activation=linear


[yolo]
mask = 0,1,2
anchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326
classes=80
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1

项目

代码

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/yolov3.cfg", "model/yolov3.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);
        }
    }
}

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/yolov3.cfg", "model/yolov3.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.niftyadmin.cn/n/5326499.html

相关文章

HEXO搭建个人博客

Hexo是一款基于Node.js的静态博客框架&#xff0c;可以生成静态网页托管在GitHub上。中文文档见HEXO 配置环境 安装Git&#xff1a;下载并安装Git 检查git是否正确安装&#xff1a; git --version 安装Node.js&#xff1a;Node.js 为大多数平台提供了官方的安装程序。注意安装…

AI绘图 | 一个免费使用AI绘图的方法

一个免费使用AI绘图的方法 当然了&#xff0c;不是完全随便用 有一些限制 但是轻度使用是够的 毕竟成本在那&#xff0c;完全免费就别想了 目前绘图软件比较火的&#xff0c;就是 Stable Diffusion &#xff08;简称sd&#xff09; Midjourney&#xff08;简称MJ&#xff09; d…

六个字总结用友U8 BI方案:不加班、涨业绩

首先&#xff0c;聊聊不加班&#xff1a;用了用友U8 BI方案后&#xff0c;简单操作即可立即生成BI数据可视化分析报表。这些报表的特点是实用、直观、灵活分析&#xff0c;也是这些特点直接降低了重复性操作&#xff0c;提升数据分析灵活性、及时性&#xff0c;让上至老板&…

使用WAF防御网络上的隐蔽威胁之SSRF攻击

服务器端请求伪造&#xff08;SSRF&#xff09;攻击是一种常见的网络安全威胁&#xff0c;它允许攻击者诱使服务器执行恶意请求。与跨站请求伪造&#xff08;CSRF&#xff09;相比&#xff0c;SSRF攻击针对的是服务器而不是用户。了解SSRF攻击的工作原理、如何防御它&#xff0…

QT-JSON相关API/QJsonDocument/QJsonObject

QJsonObject类的相关操作 格式化排版创建JSON对象&#xff0c;使用字符串创建JSON对象&#xff0c;使用标准JSON对象获取JSON对象中的值&#xff0c;非数组获取JSON对象中的值&#xff0c;数组 格式化排版 下面的代码将一个符合JSON格式的字符串&#xff0c;格式化成具有缩进格…

2024年腾讯云服务器购买优惠,附价格表

腾讯云服务器租用价格表&#xff1a;轻量应用服务器2核2G3M价格62元一年、2核2G4M价格118元一年&#xff0c;540元三年、2核4G5M带宽218元一年&#xff0c;2核4G5M带宽756元三年、轻量4核8G12M服务器446元一年、646元15个月&#xff0c;云服务器CVM S5实例2核2G配置280.8元一年…

unity C#什么是线程锁,以及使用案例

文章目录 原理1. **互斥**&#xff08;Mutual Exclusion&#xff09;:2. **缓存一致性与内存屏障**&#xff1a;3. **操作系统的支持**&#xff1a;4. **编程语言级别的实现**&#xff1a;5. **避免死锁**&#xff1a;图示 实例1实例2 原理 线程锁的原理主要是为了在多线程环境…

Python通过配置文件控制日志打印

引言&#xff1a; 作为一个Java程序员&#xff0c;我们使用过log4j,logback等一系列的日志打印框架&#xff0c;还有比较简单的Slf4j&#xff0c;只需要一个annotation&#xff0c;就可以很简单的输出日志了&#xff0c;并且日志文件可以按天或者按大小进行滚动&#xff0c;那…