C# OpenVINO 图片旋转角度检测

目录

效果

项目

代码

下载 


效果

C# OpenVINO 图片旋转角度检测_第1张图片

项目

C# OpenVINO 图片旋转角度检测_第2张图片

代码

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().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
    {
        ///


        /// Initializes a new instance of the struct.
        ///

        /// The number of color channels in the input image.
        /// The width of the input image in pixels.
        /// The height of the input image in pixels.
        public InputShape(int channel, int width, int height)
        {
            Channel = channel;
            Height = height;
            Width = width;
        }

        ///


        /// Gets the number of color channels in the input image.
        ///

        public int Channel { get; }

        ///


        /// Gets the height of the input image in pixels.
        ///

        public int Height { get; }

        ///


        /// Gets the width of the input image in pixels.
        ///

        public int Width { get; }
    }

    ///


    /// Enum representing the degrees of rotation.
    ///

    public enum RotationDegree
    {
        ///
        /// Represents the 0-degree rotation angle.
        ///

        _0,
        ///
        /// Represents the 90-degree rotation angle.
        ///

        _90,
        ///
        /// Represents the 180-degree rotation angle.
        ///

        _180,
        ///
        /// Represents the 270-degree rotation angle.
        ///

        _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转三通道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().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
    {
        /// 
        /// Initializes a new instance of the  struct.
        /// 
        /// The number of color channels in the input image.
        /// The width of the input image in pixels.
        /// The height of the input image in pixels.
        public InputShape(int channel, int width, int height)
        {
            Channel = channel;
            Height = height;
            Width = width;
        }

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

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

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

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

下载 

源码下载

你可能感兴趣的:(C#人工智能实践,OpenVino,openvino,人工智能,opencv,目标检测,机器学习,深度学习,神经网络)