This repository has been archived by the owner on Nov 19, 2020. It is now read-only.
/
DocumentSkewChecker.cs
502 lines (443 loc) · 18.5 KB
/
DocumentSkewChecker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// AForge Image Processing Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © Andrew Kirillov, 2005-2010
// andrew.kirillov@aforgenet.com
//
// Alejandro Pirola, 2008
// alejamp@gmail.com
//
namespace Accord.Imaging
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
/// <summary>
/// Skew angle checker for scanned documents.
/// </summary>
///
/// <remarks><para>The class implements document's skew checking algorithm, which is based
/// on <see cref="HoughLineTransformation">Hough line transformation</see>. The algorithm
/// is based on searching for text base lines - black line of text bottoms' followed
/// by white line below.</para>
///
/// <para><note>The routine supposes that a white-background document is provided
/// with black letters. The algorithm is not supposed for any type of objects, but for
/// document images with text.</note></para>
///
/// <para>The range of angles to detect is controlled by <see cref="MaxSkewToDetect"/> property.</para>
///
/// <para>The filter accepts 8 bpp grayscale images for processing.</para>
///
/// <para>Sample usage:</para>
/// <code>
/// // create instance of skew checker
/// DocumentSkewChecker skewChecker = new DocumentSkewChecker( );
/// // get documents skew angle
/// double angle = skewChecker.GetSkewAngle( documentImage );
/// // create rotation filter
/// RotateBilinear rotationFilter = new RotateBilinear( -angle );
/// rotationFilter.FillColor = Color.White;
/// // rotate image applying the filter
/// Bitmap rotatedImage = rotationFilter.Apply( documentImage );
/// </code>
///
/// <para><b>Initial image:</b></para>
/// <img src="..\images\imaging\sample10.png" width="300" height="184" />
/// <para><b>Deskewed image:</b></para>
/// <img src="..\images\imaging\deskew.png" width="335" height="250" />
/// </remarks>
///
/// <seealso cref="HoughLineTransformation"/>
///
public class DocumentSkewChecker
{
// Hough transformation: quality settings
private int stepsPerDegree;
private int houghHeight;
private double thetaStep;
private double maxSkewToDetect;
// Hough transformation: precalculated Sine and Cosine values
private double[] sinMap;
private double[] cosMap;
private bool needToInitialize = true;
// Hough transformation: Hough map
private short[,] houghMap;
private short maxMapIntensity = 0;
private int localPeakRadius = 4;
private List<HoughLine> lines = new List<HoughLine>();
/// <summary>
/// Steps per degree, [1, 10].
/// </summary>
///
/// <remarks><para>The value defines quality of Hough transform and its ability to detect
/// line slope precisely.</para>
///
/// <para>Default value is set to <b>1</b>.</para>
/// </remarks>
///
public int StepsPerDegree
{
get { return stepsPerDegree; }
set
{
stepsPerDegree = Math.Max( 1, Math.Min( 10, value ) );
needToInitialize = true;
}
}
/// <summary>
/// Maximum skew angle to detect, [0, 45] degrees.
/// </summary>
///
/// <remarks><para>The value sets maximum document's skew angle to detect.
/// Document's skew angle can be as positive (rotated counter clockwise), as negative
/// (rotated clockwise). So setting this value to 25, for example, will lead to
/// [-25, 25] degrees detection range.</para>
///
/// <para>Scanned documents usually have skew in the [-20, 20] degrees range.</para>
///
/// <para>Default value is set to <b>30</b>.</para>
/// </remarks>
///
public double MaxSkewToDetect
{
get { return maxSkewToDetect; }
set
{
maxSkewToDetect = Math.Max( 0, Math.Min( 45, value ) );
needToInitialize = true;
}
}
/// <summary>
/// Minimum angle to detect skew in degrees.
/// </summary>
///
/// <remarks><para><note>The property is deprecated and setting it has not any effect.
/// Use <see cref="MaxSkewToDetect"/> property instead.</note></para></remarks>
///
[Obsolete( "The property is deprecated and setting it has not any effect. Use MaxSkewToDetect property instead." )]
public double MinBeta
{
get { return ( -maxSkewToDetect ); }
set { }
}
/// <summary>
/// Maximum angle to detect skew in degrees.
/// </summary>
///
/// <remarks><para><note>The property is deprecated and setting it has not any effect.
/// Use <see cref="MaxSkewToDetect"/> property instead.</note></para></remarks>
///
[Obsolete( "The property is deprecated and setting it has not any effect. Use MaxSkewToDetect property instead." )]
public double MaxBeta
{
get { return ( maxSkewToDetect ); }
set { }
}
/// <summary>
/// Radius for searching local peak value, [1, 10].
/// </summary>
///
/// <remarks><para>The value determines radius around a map's value, which is analyzed to determine
/// if the map's value is a local maximum in specified area.</para>
///
/// <para>Default value is set to <b>4</b>.</para></remarks>
///
public int LocalPeakRadius
{
get { return localPeakRadius; }
set { localPeakRadius = Math.Max( 1, Math.Min( 10, value ) ); }
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentSkewChecker"/> class.
/// </summary>
public DocumentSkewChecker( )
{
StepsPerDegree = 10;
MaxSkewToDetect = 30;
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="image">Document's image to get skew angle of.</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( Bitmap image )
{
return GetSkewAngle( image, new Rectangle( 0, 0, image.Width, image.Height ) );
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="image">Document's image to get skew angle of.</param>
/// <param name="rect">Image's rectangle to process (used to exclude processing of
/// regions, which are not relevant to skew detection).</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( Bitmap image, Rectangle rect )
{
// check image format
if ( image.PixelFormat != PixelFormat.Format8bppIndexed )
{
throw new UnsupportedImageFormatException( "Unsupported pixel format of the source image." );
}
// lock source image
BitmapData imageData = image.LockBits(
new Rectangle( 0, 0, image.Width, image.Height ),
ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed );
double skewAngle;
try
{
// process the image
skewAngle = GetSkewAngle( new UnmanagedImage( imageData ), rect );
}
finally
{
// unlock image
image.UnlockBits( imageData );
}
return skewAngle;
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="imageData">Document's image data to get skew angle of.</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( BitmapData imageData )
{
return GetSkewAngle( new UnmanagedImage( imageData ),
new Rectangle( 0, 0, imageData.Width, imageData.Height ) );
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="imageData">Document's image data to get skew angle of.</param>
/// <param name="rect">Image's rectangle to process (used to exclude processing of
/// regions, which are not relevant to skew detection).</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( BitmapData imageData, Rectangle rect )
{
return GetSkewAngle( new UnmanagedImage( imageData ), rect );
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="image">Document's unmanaged image to get skew angle of.</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( UnmanagedImage image )
{
return GetSkewAngle( image, new Rectangle( 0, 0, image.Width, image.Height ) );
}
/// <summary>
/// Get skew angle of the provided document image.
/// </summary>
///
/// <param name="image">Document's unmanaged image to get skew angle of.</param>
/// <param name="rect">Image's rectangle to process (used to exclude processing of
/// regions, which are not relevant to skew detection).</param>
///
/// <returns>Returns document's skew angle. If the returned angle equals to -90,
/// then document skew detection has failed.</returns>
///
/// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception>
///
public double GetSkewAngle( UnmanagedImage image, Rectangle rect )
{
if ( image.PixelFormat != PixelFormat.Format8bppIndexed )
{
throw new UnsupportedImageFormatException( "Unsupported pixel format of the source image." );
}
// init hough transformation settings
InitHoughMap( );
// get source image size
int width = image.Width;
int height = image.Height;
int halfWidth = width / 2;
int halfHeight = height / 2;
// make sure the specified rectangle recides with the source image
rect.Intersect( new Rectangle( 0, 0, width, height ) );
int startX = -halfWidth + rect.Left;
int startY = -halfHeight + rect.Top;
int stopX = width - halfWidth - ( width - rect.Right );
int stopY = height - halfHeight - ( height - rect.Bottom ) - 1;
int offset = image.Stride - rect.Width;
// calculate Hough map's width
int halfHoughWidth = (int) Math.Sqrt( halfWidth * halfWidth + halfHeight * halfHeight );
int houghWidth = halfHoughWidth * 2;
houghMap = new short[houghHeight, houghWidth];
// do the job
unsafe
{
byte* src = (byte*) image.ImageData.ToPointer( ) +
rect.Top * image.Stride + rect.Left;
byte* srcBelow = src + image.Stride;
// for each row
for ( int y = startY; y < stopY; y++ )
{
// for each pixel
for ( int x = startX; x < stopX; x++, src++, srcBelow++ )
{
// if current pixel is more black
// and pixel below is more white
if ( ( *src < 128 ) && ( *srcBelow >= 128 ) )
{
// for each Theta value
for ( int theta = 0; theta < houghHeight; theta++ )
{
int radius = (int) ( cosMap[theta] * x - sinMap[theta] * y ) + halfHoughWidth;
if ( ( radius < 0 ) || ( radius >= houghWidth ) )
continue;
houghMap[theta, radius]++;
}
}
}
src += offset;
srcBelow += offset;
}
}
// find max value in Hough map
maxMapIntensity = 0;
for ( int i = 0; i < houghHeight; i++ )
{
for ( int j = 0; j < houghWidth; j++ )
{
if ( houghMap[i, j] > maxMapIntensity )
{
maxMapIntensity = houghMap[i, j];
}
}
}
CollectLines( (short) ( width / 10 ) );
// get skew angle
HoughLine[] hls = this.GetMostIntensiveLines( 5 );
double skewAngle = 0;
double sumIntensity = 0;
foreach ( HoughLine hl in hls )
{
if ( hl.RelativeIntensity > 0.5 )
{
skewAngle += ( hl.Theta * hl.RelativeIntensity );
sumIntensity += hl.RelativeIntensity;
}
}
if ( hls.Length > 0 ) skewAngle = skewAngle / sumIntensity;
return skewAngle - 90.0;
}
// Get specified amount of lines with highest intensity
private HoughLine[] GetMostIntensiveLines( int count )
{
// lines count
int n = Math.Min( count, lines.Count );
// result array
HoughLine[] dst = new HoughLine[n];
lines.CopyTo( 0, dst, 0, n );
return dst;
}
// Collect lines with intesities greater or equal then specified
private void CollectLines( short minLineIntensity )
{
int maxTheta = houghMap.GetLength( 0 );
int maxRadius = houghMap.GetLength( 1 );
short intensity;
bool foundGreater;
int halfHoughWidth = maxRadius >> 1;
// clean lines collection
lines.Clear( );
// for each Theta value
for ( int theta = 0; theta < maxTheta; theta++ )
{
// for each Radius value
for ( int radius = 0; radius < maxRadius; radius++ )
{
// get current value
intensity = houghMap[theta, radius];
if ( intensity < minLineIntensity )
continue;
foundGreater = false;
// check neighboors
for ( int tt = theta - localPeakRadius, ttMax = theta + localPeakRadius; tt < ttMax; tt++ )
{
// skip out of map values
if ( tt < 0 )
continue;
if ( tt >= maxTheta )
break;
// break if it is not local maximum
if ( foundGreater == true )
break;
for ( int tr = radius - localPeakRadius, trMax = radius + localPeakRadius; tr < trMax; tr++ )
{
// skip out of map values
if ( tr < 0 )
continue;
if ( tr >= maxRadius )
break;
// compare the neighboor with current value
if ( houghMap[tt, tr] > intensity )
{
foundGreater = true;
break;
}
}
}
// was it local maximum ?
if ( !foundGreater )
{
// we have local maximum
lines.Add( new HoughLine( 90.0 - maxSkewToDetect + (double) theta / stepsPerDegree, (short) ( radius - halfHoughWidth ), intensity, (double) intensity / maxMapIntensity ) );
}
}
}
lines.Sort( );
}
// Init Hough settings and map
private void InitHoughMap( )
{
if ( needToInitialize )
{
needToInitialize = false;
houghHeight = (int) ( 2 * maxSkewToDetect * stepsPerDegree );
thetaStep = ( 2 * maxSkewToDetect * Math.PI / 180 ) / houghHeight;
// precalculate Sine and Cosine values
sinMap = new double[houghHeight];
cosMap = new double[houghHeight];
double minTheta = 90.0 - maxSkewToDetect;
for ( int i = 0; i < houghHeight; i++ )
{
sinMap[i] = Math.Sin( ( minTheta * Math.PI / 180 ) + ( i * thetaStep ) );
cosMap[i] = Math.Cos( ( minTheta * Math.PI / 180 ) + ( i * thetaStep ) );
}
}
}
}
}