C# OpenCvSharp DNN 部署FastestDet

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署FastestDet

效果

模型信息

Inputs


name:input.1

tensor:Float[1, 3, 512, 512]


Outputs


name:761

tensor:Float[1024, 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.8f;

nmsThreshold = 0.35f;

modelpath = "model/FastestDet.onnx";

inpHeight = 512;

inpWidth = 512;

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/4.jpg";

pictureBox1.Image = new Bitmap(image_path);

}

float sigmoid(float x)

{

return (float)(1.0 / (1 + Math.Exp(-x)));

}

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

dt1 = DateTime.Now;

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

//配置图片输入数据

opencv_net.SetInput(BN_image);

//模型推理,读取推理结果

Mat[] outs = new Mat[3] { new Mat(), new Mat(), new Mat() };

string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();

opencv_net.Forward(outs, outBlobNames);

dt2 = DateTime.Now;

int num_proposal = outs[0].Size(0);

int nout = outs[0].Size(1);

int i = 0, j = 0, row_ind = 0; //box_score, xmin,ymin,xamx,ymax,class_score

int num_grid_x = 32;

int num_grid_y = 32;

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 (i = 0; i < num_grid_y; i++)

{

for (j = 0; j < num_grid_x; j++)

{

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 *= pdata[0];

if (max_class_socre > confThreshold)

{

int class_idx = classIdPoint.X;

float cx = (float)((Math.Tanh(pdata[1]) + j) / (float)num_grid_x); //cx

float cy = (float)((Math.Tanh(pdata[2]) + i) / (float)num_grid_y); //cy

float w = sigmoid(pdata[3]); //w

float h = sigmoid(pdata[4]); //h

cx *= image.Cols;

cy *= image.Rows;

w *= image.Cols;

h *= image.Rows;

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.8f;
            nmsThreshold = 0.35f;
            modelpath = "model/FastestDet.onnx";

            inpHeight = 512;
            inpWidth = 512;

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

        }

        float sigmoid(float x)
        {
            return (float)(1.0 / (1 + Math.Exp(-x)));
        }

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

            dt1 = DateTime.Now;

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

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

            //模型推理,读取推理结果
            Mat[] outs = new Mat[3] { new Mat(), new Mat(), new Mat() };
            string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

            int num_proposal = outs[0].Size(0);
            int nout = outs[0].Size(1);

            int i = 0, j = 0, row_ind = 0; //box_score, xmin,ymin,xamx,ymax,class_score
            int num_grid_x = 32;
            int num_grid_y = 32;
            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 (i = 0; i < num_grid_y; i++)
            {
                for (j = 0; j < num_grid_x; j++)
                {
                    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 *= pdata[0];
                    if (max_class_socre > confThreshold)
                    {
                        int class_idx = classIdPoint.X;
                        float cx = (float)((Math.Tanh(pdata[1]) + j) / (float)num_grid_x);  //cx
                        float cy = (float)((Math.Tanh(pdata[2]) + i) / (float)num_grid_y);   //cy
                        float w = sigmoid(pdata[3]);   //w
                        float h = sigmoid(pdata[4]);  //h

                        cx *= image.Cols;
                        cy *= image.Rows;
                        w *= image.Cols;
                        h *= image.Rows;

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

下载

源码下载

相关推荐
徐礼昭|商派软件市场负责人几秒前
AI 重构网购体验:从 “将就” 到 “讲究” 的消费者进化史|徐礼昭
大数据·人工智能·重构·智能客服·零售·智能搜索·ai推荐
ViiTor_AI1 分钟前
视频水印怎么去?8 款免费视频水印去除工具实测对比(不模糊)
人工智能·音视频
CC.GG2 分钟前
【C++】C++11(二)可变模板参数模板、新的类功能、包装器(function、bind)
开发语言·c++
Java后端的Ai之路2 分钟前
【AI大模型开发】-RAG多模态详解(通俗易懂)
人工智能·大模型·rag多模态
飞凌嵌入式4 分钟前
嵌入式AI领域的主控选择
linux·arm开发·人工智能·嵌入式硬件
_YiFei4 分钟前
2026年论文保姆级攻略:降ai率工具深度实测(附免费降ai率避坑指南)
人工智能
一只大侠的侠5 分钟前
用PyTorch Lightning快速搭建可复现实验 pipeline
人工智能·pytorch·python
KG_LLM图谱增强大模型6 分钟前
[290页电子书]打造企业级知识图谱的实战手册,Neo4j 首席科学家力作!从图数据库基础到图原生机器学习
人工智能·知识图谱·neo4j
Yupureki11 分钟前
《算法竞赛从入门到国奖》算法基础:入门篇-分治
c语言·开发语言·数据结构·c++·算法·贪心算法
无忧智库12 分钟前
深度解析:某流域水务集团“数字孪生流域”建设工程可行性研究报告(万字长文)(WORD)
大数据·人工智能