C# OpenVINO 图片旋转角度检测

目录

效果

项目

代码

下载 


效果

项目

代码

using OpenCvSharp;
using Sdcb.OpenVINO;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace C__OpenVINO_图片旋转角度检测
{
    public partial class Form1 : Form
    {
        Bitmap bmp;
        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string img = "";
        float rotateThreshold = 0.50f;
        InputShape defaultShape = new InputShape(3, 224, 224);
        string model_path;
        CompiledModel cm;
        InferRequest ir;

        StringBuilder sb = new StringBuilder();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            model_path = "models/inference.pdmodel";
            Model rawModel = OVCore.Shared.ReadModel(model_path);

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

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

            img = "1.jpg";
            bmp = new Bitmap(img);
            pictureBox1.Image = new Bitmap(img);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox1.Image = null;

            img = ofd.FileName;
            bmp = new Bitmap(img);
            pictureBox1.Image = new Bitmap(img);
            textBox1.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (bmp == null)
            {
                return;
            }

            var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
            Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);
            Cv2.Rotate(mat, mat, RotateFlags.Rotate90Clockwise);
            var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
            pictureBox1.Image = bitmap;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (bmp == null)
            {
                return;
            }

            var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
            Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);
            Cv2.Rotate(mat, mat, RotateFlags.Rotate180);
            var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
            pictureBox1.Image = bitmap;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (bmp == null)
            {
                return;
            }

            var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
            Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);
            Cv2.Rotate(mat, mat, RotateFlags.Rotate90Counterclockwise);
            var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
            pictureBox1.Image = bitmap;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (img == "") { return; }

            textBox1.Text = "";
            sb.Clear();

            Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(new Bitmap(pictureBox1.Image));
            Cv2.CvtColor(src, src, ColorConversionCodes.RGBA2RGB);//mat转三通道mat

            Stopwatch stopwatch = new Stopwatch();

            Mat resized = Common.ResizePadding(src, defaultShape);
            Mat normalized = Common.Normalize(resized);

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

            Tensor input_x = Tensor.FromArray(input_tensor_data, new Shape(1, 3, 224, 224));

            ir.Inputs[0] = input_x;

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

            ir.Run();

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

            Tensor output_0 = ir.Outputs[0];

            RotationDegree r = RotationDegree._0;

            float[] softmax = output_0.GetData<float>().ToArray();
            float max = softmax.Max();
            int maxIndex = Array.IndexOf(softmax, max);

            if (max > rotateThreshold)
            {
                r = (RotationDegree)maxIndex;
            }

            string result = r.ToString();

            result = result + " (" + max.ToString("P2")+")";

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

            sb.AppendLine("结果:" + result);
            sb.AppendLine();
            sb.AppendLine("Scores: [" + String.Join(", ", softmax) + "]");
            sb.AppendLine();
            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();

        }

    }

    public readonly struct InputShape
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="InputShape"/> struct.
        /// </summary>
        /// <param name="channel">The number of color channels in the input image.</param>
        /// <param name="width">The width of the input image in pixels.</param>
        /// <param name="height">The height of the input image in pixels.</param>
        public InputShape(int channel, int width, int height)
        {
            Channel = channel;
            Height = height;
            Width = width;
        }

        /// <summary>
        /// Gets the number of color channels in the input image.
        /// </summary>
        public int Channel { get; }

        /// <summary>
        /// Gets the height of the input image in pixels.
        /// </summary>
        public int Height { get; }

        /// <summary>
        /// Gets the width of the input image in pixels.
        /// </summary>
        public int Width { get; }
    }

    /// <summary>
    /// Enum representing the degrees of rotation.
    /// </summary>
    public enum RotationDegree
    {
        /// <summary>
        /// Represents the 0-degree rotation angle.
        /// </summary>
        _0,
        /// <summary>
        /// Represents the 90-degree rotation angle.
        /// </summary>
        _90,
        /// <summary>
        /// Represents the 180-degree rotation angle.
        /// </summary>
        _180,
        /// <summary>
        /// Represents the 270-degree rotation angle.
        /// </summary>
        _270,
    }
}

using OpenCvSharp;
using Sdcb.OpenVINO;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;namespace C__OpenVINO_图片旋转角度检测
{public partial class Form1 : Form{Bitmap bmp;string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";string img = "";float rotateThreshold = 0.50f;InputShape defaultShape = new InputShape(3, 224, 224);string model_path;CompiledModel cm;InferRequest ir;StringBuilder sb = new StringBuilder();public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){model_path = "models/inference.pdmodel";Model rawModel = OVCore.Shared.ReadModel(model_path);var ad = OVCore.Shared.AvailableDevices;Console.WriteLine("可用设备");foreach (var item in ad){Console.WriteLine(item);}cm = OVCore.Shared.CompileModel(rawModel, "CPU");ir = cm.CreateInferRequest();img = "1.jpg";bmp = new Bitmap(img);pictureBox1.Image = new Bitmap(img);}private void button1_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = fileFilter;if (ofd.ShowDialog() != DialogResult.OK) return;pictureBox1.Image = null;img = ofd.FileName;bmp = new Bitmap(img);pictureBox1.Image = new Bitmap(img);textBox1.Text = "";}private void button3_Click(object sender, EventArgs e){if (bmp == null){return;}var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);Cv2.Rotate(mat, mat, RotateFlags.Rotate90Clockwise);var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);pictureBox1.Image = bitmap;}private void button4_Click(object sender, EventArgs e){if (bmp == null){return;}var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);Cv2.Rotate(mat, mat, RotateFlags.Rotate180);var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);pictureBox1.Image = bitmap;}private void button5_Click(object sender, EventArgs e){if (bmp == null){return;}var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);Cv2.CvtColor(mat, mat, ColorConversionCodes.RGBA2RGB);Cv2.Rotate(mat, mat, RotateFlags.Rotate90Counterclockwise);var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);pictureBox1.Image = bitmap;}private void button2_Click(object sender, EventArgs e){if (img == "") { return; }textBox1.Text = "";sb.Clear();Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(new Bitmap(pictureBox1.Image));Cv2.CvtColor(src, src, ColorConversionCodes.RGBA2RGB);//mat转三通道matStopwatch stopwatch = new Stopwatch();Mat resized = Common.ResizePadding(src, defaultShape);Mat normalized = Common.Normalize(resized);float[] input_tensor_data = Common.ExtractMat(normalized);Tensor input_x = Tensor.FromArray(input_tensor_data, new Shape(1, 3, 224, 224));ir.Inputs[0] = input_x;double preprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();ir.Run();double inferTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();Tensor output_0 = ir.Outputs[0];RotationDegree r = RotationDegree._0;float[] softmax = output_0.GetData<float>().ToArray();float max = softmax.Max();int maxIndex = Array.IndexOf(softmax, max);if (max > rotateThreshold){r = (RotationDegree)maxIndex;}string result = r.ToString();result = result + " (" + max.ToString("P2")+")";double postprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Stop();double totalTime = preprocessTime + inferTime + postprocessTime;sb.AppendLine("结果:" + result);sb.AppendLine();sb.AppendLine("Scores: [" + String.Join(", ", softmax) + "]");sb.AppendLine();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();}}public readonly struct InputShape{/// <summary>/// Initializes a new instance of the <see cref="InputShape"/> struct./// </summary>/// <param name="channel">The number of color channels in the input image.</param>/// <param name="width">The width of the input image in pixels.</param>/// <param name="height">The height of the input image in pixels.</param>public InputShape(int channel, int width, int height){Channel = channel;Height = height;Width = width;}/// <summary>/// Gets the number of color channels in the input image./// </summary>public int Channel { get; }/// <summary>/// Gets the height of the input image in pixels./// </summary>public int Height { get; }/// <summary>/// Gets the width of the input image in pixels./// </summary>public int Width { get; }}/// <summary>/// Enum representing the degrees of rotation./// </summary>public enum RotationDegree{/// <summary>/// Represents the 0-degree rotation angle./// </summary>_0,/// <summary>/// Represents the 90-degree rotation angle./// </summary>_90,/// <summary>/// Represents the 180-degree rotation angle./// </summary>_180,/// <summary>/// Represents the 270-degree rotation angle./// </summary>_270,}
}

下载 

源码下载

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

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

相关文章

Avalonia学习(二十三)-大屏

弄一个大屏显示的界面例子&#xff0c;但是代码有点多&#xff0c;还有用户控件。 目前还有一点问题在解决&#xff0c;先看一下界面效果。 圆形控件 前端代码 <UserControl xmlns"https://github.com/avaloniaui"xmlns:x"http://schemas.microsoft.com/…

django admin 自定义界面时丢失左侧导航 nav_sidebar

只显示了自定义模板的内容&#xff0c;左侧导航没有显示出来。 原因&#xff1a;context 漏掉了&#xff0c;要补上。 # 错误写法&#xff08;左侧导航不显示&#xff09;def changelist_view(self, request, extra_contextNone):form CsvImportForm()payload {"form&qu…

【开源】JAVA+Vue.js实现高校实验室管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 实验室类型模块2.2 实验室模块2.3 实验管理模块2.4 实验设备模块2.5 实验订单模块 三、系统设计3.1 用例设计3.2 数据库设计 四、系统展示五、样例代码5.1 查询实验室设备5.2 实验放号5.3 实验预定 六、免责说明 一、摘…

Java图形化界面编程—— 基本组件和对话框 笔记

2.5 AWT中常用组件 2.5.1 基本组件 组件名功能ButtonButtonCanvas用于绘图的画布Checkbox复选框组件&#xff08;也可当做单选框组件使用&#xff09;CheckboxGroup选项组&#xff0c;用于将多个Checkbox 组件组合成一组&#xff0c; 一组 Checkbox 组件将只有一个可以 被选中…

MATLAB环境下基于同态滤波方法的医学图像增强

目前图像增强技术主要分为基于空间域和基于频率域两大方面&#xff0c;基于空间域图像增强的方法包括了直方图均衡化方法和 Retinex 方法等&#xff0c;基于频率域的方法包括同态滤波方法。其中直方图均衡化方法只是根据图像的灰度概率分布函数进行简单的全局拉伸&#xff0c;没…

Qt PCL学习(二):点云读取与保存

注意事项 版本一览&#xff1a;Qt 5.15.2 PCL 1.12.1 VTK 9.1.0前置内容&#xff1a;Qt PCL学习&#xff08;一&#xff09;&#xff1a;环境搭建 0. 效果演示 1. pcl_open_save.pro QT core guigreaterThan(QT_MAJOR_VERSION, 4): QT widgets// 添加下行代码&#…

MQTT 服务器(emqx)搭建及使用

推荐阅读&#xff1a; MQTT 服务器(emqx)搭建及使用 - 哔哩哔哩 (bilibili.com) 一、EMQX 服务器搭建 1、下载EMQX https://www.emqx.com/zh/try?productbroker 官方中文手册&#xff1a; EMQX Docs 2、安装使用 1、该软件为绿色免安装版本&#xff0c;解压缩后即安装完…

C++算法之双指针、BFS和图论

一、双指针 1.AcWing 1238.日志统计 分析思路 前一区间和后一区间有大部分是存在重复的 我们要做的就是利用这部分 来缩短我们查询的时间 并且在使用双指针时要注意对所有的博客记录按时间从小到大先排好顺序 因为在有序的区间内才能使用双指针记录两个区间相差 相当于把一个…

React + SpringBoot + Minio实现文件的预览

思路&#xff1a;后端提供接口&#xff0c;从minio获取文件的预览链接&#xff0c;返回给前端&#xff0c;前端使用组件进行渲染展示 这里我从minio获取文件预览地址用到了一个最近刚开源的项目&#xff0c;挺好用的&#xff0c;大伙可以试试&#xff0c;用法也很简单 官网&am…

PlateUML绘制UML图教程

UML&#xff08;Unified Modeling Language&#xff09;是一种通用的建模语言&#xff0c;广泛用于软件开发中对系统进行可视化建模。PlantUML是一款强大的工具&#xff0c;通过简单的文本描述&#xff0c;能够生成UML图&#xff0c;包括类图、时序图、用例图等。PlantUML是一款…

ubuntu原始套接字多线程负载均衡

原始套接字多线程负载均衡是一种在网络编程中常见的技术&#xff0c;特别是在高性能网络应用或网络安全工具中。这种技术允许应用程序在多个线程之间有效地分配和处理网络流量&#xff0c;提高系统的并发性能。以下是关于原始套接字多线程负载均衡技术的一些介绍&#xff1a; …

LEETCODE 164. 最大间距

class Solution { public:int maximumGap(vector<int>& nums) {//基数排序if(nums.size()<2){return 0;}int maxnums[0];for(int i1;i<nums.size();i){if(max<nums[i]){maxnums[i];}}int radix1;vector<int> tmp(nums.size());while(max>0){// int…

2024-02-08 Unity 编辑器开发之编辑器拓展1 —— 自定义菜单栏与窗口

文章目录 1 特殊文件夹 Editor2 在 Unity 菜单栏中添加自定义页签3 在 Hierarchy 窗口中添加自定义页签4 在 Project 窗口中添加自定义页签5 在菜单栏的 Component 菜单添加脚本6 在 Inspector 为脚本右键添加菜单7 加入快捷键8 小结 1 特殊文件夹 Editor ​ Editor 文件夹是 …

【RabbitMQ(一)】:基本介绍 | 配置安装与快速入门

应该是新年前最后一篇博客了&#xff0c;明天浅浅休息一下&#xff0c;提前祝大家新年快乐捏&#xff01;&#x1f60a;&#x1f60a;&#x1f60a; 01. 基础理解 1.1 同步调用和异步调用 &#x1f449; 同步调用 的时候调用者会 阻塞 等待被调用函数或方法执行完成&#xff…

【CSS】什么是BFC?BFC有什么作用?

【CSS】什么是BFC&#xff1f;BFC有什么作用&#xff1f; 一、BFC概念二、触发BFC三、BFC特性即应用场景1、解决margin塌陷的问题2、避免外边距margin重叠&#xff08;margin合并&#xff09;3、清除浮动4、阻止元素被浮动元素覆盖 一、BFC概念 BFC(block formatting context)…

华为第二批难题五:AI技术提升六面体网格生成自动化问题

有CAE开发商问及OCCT几何内核的网格方面的技术问题。其实&#xff0c;OCCT几何内核的现有网格生成能力比较弱。 HybridOctree_Hex的源代码&#xff0c;还没有仔细去学习。 “HybridOctree_Hex”的开发者说&#xff1a;六面体网格主要是用在数值模拟领域的&#xff0c;比如汽车…

leetcode(哈希表)49.字母异位词分组(C++详细解释)DAY5

文章目录 1.题目示例提示 2.解答思路3.实现代码结果 4.总结 1.题目 给你一个字符串数组&#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 示例 示例 1: 输入: strs [“eat”, “tea”…

PCA与梯度上升法

PAC 主成分分析&#xff08;Principal Component Analysis&#xff09; 一个非监督的机器学习算法主要用于数据的降维通过降维&#xff0c;可以发现更便于人类理解的特征其他应用&#xff1a;可视化&#xff1b;去噪 如何找到这个让样本间间距最大的轴&#xff1f; 如何定义样…

ansible shell模块 可以用来使用shell 命令 支持管道符 shell 模块和 command 模块的区别

这里写目录标题 说明shell模块用法shell 模块和 command 模块的区别 说明 shell模块可以在远程主机上调用shell解释器运行命令&#xff0c;支持shell的各种功能&#xff0c;例如管道等 shell模块用法 ansible slave -m shell -a cat /etc/passwd | grep root # 可以使用管道…

Window环境下使用go编译grpc最新教程

网上的grpc教程都或多或少有些老或者有些问题&#xff0c;导致最后执行生成文件时会报很多错。这里给出个人实践出可执行的编译命令与碰到的报错与解决方法。&#xff08;ps:本文代码按照煎鱼的教程编写&#xff1a;4.2 gRPC Client and Server - 跟煎鱼学 Go (gitbook.io)&…