C#OpenCvSharp YOLO v3 Demo

目录

效果

项目

代码

下载 


效果

项目

代码

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 System.IO;
using OpenCvSharp.Dnn;
using System.Diagnostics;
using OpenCvSharp.Extensions;namespace OpenCvSharp_YoloV3
{public partial class frmMain : Form{public frmMain(){InitializeComponent();}//random assign color to each labelprivate static readonly Scalar[] Colors = Enumerable.Repeat(false, 80).Select(x => Scalar.RandomColor()).ToArray();//get labels from coco.namesprivate static readonly string[] Labels = File.ReadAllLines("coco.names").ToArray();string cfg = "yolov3.cfg";string model = "yolov3.weights";const float threshold = 0.5f;       //for confidence const float nmsThreshold = 0.3f;    //threshold for nmsNet net;private void frmMain_Load(object sender, EventArgs e){//load model and config, if you got error: "separator_index < line.size()", check your cfg file, must be something wrong.net = CvDnn.ReadNetFromDarknet(cfg, model);#region set preferablenet.SetPreferableBackend(3);/*0:DNN_BACKEND_DEFAULT 1:DNN_BACKEND_HALIDE 2:DNN_BACKEND_INFERENCE_ENGINE3:DNN_BACKEND_OPENCV */net.SetPreferableTarget(0);/*0:DNN_TARGET_CPU 1:DNN_TARGET_OPENCL2:DNN_TARGET_OPENCL_FP163:DNN_TARGET_MYRIAD 4:DNN_TARGET_FPGA */#endregion}private void button1_Click(object sender, EventArgs e){if (bmp == null) return;//get imagevar org = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);//bitmap转matCv2.CvtColor(org, org, ColorConversionCodes.RGBA2RGB);//mat转三通道mat//setting blob, size can be:320/416/608//opencv blob setting can check here https://github.com/opencv/opencv/tree/master/samples/dnn#object-detectionvar blob = CvDnn.BlobFromImage(org, 1.0 / 255, new OpenCvSharp.Size(416, 416), new Scalar(), true, false);//input datanet.SetInput(blob);//get output layer namevar outNames = net.GetUnconnectedOutLayersNames();//create mats for output layervar outs = outNames.Select(_ => new Mat()).ToArray();#region forward modelStopwatch sw = new Stopwatch();sw.Start();net.Forward(outs, outNames);sw.Stop();Console.WriteLine("Runtime:{" + sw.ElapsedMilliseconds + "} ms");#endregion//get result from all outputGetResult(outs, org, threshold, nmsThreshold);Bitmap Bitmap1 = BitmapConverter.ToBitmap(org);pictureBox2.Image = Bitmap1;}/// <summary>/// Get result form all output/// </summary>/// <param name="output"></param>/// <param name="image"></param>/// <param name="threshold"></param>/// <param name="nmsThreshold">threshold for nms</param>/// <param name="nms">Enable Non-maximum suppression or not</param>private static void GetResult(IEnumerable<Mat> output, Mat image, float threshold, float nmsThreshold, bool nms = true){//for nmsvar classIds = new List<int>();var confidences = new List<float>();var probabilities = new List<float>();var boxes = new List<Rect2d>();var w = image.Width;var h = image.Height;/*YOLO3 COCO trainval output0 1 : center                    2 3 : w/h4 : confidence                  5 ~ 84 : class probability */const int prefix = 5;   //skip 0~4foreach (var prob in output){for (var i = 0; i < prob.Rows; i++){var confidence = prob.At<float>(i, 4);if (confidence > threshold){//get classes probabilityOpenCvSharp.Point max;OpenCvSharp.Point minLoc;Cv2.MinMaxLoc(prob.Row[i].ColRange(prefix, prob.Cols), out minLoc, out  max);var classes = max.X;var probability = prob.At<float>(i, classes + prefix);if (probability > threshold) //more accuracy, you can cancel it{//get center and width/heightvar centerX = prob.At<float>(i, 0) * w;var centerY = prob.At<float>(i, 1) * h;var width = prob.At<float>(i, 2) * w;var height = prob.At<float>(i, 3) * h;if (!nms){// draw result (if don't use NMSBoxes)Draw(image, classes, confidence, probability, centerX, centerY, width, height);continue;}//put data to list for NMSBoxesclassIds.Add(classes);confidences.Add(confidence);probabilities.Add(probability);boxes.Add(new Rect2d(centerX, centerY, width, height));}}}}if (!nms) return;//using non-maximum suppression to reduce overlapping low confidence boxint[] indices;CvDnn.NMSBoxes(boxes, confidences, threshold, nmsThreshold, out indices);Console.WriteLine("NMSBoxes drop {" + (confidences.Count - indices.Length) + "} overlapping result.");foreach (var i in indices){var box = boxes[i];Draw(image, classIds[i], confidences[i], probabilities[i], box.X, box.Y, box.Width, box.Height);}}/// <summary>/// Draw result to image/// </summary>/// <param name="image"></param>/// <param name="classes"></param>/// <param name="confidence"></param>/// <param name="probability"></param>/// <param name="centerX"></param>/// <param name="centerY"></param>/// <param name="width"></param>/// <param name="height"></param>private static void Draw(Mat image, int classes, float confidence, float probability, double centerX, double centerY, double width, double height){//label formatingvar label = Labels[classes] + " " + (probability * 100).ToString("0.00") + "%";Console.WriteLine("confidence " + (confidence * 100).ToString("0.00") + "%  " + label);var x1 = (centerX - width / 2) < 0 ? 0 : centerX - width / 2; //avoid left side over edge//draw resultimage.Rectangle(new OpenCvSharp.Point(x1, centerY - height / 2), new OpenCvSharp.Point(centerX + width / 2, centerY + height / 2), Colors[classes], 2);int baseline;var textSize = Cv2.GetTextSize(label, HersheyFonts.HersheyTriplex, 0.5, 1, out  baseline);Cv2.Rectangle(image, new Rect(new OpenCvSharp.Point(x1, centerY - height / 2 - textSize.Height - baseline),new OpenCvSharp.Size(textSize.Width, textSize.Height + baseline)), Colors[classes], Cv2.FILLED);var textColor = Cv2.Mean(Colors[classes]).Val0 < 70 ? Scalar.White : Scalar.Black;Cv2.PutText(image, label, new OpenCvSharp.Point(x1, centerY - height / 2 - baseline), HersheyFonts.HersheyTriplex, 0.5, textColor);}private string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";Bitmap bmp;private void button2_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = fileFilter;if (ofd.ShowDialog() != DialogResult.OK) return;var imagebyte = File.ReadAllBytes(ofd.FileName);bmp = new Bitmap(new MemoryStream(imagebyte));pictureBox1.Image = bmp;}}
}

下载 

Demo下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/578152.html

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

相关文章

SiameseRPN原理详解(个人学习笔记)

参考资源&#xff1a; 视觉目标跟踪SiamRPNSiameseRPN详解CVPR2018视觉目标跟踪之 SiameseRPN 目录&#xff09; 1. 模型架构1.1 Siamese Network1.2 RPN 2. 模型训练2.1 损失函数2.2 端到端训练2.3 正负样本选择 3. 跟踪阶段总结 SiamRPN是在SiamFC的基础上进行改进而得到的一…

产品推荐 | 基于华为海思ARM+Xilinx FPGA双核的8路SDI高清视频图像处理平台

一、板卡概述 PCIE703 是我司自主研制的一款基于 PCIE 总线架构的高性能综 合视频图像处理平台&#xff0c;该平台采用 Xilinx 的高性能 Kintex UltraScale 系列 FPGA 加上华为海思的高性能视频处理器来实现。 华为海思的 HI3531DV200 是一款集成了 ARM A53 四核处理 器性能强…

003 高并发内存池_整体框架设计

​&#x1f308;个人主页&#xff1a;Fan_558 &#x1f525; 系列专栏&#xff1a;高并发内存池 &#x1f339;关注我&#x1f4aa;&#x1f3fb;带你学更多知识 文章目录 前言一、ThreadCache整体框架设计二、CentralCache整体框架设计三、PageCache整体框架设计 小结 前言 在…

个人简历主页搭建系列-05:部署至 Github

前面只是本地成功部署网站&#xff0c;网站运行的时候我们可以通过 localhost: port 进行访问。不过其他人是无法访问我们本机部署的网站的。 接下来通过 Github Pages 服务把网站部署上去&#xff0c;这样大家都可以通过特定域名访问我的网站了&#xff01; 创建要部署的仓库…

U盘文件突然消失?原因与恢复策略全解析

一、遭遇不测&#xff1a;U盘文件突然消失 在日常生活和工作中&#xff0c;U盘扮演着不可或缺的角色&#xff0c;它小巧便捷&#xff0c;能够随时随地存储和传输文件。然而&#xff0c;有时我们会遭遇一个令人头疼的问题&#xff1a;U盘中的文件突然消失。这种突如其来的变故往…

Web漏洞-深入WAF注入绕过

目录 简要其他测试绕过 方式一:白名单&#xff08;实战中意义不大&#xff09; 方式二:静态资源 方式三: url白名单 方式四:爬虫白名单 #阿里云盾防SQL注入简要分析 #安全狗云盾SQL注入插件脚本编写 在攻防实战中&#xff0c;往往需要掌握一些特性&#xff0c;比如服务…

Linux CPU 占用率 100% 排查

Linux CPU 占用率 100% 排查 总体来说分为五个步骤 top 命令定位应用进程 pidtop -Hp [pid] 定位应用进程对应的线程 tidprintf “%x\n” [tid] 将 tid 转换为十六进制jstack [pid] | grep -A 10 [tid 的十六进制] 打印堆栈信息根据堆栈信息分析问题 以下为实战例子 写一段…

SQLBolt,一个练习SQL的宝藏网站

知乎上有人问学SQL有什么好的网站&#xff0c;这可太多了。 我之前学习SQL买了本SQL学习指南&#xff0c;把语法从头到尾看了个遍&#xff0c;但仅仅是心里有数的程度&#xff0c;后来进公司大量的写代码跑数&#xff0c;才算真真摸透了SQL&#xff0c;知道怎么调优才能最大化…

Autosar-Mcal配置详解(免费)-MCU

3.6.1创建、配置RAM 1)配置MCU通用配置项 MCU的通用配置项可参考以下配置&#xff1a; 各配置项的说明如下&#xff1a; Wake Up Factor Clear Isr: 是否在唤醒的中断服务函数中清除Wakeup Factor Wake Up Factors Clear Centralised: 是否在shutdown前集中集中清除Wakeu…

OpenHarmony动效示例-如何使用animateTo实现显式动画。

介绍 利用ArkUI组件不仅可以实现局部属性变化产生的属性动画&#xff0c;也可以实现父组件属性变化引起子组件产生过渡效果式的全局动画即显式动画。效果如图所示&#xff1a; 相关概念 显式动画&#xff1a;提供全局animateTo显式动画接口来指定有闭包代码导致的状态变化插入…

HarmonyOS 应用开发之启动/停止本地PageAbility

启动本地PageAbility PageAbility相关的能力通过featureAbility提供&#xff0c;启动本地Ability通过featureAbility中的startAbility接口实现。 表1 featureAbility接口说明 接口名接口描述startAbility(parameter: StartAbilityParameter)启动Ability。startAbilityForRes…