C# OpenCvSharp DNN Yolov8-OBB 旋转目标检测

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN Yolov8-OBB 旋转目标检测

效果

模型信息

Model Properties
-------------------------
date:2024-02-26T08:38:44.171849
description:Ultralytics YOLOv8s-obb model trained on runs/DOTAv1.0-ms.yaml
author:Ultralytics
task:obb
license:AGPL-3.0 https://ultralytics.com/license
version:8.1.18
stride:32
batch:1
imgsz:[640, 640]
names:{0: 'plane', 1: 'ship', 2: 'storage tank', 3: 'baseball diamond', 4: 'tennis court', 5: 'basketball court', 6: 'ground track field', 7: 'harbor', 8: 'bridge', 9: 'large vehicle', 10: 'small vehicle', 11: 'helicopter', 12: 'roundabout', 13: 'soccer ball field', 14: 'swimming pool'}
---------------------------------------------------------------

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

Outputs
-------------------------
name:output0
tensor:Float[1, 20, 8400]
---------------------------------------------------------------

项目

代码

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;

        string modelpath;
        string classer_path;

        List<string> class_names;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        string[] class_lables;

        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)
        {
            modelpath = "model/yolov8s-obb.onnx";
            classer_path = "model/lable.txt";

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            List<string> str = new List<string>();
            StreamReader sr = new StreamReader(classer_path);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                str.Add(line);
            }
            class_lables = str.ToArray();

            image_path = "test_img/1.png";
            pictureBox1.Image = new Bitmap(image_path);

        }

        private  void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }
            textBox1.Text = "检测中,请稍等……";
            pictureBox2.Image = null;
            button2.Enabled = false;
            Application.DoEvents();

            image = new Mat(image_path);

            //图片缩放
            image = new Mat(image_path);
            int max_image_length = image.Cols > image.Rows ? image.Cols : image.Rows;
            Mat max_image = Mat.Zeros(new OpenCvSharp.Size(max_image_length, max_image_length), MatType.CV_8UC3);
            Rect roi = new Rect(0, 0, image.Cols, image.Rows);
            image.CopyTo(new Mat(max_image, roi));

            float[] result_array;
            float factor = (float)(max_image_length / 640.0);

            // 将图片转为RGB通道
            Mat image_rgb = new Mat();
            Cv2.CvtColor(max_image, image_rgb, ColorConversionCodes.BGR2RGB);
            Mat resize_image = new Mat();
            Cv2.Resize(image_rgb, resize_image, new OpenCvSharp.Size(640, 640));

            BN_image = CvDnn.BlobFromImage(resize_image, 1 / 255.0, new OpenCvSharp.Size(640, 640), new Scalar(0, 0, 0), true, false);

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

            //模型推理,读取推理结果
            Mat[] outs = new Mat[1] { 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);
            int nout = outs[0].Size(2);

            if (outs[0].Dims > 2)
            {
                outs[0] = outs[0].Reshape(0, num_proposal);
            }

            Mat result_data = new Mat(20, 8400, MatType.CV_32F);
            result_data = outs[0].T();
            List<Rect2d> position_boxes = new List<Rect2d>();
            List<int> class_ids = new List<int>();
            List<float> confidences = new List<float>();
            List<float> rotations = new List<float>();
            // Preprocessing output results
            for (int i = 0; i < result_data.Rows; i++)
            {
                Mat classes_scores = new Mat(result_data, new Rect(4, i, 15, 1));
                OpenCvSharp.Point max_classId_point, min_classId_point;
                double max_score, min_score;
                // Obtain the maximum value and its position in a set of data
                Cv2.MinMaxLoc(classes_scores, out min_score, out max_score,
                    out min_classId_point, out max_classId_point);
                // Confidence level between 0 ~ 1
                // Obtain identification box information
                if (max_score > 0.25)
                {
                    float cx = result_data.At<float>(i, 0);
                    float cy = result_data.At<float>(i, 1);
                    float ow = result_data.At<float>(i, 2);
                    float oh = result_data.At<float>(i, 3);
                    double x = (cx - 0.5 * ow) * factor;
                    double y = (cy - 0.5 * oh) * factor;
                    double width = ow * factor;
                    double height = oh * factor;
                    Rect2d box = new Rect2d();
                    box.X = x;
                    box.Y = y;
                    box.Width = width;
                    box.Height = height;
                    position_boxes.Add(box);
                    class_ids.Add(max_classId_point.X);
                    confidences.Add((float)max_score);
                    rotations.Add(result_data.At<float>(i, 19));
                }
            }

            // NMS 
            int[] indexes = new int[position_boxes.Count];
            CvDnn.NMSBoxes(position_boxes, confidences, 0.25f, 0.7f, out indexes);
            List<RotatedRect> rotated_rects = new List<RotatedRect>();
            for (int i = 0; i < indexes.Length; i++)
            {
                int index = indexes[i];
                float w = (float)position_boxes[index].Width;
                float h = (float)position_boxes[index].Height;
                float x = (float)position_boxes[index].X + w / 2;
                float y = (float)position_boxes[index].Y + h / 2;
                float r = rotations[index];
                float w_ = w > h ? w : h;
                float h_ = w > h ? h : w;
                r = (float)((w > h ? r : (float)(r + Math.PI / 2)) % Math.PI);
                RotatedRect rotate = new RotatedRect(new Point2f(x, y), new Size2f(w_, h_), (float)(r * 180.0 / Math.PI));
                rotated_rects.Add(rotate);
            }

            result_image = image.Clone();

            for (int i = 0; i < indexes.Length; i++)
            {
                int index = indexes[i];
                Point2f[] points = rotated_rects[i].Points();

                for (int j = 0; j < 4; j++)
                {
                    Cv2.Line(result_image, (OpenCvSharp.Point)points[j], (OpenCvSharp.Point)points[(j + 1) % 4], new Scalar(0, 255, 0), 2);
                }

                Cv2.PutText(result_image, class_lables[class_ids[index]] + "-" + confidences[index].ToString("0.00"),
                    (OpenCvSharp.Point)points[0], HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 0, 255), 2);
            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";

            button2.Enabled = true;
        }

        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;string modelpath;string classer_path;List<string> class_names;Net opencv_net;Mat BN_image;Mat image;Mat result_image;string[] class_lables;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){modelpath = "model/yolov8s-obb.onnx";classer_path = "model/lable.txt";opencv_net = CvDnn.ReadNetFromOnnx(modelpath);List<string> str = new List<string>();StreamReader sr = new StreamReader(classer_path);string line;while ((line = sr.ReadLine()) != null){str.Add(line);}class_lables = str.ToArray();image_path = "test_img/1.png";pictureBox1.Image = new Bitmap(image_path);}private  void button2_Click(object sender, EventArgs e){if (image_path == ""){return;}textBox1.Text = "检测中,请稍等……";pictureBox2.Image = null;button2.Enabled = false;Application.DoEvents();image = new Mat(image_path);//图片缩放image = new Mat(image_path);int max_image_length = image.Cols > image.Rows ? image.Cols : image.Rows;Mat max_image = Mat.Zeros(new OpenCvSharp.Size(max_image_length, max_image_length), MatType.CV_8UC3);Rect roi = new Rect(0, 0, image.Cols, image.Rows);image.CopyTo(new Mat(max_image, roi));float[] result_array;float factor = (float)(max_image_length / 640.0);// 将图片转为RGB通道Mat image_rgb = new Mat();Cv2.CvtColor(max_image, image_rgb, ColorConversionCodes.BGR2RGB);Mat resize_image = new Mat();Cv2.Resize(image_rgb, resize_image, new OpenCvSharp.Size(640, 640));BN_image = CvDnn.BlobFromImage(resize_image, 1 / 255.0, new OpenCvSharp.Size(640, 640), new Scalar(0, 0, 0), true, false);//配置图片输入数据opencv_net.SetInput(BN_image);//模型推理,读取推理结果Mat[] outs = new Mat[1] { 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);int nout = outs[0].Size(2);if (outs[0].Dims > 2){outs[0] = outs[0].Reshape(0, num_proposal);}Mat result_data = new Mat(20, 8400, MatType.CV_32F);result_data = outs[0].T();List<Rect2d> position_boxes = new List<Rect2d>();List<int> class_ids = new List<int>();List<float> confidences = new List<float>();List<float> rotations = new List<float>();// Preprocessing output resultsfor (int i = 0; i < result_data.Rows; i++){Mat classes_scores = new Mat(result_data, new Rect(4, i, 15, 1));OpenCvSharp.Point max_classId_point, min_classId_point;double max_score, min_score;// Obtain the maximum value and its position in a set of dataCv2.MinMaxLoc(classes_scores, out min_score, out max_score,out min_classId_point, out max_classId_point);// Confidence level between 0 ~ 1// Obtain identification box informationif (max_score > 0.25){float cx = result_data.At<float>(i, 0);float cy = result_data.At<float>(i, 1);float ow = result_data.At<float>(i, 2);float oh = result_data.At<float>(i, 3);double x = (cx - 0.5 * ow) * factor;double y = (cy - 0.5 * oh) * factor;double width = ow * factor;double height = oh * factor;Rect2d box = new Rect2d();box.X = x;box.Y = y;box.Width = width;box.Height = height;position_boxes.Add(box);class_ids.Add(max_classId_point.X);confidences.Add((float)max_score);rotations.Add(result_data.At<float>(i, 19));}}// NMS int[] indexes = new int[position_boxes.Count];CvDnn.NMSBoxes(position_boxes, confidences, 0.25f, 0.7f, out indexes);List<RotatedRect> rotated_rects = new List<RotatedRect>();for (int i = 0; i < indexes.Length; i++){int index = indexes[i];float w = (float)position_boxes[index].Width;float h = (float)position_boxes[index].Height;float x = (float)position_boxes[index].X + w / 2;float y = (float)position_boxes[index].Y + h / 2;float r = rotations[index];float w_ = w > h ? w : h;float h_ = w > h ? h : w;r = (float)((w > h ? r : (float)(r + Math.PI / 2)) % Math.PI);RotatedRect rotate = new RotatedRect(new Point2f(x, y), new Size2f(w_, h_), (float)(r * 180.0 / Math.PI));rotated_rects.Add(rotate);}result_image = image.Clone();for (int i = 0; i < indexes.Length; i++){int index = indexes[i];Point2f[] points = rotated_rects[i].Points();for (int j = 0; j < 4; j++){Cv2.Line(result_image, (OpenCvSharp.Point)points[j], (OpenCvSharp.Point)points[(j + 1) % 4], new Scalar(0, 255, 0), 2);}Cv2.PutText(result_image, class_lables[class_ids[index]] + "-" + confidences[index].ToString("0.00"),(OpenCvSharp.Point)points[0], HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 0, 255), 2);}pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";button2.Enabled = true;}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.mzph.cn/news/706111.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一周学会Django5 Python Web开发-Django5二进制文件下载响应

锋哥原创的Python Web开发 Django5视频教程&#xff1a; 2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计25条视频&#xff0c;包括&#xff1a;2024版 Django5 Python we…

【Git教程】(三)提交详解 —— add、commit、status、stach命令的说明,提交散列值与历史,多次提交及忽略 ~

Git教程 提交详解 1️⃣ 访问权限与时间戳2️⃣ add命令与 commit 命令3️⃣ 提交散列值4️⃣ 提交历史5️⃣ 一种特别的提交查看方法6️⃣ 同一项目的多部不同历史6.1 部分输出&#xff1a;-n6.2 格式化输出&#xff1a;--format、--oneline6.3 统计修改信息&#xff1a;--st…

C++初阶 | [八] (下) vector 模拟实现

摘要&#xff1a;vector 模拟实现讲解&#xff08;附代码示例&#xff09;&#xff0c;隐藏的浅拷贝&#xff0c;迭代器失效 在进行 vector 的模拟实现之前&#xff0c;我们先粗略浏览一下 stl_vector.h 文件中的源码来确定模拟实现的大体框架。 这里提供一些粗略浏览源码的技巧…

go环境安装-基于vscode的Windows安装

1、vscode安装 官网链接&#xff1a;https://code.visualstudio.com/ 选择相应的版本&#xff0c;这里选择Windows下的 下载得到一个VSCodeUserSetUp-x64的可执行文件&#xff0c;双击执行&#xff0c;选择要安装的路径&#xff0c;下一步。 2、go语言安装 官网链接&#x…

【Unity自制手册】Unity—Camera相机跟随的方法大全

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

微信小程序的医院体检预约管理系统springboot+uniapp+python

本系统设计的目的是建立一个简化信息管理工作、便于操作的体检导引平台。共有以下四个模块&#xff1a; uni-app框架&#xff1a;使用Vue.js开发跨平台应用的前端框架&#xff0c;编写一套代码&#xff0c;可编译到Android、小程序等平台。 语言&#xff1a;pythonjavanode.js…

Sentinel 动态规则扩展

一、规则 Sentinel 的理念是开发者只需要关注资源的定义&#xff0c;当资源定义成功后可以动态增加各种流控降级规则。Sentinel 提供两种方式修改规则&#xff1a; 通过 API 直接修改 (loadRules)通过 DataSource 适配不同数据源修改 手动通过 API 修改比较直观&#xff0c;…

主机字节序与网络字节序

大端序和小端序 大端序&#xff08;Big Endian&#xff09;和小端序&#xff08;Little Endian&#xff09;是两种计算机存储数据的方式。 大端序指的是将数据的高位字节存储在内存的低地址处&#xff0c;而将低位字节存储在内存的高地址处。这类似于我们阅读多位数时从左往右…

迁移学习 领域自适应

迁移学习 什么是迁移学习 迁移学习是机器学习领域用于标记数据难获取这一基础问题的重要手段&#xff0c; 将训练好的内容应用到新的任务上被称为迁移学习。 由于这个过程发生在两个领域间&#xff0c;已有的知识和数据也就是被迁移的对象被称为源域&#xff0c;被赋予经验…

防火墙的内容安全

目录 1. 内容安全 1.1 IAE引擎 DPI---深度包检测技术 DFI---深度流检测技术 结论(优缺点)&#xff1a; 1.2 入侵防御&#xff08;检测&#xff09;(IPS) IPS的优势: 入侵检测的方法: 入侵检测的流程 签名 查看预定义签名的内容 新建自定义签名 入侵防御的检测…

热闹元宵进行中,如何利用VR全景展示民宿品牌形象?

错峰出游闹元宵&#xff0c;元宵节恰逢周末&#xff0c;而且还是春节假期返工之后的首个休息日&#xff0c;不少人都想通过短途度假来缓解“节后综合征”。两位数的特价机票、打折的各种酒店让你实现“旅行自由”&#xff0c;那么如何知道特价酒店服务好不好呢&#xff1f;先别…

对于大前端开发来说,转鸿蒙开发究竟是福还是祸?

从铺天盖地的市场消息来看&#xff0c;华为即将面世的鸿蒙NEXT系统已经势不可挡了 想必大家都已经迫不及待地想要进行尝试。 估计大家都有着同样的疑问&#xff1a; 会不会是下一个风口&#xff1f;转鸿蒙应用开发难吗&#xff1f; 会不会是下一个风口&#xff1f; 自从鸿蒙…

江科大stm32 定时器 TIM输出比较--学习笔记

这几天遇到输出比较相关的问题&#xff0c;于是来学习下TIM输出比较部分知识点&#xff01; 输出比较简介 CNT是计数器的值&#xff0c;CCR寄存器是捕获/ 比较寄存器 简单的讲&#xff0c;输出比较就是用来输出PWM波形。 PWM简介 占空比&#xff1a;高电平占一个周期的比例。…

搜索算法(算法竞赛、蓝桥杯)--双向BFS字串变换

1、B站视频链接&#xff1a;B19 双向BFS 字串变换_哔哩哔哩_bilibili 题目链接&#xff1a;[NOIP2002 提高组] 字串变换 - 洛谷 #include <iostream> #include <queue> #include <unordered_map> using namespace std;const int N7; int n; string A,B,a[N]…

opencascade c#例程解析

1.编译 将msvc.bat文件拖入vs2022的x64 native tools&#xff0c;即可 2.about.xaml <Windowxmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x"http://schemas.microsoft.com/winfx/2006/xaml"x:Class"IE_WPF_WinForms…

前后端项目-part03

文章目录 5.4.4 机构名称5.4.4.1 创建实体类Company5.4.4.2 创建实体类CompanyMapper5.4.4.3 创建实体类CompanyService5.4.4.4 创建实体类CompanyController5.4.4.5 后端测试5.4.4.6 修改basic.js5.4.4.7 修改course.vue5.4.4.8 测试5.4.5 课程标签5.4.5.1 效果5.4.5.2 修改co…

后台管理系统: 权限管理

权限管理 角色:一家企业而言&#xff1a;BOSS、运维、销售、程序员 权限:超级管理员&#xff08;BOSS&#xff09;&#xff0c;是有权利操作整个项目的所有的模块 test&#xff08;新媒体&#xff09;&#xff0c;只能首页、商品管理者一部分菜单数据 admin&#xff1a;…

ClickHouse 指南(三)最佳实践 -- 主键稀疏索引

在ClickHouse主索引的实用介绍 ClickHouse release 24.1, 2024-01-30 1、简介 在本指南中&#xff0c;我们将深入研究ClickHouse索引。我们将详细说明和讨论: ClickHouse中的索引与传统的关系数据库管理系统有何不同ClickHouse是如何构建和使用表的稀疏主索引的什么是在Clic…

Curator基本使用

文章目录 1. 基本操作1.1 建立连接1.2 创建结点1.3 查询结点查询数据查询子结点查看结点信息 1.4 修改结点普通修改带乐观锁的修改 1.5 删除删除单个结点删除带子结点的结点必须成功的删除带回调函数的删除 2. 监听器事件2.1 NodeCache单一结点连续监听2.2 PathChildrenCache监…

nginx平滑升级,信号使用,分割日志

信号 kill -l 看信号大全 nginx -h 中可以看到的信号较少 s signal : send signal to a master process: stop, quit, reopen, reload 可以使用man手册来查看详细的信号 如果没安装&#xff0c;去源码包里找到man文件 man 路径/nginx.8 不加路径打不开man帮助 st…