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,一经查实,立即删除!

相关文章

[C++]C++实现本地TCP通讯的示例代码

这篇文章主要为大家详细介绍了C如何利用TCP技术,实现本地ROS1和ROS2的通讯,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下 概要服务端代码 头文件源代码客户端代码 概要 利用TCP技术&#xff0c;实现本地ROS1和ROS2的通讯。 服务端代码 头文件 #include &…

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

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

使用 BroadcastChannel 实现跨标签页通信及页面跳

引言 在现代Web应用程序开发中&#xff0c;尤其是基于Vue.js构建的单页面应用&#xff08;SPA&#xff09;&#xff0c;跨标签页的数据同步与页面控制是一项常见需求。本文将探讨如何巧妙地结合HTML5的BroadcastChannel API和Vue Router来实现跨标签页通信&#xff0c;并在此基…

【无标题】npm使用淘宝镜像安装luckyExcel不行

问题描述&#xff1a; npm使用淘宝镜像安装luckyExcel 一直停留在still…下载不下来 原因分析&#xff1a; 淘宝镜像已从registry.npm.taobao.org 改为https://registry.npmmirror.com 切换镜像后就能正常下载luckyExcel 解决方案&#xff1a; // 1. 清空缓存 npm cache cle…

【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…

《Sora视频生成技术探秘:从压缩到生成,语言理解引领创新》

Sora背后的技术原理&#xff1a;深度探索Video Compression Network与Transformer模型在视频生成中的应用 摘要 随着人工智能技术的不断发展和创新&#xff0c;视频生成技术在许多领域中都得到了广泛的应用。作为一种前沿的视频生成技术&#xff0c;Sora凭借其高效的视频处理…

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…

搭建freqtrade量化交易机器人

本文采用python量化机器人框架 freqtrade 开始操作&#xff01; freqtrade官方文档 官方文档内容过多&#xff0c;请先跟随本文入门阅读&#xff0c;后续深入学习可参考官方文档&#xff5e; 1. 准备云服务器 docker 环境 这里以云服务器选择 ubuntu 系统开始&#xff0c;先…

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

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

VBA来创建一个新的 Excel 文件

前言 其他的宏指令执行的前提条件是创建一个新的xlsx文件,来存储操作完成后的结果.否则会因为缺少操作对象,出现1004错误. Sub CreateNewFile()Dim xlApp As ObjectDim xlWB As Object 创建一个新的 Excel 应用程序对象Set xlApp CreateObject("Excel.Application")…

docker学习快速入门

目录 Linux下安装docker配置阿里云镜像加速docker命令部署安装Tomcat、ES容器数据卷DockerFiledocker网络制作tomcat镜像Redis集群部署SpringBoot微服务打包docker镜像拓展 什么是Docker Docker是内核级别的虚拟化&#xff0c;可以在一个物理机上可以运行很多的容器实例。服务…

Unity使用PlayableAPI 动态播放动画

1.初始化animator&#xff0c;创建Playable图&#xff0c;创建动画Playable private void InitAnimator(GameObject headGo) {if (headGo){_headAnimator headGo.GetComponent<Animator>();if (_headAnimator){_headAnimator.cullingMode AnimatorCullingMode.AlwaysA…

【面试】找工作历程

简单介绍一下自己&#xff1a;本科双非一本&#xff0c;22年毕业&#xff0c;工作一段时间到24年1月份辞职&#xff0c;怎么说实习加正式&#xff0c;工作了大概两年&#xff0c;年后准备换工作&#xff0c;目前IP上海。 2024.2.26 第一天正式投简历投了boss的上限&#xff0c;…

Sentinel 动态规则扩展

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

主机字节序与网络字节序

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

YOLOv6代码解读[05] yolov6/core/engine.py文件解读

#!/usr/bin/env python3 # -*- coding:utf-8 -*- from ast import Pass import os import os.path as osp import time from copy import deepcopy from tqdm import tqdm import cv2 import numpy as np import mathimport torch from torch.cuda

新版vscode remote ssh不兼容老系统 (waiting for server log)

参考知乎-萌萌哒赫萝​ 最近vscode发布了1.86版本&#xff0c;该版本中&#xff0c;更新了对glibc的要求( ≥ \geq ≥ 2.28)&#xff0c;导致各种旧版本的linux发行版&#xff08;如centos 7&#xff09;都无法用remote-ssh来连接了&#xff0c;会一直控制台报错waiting for s…

迁移学习 领域自适应

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