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

下载

源码下载

相关推荐
冷眼看人间恩怨7 分钟前
【话题讨论】AI大模型重塑软件开发:定义、应用、优势与挑战
人工智能·ai编程·软件开发
2401_883041088 分钟前
新锐品牌电商代运营公司都有哪些?
大数据·人工智能
AI极客菌1 小时前
Controlnet作者新作IC-light V2:基于FLUX训练,支持处理风格化图像,细节远高于SD1.5。
人工智能·计算机视觉·ai作画·stable diffusion·aigc·flux·人工智能作画
阿_旭1 小时前
一文读懂| 自注意力与交叉注意力机制在计算机视觉中作用与基本原理
人工智能·深度学习·计算机视觉·cross-attention·self-attention
王哈哈^_^1 小时前
【数据集】【YOLO】【目标检测】交通事故识别数据集 8939 张,YOLO道路事故目标检测实战训练教程!
前端·人工智能·深度学习·yolo·目标检测·计算机视觉·pyqt
Power20246662 小时前
NLP论文速读|LongReward:基于AI反馈来提升长上下文大语言模型
人工智能·深度学习·机器学习·自然语言处理·nlp
数据猎手小k2 小时前
AIDOVECL数据集:包含超过15000张AI生成的车辆图像数据集,目的解决旨在解决眼水平分类和定位问题。
人工智能·分类·数据挖掘
好奇龙猫2 小时前
【学习AI-相关路程-mnist手写数字分类-win-硬件:windows-自我学习AI-实验步骤-全连接神经网络(BPnetwork)-操作流程(3) 】
人工智能·算法
沉下心来学鲁班3 小时前
复现LLM:带你从零认识语言模型
人工智能·语言模型
数据猎手小k3 小时前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型