C# OpenCvSharp DNN 部署yoloX

这篇具有很好参考价值的文章主要介绍了C# OpenCvSharp DNN 部署yoloX。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署yoloX

效果

C# OpenCvSharp DNN 部署yoloX,C#人工智能实践,dnn,人工智能,神经网络,c#,opencv,计算机视觉,目标检测

模型信息

Inputs
-------------------------
name:images
tensor:Float[1, 3, 640, 640]
---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:Float[1, 8400, 85]
---------------------------------------------------------------

项目

C# OpenCvSharp DNN 部署yoloX,C#人工智能实践,dnn,人工智能,神经网络,c#,opencv,计算机视觉,目标检测

代码

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 prob_threshold;
        float nms_threshold;

        float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };

        int[] input_shape = new int[] { 640, 640 };   // height, width

        float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
        float scale = 1.0f;

        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        public Mat Normalize(Mat src)
        {
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return src;
        }

        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)
        {
            prob_threshold = 0.6f;
            nms_threshold = 0.6f;

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

        }

        Mat ResizeImage(Mat srcimg)
        {

            float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
            scale = r;
            int unpad_w = (int)(r * srcimg.Cols);
            int unpad_h = (int)(r * srcimg.Rows);
            Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
            Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
            Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
            re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
            return outMat;
        }


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

            Mat dstimg = ResizeImage(image);

            dstimg = Normalize(dstimg);

            BN_image = CvDnn.BlobFromImage(dstimg);

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

            //模型推理,读取推理结果
            Mat[] outs = 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(1);
            outs[0] = outs[0].Reshape(0, num_proposal);

            float* pdata = (float*)outs[0].Data;

            int row_ind = 0;
            int nout = num_class + 5;

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

            for (int n = 0; n < 3; n++)
            {
                int num_grid_x = (int)(inpWidth / stride[n]);
                int num_grid_y = (int)(inpHeight / stride[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].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);

                        int class_idx = classIdPoint.X;

                        float cls_score = pdata[5 + class_idx];
                        float box_prob = box_score * cls_score;
                        if (box_prob > prob_threshold)
                        {
                            float x_center = (pdata[0] + j) * stride[n];
                            float y_center = (pdata[1] + i) * stride[n];
                            float w = (float)(Math.Exp(pdata[2]) * stride[n]);
                            float h = (float)(Math.Exp(pdata[3]) * stride[n]);
                            float x0 = x_center - w * 0.5f;
                            float y0 = y_center - h * 0.5f;

                            classIds.Add(class_idx);
                            confidences.Add(box_prob);
                            boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
                        }

                        pdata += nout;
                        row_ind++;
                    }
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];

                // adjust offset to original unpadded
                float x0 = box.X / scale; ;
                float y0 = box.Y / scale; ;
                float x1 = (box.X + box.Width) / scale;
                float y1 = (box.Y + box.Height) / scale;

                // clip
                x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
                y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
                x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
                y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 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 prob_threshold;
        float nms_threshold;

        float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };

        int[] input_shape = new int[] { 640, 640 };   // height, width

        float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
        float scale = 1.0f;

        string modelpath;

        int inpHeight;
        int inpWidth;

        List<string> class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        public Mat Normalize(Mat src)
        {
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return src;
        }

        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)
        {
            prob_threshold = 0.6f;
            nms_threshold = 0.6f;

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

        }

        Mat ResizeImage(Mat srcimg)
        {

            float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
            scale = r;
            int unpad_w = (int)(r * srcimg.Cols);
            int unpad_h = (int)(r * srcimg.Rows);
            Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
            Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
            Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
            re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
            return outMat;
        }


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

            Mat dstimg = ResizeImage(image);

            dstimg = Normalize(dstimg);

            BN_image = CvDnn.BlobFromImage(dstimg);

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

            //模型推理,读取推理结果
            Mat[] outs = 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(1);
            outs[0] = outs[0].Reshape(0, num_proposal);

            float* pdata = (float*)outs[0].Data;

            int row_ind = 0;
            int nout = num_class + 5;

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

            for (int n = 0; n < 3; n++)
            {
                int num_grid_x = (int)(inpWidth / stride[n]);
                int num_grid_y = (int)(inpHeight / stride[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].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);

                        int class_idx = classIdPoint.X;

                        float cls_score = pdata[5 + class_idx];
                        float box_prob = box_score * cls_score;
                        if (box_prob > prob_threshold)
                        {
                            float x_center = (pdata[0] + j) * stride[n];
                            float y_center = (pdata[1] + i) * stride[n];
                            float w = (float)(Math.Exp(pdata[2]) * stride[n]);
                            float h = (float)(Math.Exp(pdata[3]) * stride[n]);
                            float x0 = x_center - w * 0.5f;
                            float y0 = y_center - h * 0.5f;

                            classIds.Add(class_idx);
                            confidences.Add(box_prob);
                            boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
                        }

                        pdata += nout;
                        row_ind++;
                    }
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];

                // adjust offset to original unpadded
                float x0 = box.X / scale; ;
                float y0 = box.Y / scale; ;
                float x1 = (box.X + box.Width) / scale;
                float y1 = (box.Y + box.Height) / scale;

                // clip
                x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
                y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
                x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
                y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 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);
        }
    }
}

下载

源码下载文章来源地址https://www.toymoban.com/news/detail-789293.html

到了这里,关于C# OpenCvSharp DNN 部署yoloX的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# OpenCvSharp DNN Onnx Demo 资源汇总

    目录 1、OCR 相关 2、人脸、人像、人头 相关 3、物体检测 对象识别相关 4、图像分类、实例分割 姿态识别 5、摄像头相关 6、条码、二维码相关 7、OpencvSharp Demo 8、其他 C# OpenCvSharp DNN Onnx Demo 资源汇总,不定时更新 最新更新时间:2023-11-13 我建了一个QQ群,欢迎大家进群交流 群

    2024年02月05日
    浏览(26)
  • C# OpenCvSharp DNN Low Light image Enhancement

    目录 介绍 效果 模型信息 项目 代码 下载 C# OpenCvSharp DNN Low Light image Enhancement github地址:https://github.com/zhenqifu/PairLIE     Model Properties ------------------------- --------------------------------------------------------------- Inputs ------------------------- name:input tensor:Float[1, 3, 512, 512] name:exposure

    2024年02月21日
    浏览(36)
  • C# OpenCvSharp DNN 二维码增强 超分辨率

    目录 效果 项目 代码 下载  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCvSharp; using OpenCvSharp.Dnn; using OpenCvSharp.Extensions; namespace OpenCvSharp_DNN_二维码增强 {     public partial cl

    2024年02月12日
    浏览(29)
  • C# OpenCvSharp DNN FreeYOLO 人脸检测&人脸图像质量评估

    目录 效果 模型信息 yolo_free_huge_widerface_192x320.onnx face-quality-assessment.onnx 项目 代码 frmMain.cs FreeYoloFace FaceQualityAssessment.cs 下载 C# OpenCvSharp DNN FreeYOLO 人脸检测人脸图像质量评估 Inputs ------------------------- name:input tensor:Float[1, 3, 192, 320] ------------------------------------------------------

    2024年01月22日
    浏览(35)
  • CSDN独家|YOLOv5改进、YOLOv7改进、YOLOv8改进、YOLOX改进目录一览|YOLO改进模型全系列目录(芒果书系列) | 人工智能专家老师联袂推荐

    🔥 《芒果书》系列改进专栏内的改进文章,均包含多种模型改进方式,均适用于 YOLOv3 、 YOLOv4 、 YOLOR 、 YOLOX 、 YOLOv5 、 YOLOv7 、 YOLOv8 改进(重点)!!! 🔥 专栏创新点教程 均有不少同学反应和我说已经在自己的数据集上有效涨点啦!! 包括COCO数据集也能涨点 , 所有文

    2024年02月03日
    浏览(43)
  • 微信小程序的人工智能模型部署(flask)

    目录 写在前面: 具体做法: 后端: 前端: 其他: 我使用的微信小程序开发工具是:“微信开发者工具”,当然你用其他的开发工具应该也差别不大; 人工智能模型用的是pytorch; 具体不介绍人工智能模型的保存,主要介绍一下flask的写法; 首先你要把人工智能模型先保存

    2024年02月15日
    浏览(87)
  • 数据驱动的人工智能:从算法设计到实践部署

    人工智能(Artificial Intelligence, AI)是一门研究如何让机器具有智能行为的学科。数据驱动的人工智能(Data-Driven AI)是一种通过大量数据来训练和优化机器学习模型的方法。这种方法的核心思想是通过大量数据来驱动机器学习模型的训练和优化,从而使其具备更好的性能和准确性。

    2024年02月22日
    浏览(29)
  • 美国家安全局等发布安全部署人工智能系统指南

    该指南旨在为部署和运行由其他实体设计和开发的人工智能系统的组织提供最佳实践。 2024年4月15日,美国国家安全局发布了名为《安全部署人工智能系统:部署安全、弹性人工智能系统的最佳实践》,该指南旨在为部署和运行由其他实体设计和开发的人工智能系统的组织提

    2024年04月22日
    浏览(27)
  • 人工智能CSDN版AI和百度AI代码转化测试,C#、Java代码转Python

    工作中,需要完成以下的工作场景: 【场景】单据转换不支持多选基础资料下推; 【案例】通过单据转换插件,实现应收单单据头的多选基础资料下推到付款申请单的单据头的多选基础资料 原文链接:https://vip.kingdee.com/article/324304152484608000?productLineId=1 需要将原代码转换为

    2024年02月03日
    浏览(36)
  • AI一叶知秋:从目标检测部署浅谈人工智能发展

    笔者写这篇文章也有讨巧之嫌,仅以个人视角分享一些看法,主要从实践部署来谈谈近两年来计算机视觉模型的变化,不过AI是一个宏大的话题,每个人定义的人工智能就不一样,我们先来探讨一下何为人工智能。百度百科中是这样定义的: 人工智能是研究、开发用于模拟、

    2024年02月02日
    浏览(79)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包