C# OpenCvSharp DNN HybridNets 同时处理车辆检测、可驾驶区域分割、车道线分割

效果

项目

代码

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
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;
        string anchorpath;
 
        int inpHeight;
        int inpWidth;
 
        float[] mean = { 0.485f, 0.456f, 0.406f };
        float[] std = { 0.229f, 0.224f, 0.225f };
 
        List<string> det_class_names = new List<string>() { "car" };
        List<string> seg_class_names = new List<string>() { "Background", "Lane", "Line" };
        List<Vec3b> class_colors = new List<Vec3b> { new Vec3b(0, 0, 0), new Vec3b(0, 255, 0), new Vec3b(255, 0, 0) };
 
        int det_num_class = 1;
        int seg_numclass = 3;
 
        float[] anchors;
 
        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/hybridnets_256x384.onnx";
            anchorpath = "model/anchors_73656.bin";
 
            inpHeight = 256;
            inpWidth = 384;
 
            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);
 
            FileStream fileStream = new FileStream(anchorpath, FileMode.Open);
            //读二进制文件类
            BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
            int len = 73656;
            anchors = new float[len];
 
            byte[] byteTemp;
            float fTemp;
            for (int i = 0; i < len; i++)
            {
                byteTemp = br.ReadBytes(4);
                fTemp = BitConverter.ToSingle(byteTemp, 0);
                anchors[i] = fTemp;
            }
            br.Close();
 
            image_path = "test_img/test.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);
 
            int newh = 0, neww = 0, padh = 0, padw = 0;
            Mat resize_img = Common.ResizeImage(image, inpHeight, inpWidth, ref newh, ref neww, ref padh, ref padw);
 
            float ratioh = (float)image.Rows / newh;
            float ratiow = (float)image.Cols / neww;
 
            Mat normalize = Common.Normalize(resize_img, mean, std);
 
            dt1 = DateTime.Now;
 
            BN_image = CvDnn.BlobFromImage(normalize);
 
            //配置图片输入数据
            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;
 
            float* classification = (float*)outs[0].Data;
            float* box_regression = (float*)outs[1].Data;
            float* seg = (float*)outs[2].Data;
 
            List<Rect> boxes = new List<Rect>();
            List<float> confidences = new List<float>();
            List<int> classIds = new List<int>();
 
            int num_proposal = outs[1].Size(1);  //输入的是单张图, 第0维batchsize忽略
 
            for (int n = 0; n < num_proposal; n++)
            {
                float conf = classification[n];
 
                if (conf > confThreshold)
                {
                    int row_ind = n * 4;
                    float x_centers = box_regression[row_ind + 1] * anchors[row_ind + 2] + anchors[row_ind];
                    float y_centers = box_regression[row_ind] * anchors[row_ind + 3] + anchors[row_ind + 1];
                    float w = (float)(Math.Exp(box_regression[row_ind + 3]) * anchors[row_ind + 2]);
                    float h = (float)(Math.Exp(box_regression[row_ind + 2]) * anchors[row_ind + 3]);
 
                    float xmin = (float)((x_centers - w * 0.5 - padw) * ratiow);
                    float ymin = (float)((y_centers - h * 0.5 - padh) * ratioh);
                    w *= ratiow;
                    h *= ratioh;
                    Rect box = new Rect((int)xmin, (int)ymin, (int)w, (int)h);
                    boxes.Add(box);
                    confidences.Add(conf);
                    classIds.Add(0);
                }
 
            }
 
            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 = det_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);
            }
 
            int area = inpHeight * inpWidth;
            int i = 0, j = 0, c = 0;
            for (i = 0; i < result_image.Rows; i++)
            {
                for (j = 0; j < result_image.Cols; j++)
                {
                    int x = (int)((j / ratiow) + padw);  ///从原图映射回到输出特征图
                    int y = (int)((i / ratioh) + padh);
                    int max_id = -1;
                    float max_conf = -10000;
                    for (c = 0; c < seg_numclass; c++)
                    {
                        float seg_conf = seg[c * area + y * inpWidth + x];
                        if (seg_conf > max_conf)
                        {
                            max_id = c;
                            max_conf = seg_conf;
                        }
                    }
                    if (max_id > 0)
                    {
                        result_image.Set<Vec3b>(i, j, class_colors[max_id]);
                    }
                }
            }
 
            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);
        }
    }
}

下载

源码下载

相关推荐
这个男人是小帅3 分钟前
【GAT】 代码详解 (1) 运行方法【pytorch】可运行版本
人工智能·pytorch·python·深度学习·分类
__基本操作__5 分钟前
边缘提取函数 [OPENCV--2]
人工智能·opencv·计算机视觉
Doctor老王10 分钟前
TR3:Pytorch复现Transformer
人工智能·pytorch·transformer
热爱生活的五柒10 分钟前
pytorch中数据和模型都要部署在cuda上面
人工智能·pytorch·深度学习
HyperAI超神经2 小时前
【TVM 教程】使用 Tensorize 来利用硬件内联函数
人工智能·深度学习·自然语言处理·tvm·计算机技术·编程开发·编译框架
扫地的小何尚4 小时前
NVIDIA RTX 系统上使用 llama.cpp 加速 LLM
人工智能·aigc·llama·gpu·nvidia·cuda·英伟达
埃菲尔铁塔_CV算法6 小时前
深度学习神经网络创新点方向
人工智能·深度学习·神经网络
艾思科蓝-何老师【H8053】7 小时前
【ACM出版】第四届信号处理与通信技术国际学术会议(SPCT 2024)
人工智能·信号处理·论文发表·香港中文大学
weixin_452600697 小时前
《青牛科技 GC6125:驱动芯片中的璀璨之星,点亮 IPcamera 和云台控制(替代 BU24025/ROHM)》
人工智能·科技·单片机·嵌入式硬件·新能源充电桩·智能充电枪
学术搬运工7 小时前
【珠海科技学院主办,暨南大学协办 | IEEE出版 | EI检索稳定 】2024年健康大数据与智能医疗国际会议(ICHIH 2024)
大数据·图像处理·人工智能·科技·机器学习·自然语言处理