using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
using System.Drawing.Imaging;
//窗体调用
private Bitmap RotateImage(Bitmap bmp, double angle)
{
Graphics g = null;
Bitmap tmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format32bppRgb);
tmp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
g = Graphics.FromImage(tmp);
try
{
g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
g.RotateTransform((float)angle);
g.DrawImage(bmp, 0, 0);
}
finally
{
g.Dispose();
}
return tmp;
}
private void button1_Click(object sender, EventArgs e)
{
string fnIn = "f:\\\\test\\\\image0097_4.tif";
string fnOut = "f:\\\\test\\\\output.tif";
Bitmap bmpIn = new Bitmap(fnIn);
gmseDeskew sk = new gmseDeskew(bmpIn);
double skewangle = sk.GetSkewAngle();
Bitmap bmpOut = RotateImage(bmpIn, -skewangle);
bmpOut.Save(fnOut, ImageFormat.Tiff);//此处简单保存,可采用压缩方式保存
}
#region 算法处理类
public class gmseDeskew
{
public class HougLine
{
// Count of points in the line.
public int Count;
// Index in Matrix.
public int Index;
// The line is represented as all x,y that solve y*cos(alpha)-x*sin(alpha)=d
public double Alpha;
public double d;
}
Bitmap cBmp;
double cAlphaStart = -20;
double cAlphaStep = 0.2;
int cSteps = 40 * 5;
double[] cSinA;
double[] cCosA;
double cDMin;
double cDStep = 1;
int cDCount;
// Count of points that fit in a line.
int[] cHMatrix;
public double GetSkewAngle()
{
gmseDeskew.HougLine[] hl = null;
int i = 0;
double sum = 0;
int count = 0;
// Hough Transformation
Calc();
// Top 20 of the detected lines in the image.
hl = GetTop(20);
// Average angle of the lines
for (i = 0; i <= 19; i++)
{
sum += hl[i].Alpha;
count += 1;
}
return sum / count;
}
private HougLine[] GetTop(int Count)
{
HougLine[] hl = null;
int i = 0;
int j = 0;
HougLine tmp = null;
int AlphaIndex = 0;
int dIndex = 0;
hl = new HougLine[Count + 1];
for (i = 0; i <= Count - 1; i++)
{