C# OpenVINO 直接读取百度Paddle模型实现物体检测( yolov3_darknet)

news/2024/7/9 23:44:02 标签: openvino, paddle, YOLO, 目标检测, 人工智能, c#, 机器学习

目录

效果

项目

代码

下载


C# OpenVINO 直接读取百度Paddle模型实现物体检测( yolov3_darknet)

效果

项目

代码

using OpenCvSharp;
using Sdcb.OpenVINO;
using Sdcb.OpenVINO.Natives;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;

namespace OpenVINO_Det_物体检测
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";
        string startupPath;
        string model_path;
        Mat src;
        string[] dicts;

        StringBuilder sb = new StringBuilder();

        float confidence = 0.75f;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;
            pictureBox1.Image = null;
            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);
            textBox1.Text = "";
            src = new Mat(image_path);
            pictureBox2.Image = null;
        }

        unsafe private void button2_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                return;
            }

            pictureBox2.Image = null;
            textBox1.Text = "";
            sb.Clear();

            src = new Mat(image_path);
            Mat result_image = src.Clone();

            model_path = "yolov3_darknet/model.pdmodel";
            Model rawModel = OVCore.Shared.ReadModel(model_path);

            int inpHeight = 608;
            int inpWidth = 608;

            var ad = OVCore.Shared.AvailableDevices;
            Console.WriteLine("可用设备");
            foreach (var item in ad)
            {
                Console.WriteLine(item);
            }

            CompiledModel cm = OVCore.Shared.CompileModel(rawModel, "CPU");
            InferRequest ir = cm.CreateInferRequest();

            Stopwatch stopwatch = new Stopwatch();

            Shape inputShape = new Shape(1, 608, 608);
            Size2f sizeRatio = new Size2f(1f * src.Width / inputShape[2], 1f * src.Height / inputShape[1]);
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);

            Point2f scaleRate = new Point2f(1f * inpWidth / src.Width, 1f * inpHeight / src.Height);

            Cv2.Resize(src, src, new OpenCvSharp.Size(), scaleRate.X, scaleRate.Y);

            Common.Normalize(src);

            float[] input_tensor_data = Common.ExtractMat(src);

            /*
             scale_factor   1,2
             image          1,3,608,608
             im_shape       1,2 
             */
            Tensor input_scale_factor = Tensor.FromArray(new float[] { scaleRate.Y, scaleRate.X }, new Shape(1, 2));
            Tensor input_image = Tensor.FromArray(input_tensor_data, new Shape(1, 3, 608, 608));
            Tensor input_im_shape = Tensor.FromArray(new float[] { 608, 608 }, new Shape(1, 2));

            ir.Inputs[0] = input_scale_factor;
            ir.Inputs[1] = input_image;
            ir.Inputs[2] = input_im_shape;

            double preprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();

            ir.Run();

            double inferTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();

            Tensor output_0 = ir.Outputs[0];

            int num = (int)output_0.Shape.Dimensions[0];

            float[] output_0_array = output_0.GetData<float>().ToArray();

            for (int j = 0; j < num; j++)
            {
                int num12 = (int)Math.Round(output_0_array[j * 6]);
                float score = output_0_array[1 + j * 6];

                if (score > this.confidence)
                {
                    int num13 = (int)(output_0_array[2 + j * 6]);
                    int num14 = (int)(output_0_array[3 + j * 6]);
                    int num15 = (int)(output_0_array[4 + j * 6]);
                    int num16 = (int)(output_0_array[5 + j * 6]);

                    string ClassName = dicts[num12];
                    Rect r = Rect.FromLTRB(num13, num14, num15, num16);
                    sb.AppendLine($"{ClassName}:{score:P0}");
                    Cv2.PutText(result_image, $"{ClassName}:{score:P0}", new OpenCvSharp.Point(r.TopLeft.X, r.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                    Cv2.Rectangle(result_image, r, Scalar.Red, thickness: 2);
                }
            }

            double postprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Stop();
            double totalTime = preprocessTime + inferTime + postprocessTime;

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());

            sb.AppendLine($"Preprocess: {preprocessTime:F2}ms");
            sb.AppendLine($"Infer: {inferTime:F2}ms");
            sb.AppendLine($"Postprocess: {postprocessTime:F2}ms");
            sb.AppendLine($"Total: {totalTime:F2}ms");

            textBox1.Text = sb.ToString();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = Application.StartupPath;

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

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

using OpenCvSharp;
using Sdcb.OpenVINO;
using Sdcb.OpenVINO.Natives;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;

namespace OpenVINO_Det_物体检测
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";
        string startupPath;
        string model_path;
        Mat src;
        string[] dicts;

        StringBuilder sb = new StringBuilder();

        float confidence = 0.75f;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;
            pictureBox1.Image = null;
            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);
            textBox1.Text = "";
            src = new Mat(image_path);
            pictureBox2.Image = null;
        }

        unsafe private void button2_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                return;
            }

            pictureBox2.Image = null;
            textBox1.Text = "";
            sb.Clear();

            src = new Mat(image_path);
            Mat result_image = src.Clone();

            model_path = "yolov3_darknet/model.pdmodel";
            Model rawModel = OVCore.Shared.ReadModel(model_path);

            int inpHeight = 608;
            int inpWidth = 608;

            var ad = OVCore.Shared.AvailableDevices;
            Console.WriteLine("可用设备");
            foreach (var item in ad)
            {
                Console.WriteLine(item);
            }

            CompiledModel cm = OVCore.Shared.CompileModel(rawModel, "CPU");
            InferRequest ir = cm.CreateInferRequest();

            Stopwatch stopwatch = new Stopwatch();

            Shape inputShape = new Shape(1, 608, 608);
            Size2f sizeRatio = new Size2f(1f * src.Width / inputShape[2], 1f * src.Height / inputShape[1]);
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);

            Point2f scaleRate = new Point2f(1f * inpWidth / src.Width, 1f * inpHeight / src.Height);

            Cv2.Resize(src, src, new OpenCvSharp.Size(), scaleRate.X, scaleRate.Y);

            Common.Normalize(src);

            float[] input_tensor_data = Common.ExtractMat(src);

            /*
             scale_factor   1,2
             image          1,3,608,608
             im_shape       1,2 
             */
            Tensor input_scale_factor = Tensor.FromArray(new float[] { scaleRate.Y, scaleRate.X }, new Shape(1, 2));
            Tensor input_image = Tensor.FromArray(input_tensor_data, new Shape(1, 3, 608, 608));
            Tensor input_im_shape = Tensor.FromArray(new float[] { 608, 608 }, new Shape(1, 2));

            ir.Inputs[0] = input_scale_factor;
            ir.Inputs[1] = input_image;
            ir.Inputs[2] = input_im_shape;

            double preprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();

            ir.Run();

            double inferTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Restart();

            Tensor output_0 = ir.Outputs[0];

            int num = (int)output_0.Shape.Dimensions[0];

            float[] output_0_array = output_0.GetData<float>().ToArray();

            for (int j = 0; j < num; j++)
            {
                int num12 = (int)Math.Round(output_0_array[j * 6]);
                float score = output_0_array[1 + j * 6];

                if (score > this.confidence)
                {
                    int num13 = (int)(output_0_array[2 + j * 6]);
                    int num14 = (int)(output_0_array[3 + j * 6]);
                    int num15 = (int)(output_0_array[4 + j * 6]);
                    int num16 = (int)(output_0_array[5 + j * 6]);

                    string ClassName = dicts[num12];
                    Rect r = Rect.FromLTRB(num13, num14, num15, num16);
                    sb.AppendLine($"{ClassName}:{score:P0}");
                    Cv2.PutText(result_image, $"{ClassName}:{score:P0}", new OpenCvSharp.Point(r.TopLeft.X, r.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                    Cv2.Rectangle(result_image, r, Scalar.Red, thickness: 2);
                }
            }

            double postprocessTime = stopwatch.Elapsed.TotalMilliseconds;
            stopwatch.Stop();
            double totalTime = preprocessTime + inferTime + postprocessTime;

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());

            sb.AppendLine($"Preprocess: {preprocessTime:F2}ms");
            sb.AppendLine($"Infer: {inferTime:F2}ms");
            sb.AppendLine($"Postprocess: {postprocessTime:F2}ms");
            sb.AppendLine($"Total: {totalTime:F2}ms");

            textBox1.Text = sb.ToString();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startupPath = Application.StartupPath;

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

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

下载

源码下载


http://www.niftyadmin.cn/n/5236496.html

相关文章

WT2605C与WT2003HX系列语音芯片:高品质白噪音音乐播放的优选解决方案

在现今的电子产品市场中&#xff0c;音质与用户体验的重要性日益凸显。作为一种能够提供舒适、宁静环境的音频&#xff0c;白噪音音乐在健康、家居、放松等领域中受到了广泛的关注。为了满足对于高品质白噪音音乐播放的需求&#xff0c;唯创知音推出了WT2605C与WT2003HX系列语音…

排序算法介绍(三)选择排序

0. 简介 选择排序&#xff08;Selection Sort&#xff09;是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小&#xff08;或最大&#xff09;的一个元素&#xff0c;存放在序列的起始位置&#xff0c;直到全部待排序的数据元素排完。选择排序是不稳…

西北大学计算机844考研-最后20天复习重点

西北大学计算机844考研-最后20天复习重点 ​ 我做844辅导超过400小时&#xff0c;人数超过20余人&#xff0c; 现在是2023年12月03日晚上22:33&#xff0c;这篇文章旨在帮助844众多考研学子在最后20天稳住心态&#xff0c;科学备考&#xff0c;争取获得专业课高分&#xff0c;…

【LeetCode热题100】【哈希】最长连续序列

据说是字节跳动二面的原题&#xff0c;这题面试要是让我当场手撕&#xff0c;我直接当场去世T_T 给定一个未排序的整数数组 nums &#xff0c;找出数字连续的最长序列&#xff08;不要求序列元素在原数组中连续&#xff09;的长度。 请你设计并实现时间复杂度为 O(n) 的算法解…

LLM大语言模型(一):ChatGLM3-6B试用

前言 LLM大语言模型工程化&#xff0c;在本地搭建一套开源的LLM&#xff0c;方便后续的Agent等特性的研究。 本机环境 CPU&#xff1a;AMD Ryzen 5 3600X 6-Core Processor Mem&#xff1a;32GB GPU&#xff1a;RTX 4060Ti 16G ChatGLM3代码库下载 # 下载代码库 ​git c…

2023-12-03 C语言最小二乘法备忘

点击 <C 语言编程核心突破> 快速C语言入门 C语言最小二乘法备忘 前言一、数学公式二、代码总结 前言 要解决问题: 最小二乘法实现线性回归的C语言实现, 这个数学公式转为C语言. 一、数学公式 设有 n n n 组数据 ( x 1 , y 1 ) , ( x 2 , y 2 ) , ⋯ , ( x n , y n ) …

【异常】捕获线程池执行任务时产生的异常

前言&#xff1a; 在编写程序时&#xff0c;我们为了充分利用多核CPU、加快接口响应速度&#xff0c;通常会使用线程池来处理请求&#xff0c;但线程池执行任务过程中难免会出现异常&#xff0c;导致请求失败。那如果我们想在任务发生异常后捕获异常&#xff0c;并做一些”善后…

单细胞个性化细胞注释

关于单细胞中级的课程内容&#xff0c;前面已经有了三次直播。欢迎回看&#xff5e; 单细胞直播一理解seurat数据结构与pbmc处理流程 单细胞直播二从GSE104154中理解seurat结构 单细胞直播三seurat数据结构与数据可视化 本期主要内容 本期指哪打哪&#xff0c;自己选定细胞&…