效果
项目
VS2022+.net4.8+ OpenCvSharp4+Sdcb.RotationDetector
代码
using OpenCvSharp;
using Sdcb.RotationDetector;
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;
namespace RotationDetector_图片旋转角度检测
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
startupPath = Application.StartupPath;
rd = new PaddleRotationDetector(RotationDetectionModel.EmbeddedDefault);
}
Bitmap bmp;
string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
string img = "";
string startupPath = "";
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now;
PaddleRotationDetector rd;
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 button2_Click(object sender, EventArgs e)
{
if (img=="") { return; }
Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(new Bitmap(pictureBox1.Image));
Cv2.CvtColor(src, src, ColorConversionCodes.RGBA2RGB);//mat转三通道mat
dt1 = DateTime.Now;
RotationResult r = rd.Run(src);
dt2 = DateTime.Now;
StringBuilder sb = new StringBuilder();
sb.AppendLine("图片旋转角度:"+ r.Rotation );
sb.AppendLine("--------------------");
sb.AppendLine("耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
textBox1.Text = sb.ToString();
}
/// <summary>
/// 90
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// 180
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// 270
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
}
}
Demo下载