forked from unpaper/unpaper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageprocess.c
1344 lines (1207 loc) · 49.8 KB
/
imageprocess.c
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Unpaper.
*
* Copyright © 2005-2007 Jens Gulden
* Copyright © 2011-2011 Diego Elio Pettenò
*
* Unpaper is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* Unpaper is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
/* --- image processing --------------------------------------------------- */
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
//#include <time.h>
#include "unpaper.h"
#include "tools.h"
#include "parse.h" //for maksOverlapAny
/****************************************************************************
* image processing functions *
****************************************************************************/
/* --- deskewing ---------------------------------------------------------- */
/**
* Returns the maximum peak value that occurs when shifting a rotated virtual line above the image,
* starting from one edge of an area and moving towards the middle point of the area.
* The peak value is calulated by the absolute difference in the average blackness of pixels that occurs between two single shifting steps.
*
* @param m ascending slope of the virtually shifted (m=tan(angle)). Mind that this is negative for negative radians.
*/
static int detectEdgeRotationPeak(double m, int deskewScanSize, float deskewScanDepth, int shiftX, int shiftY, int left, int top, int right, int bottom, struct IMAGE* image) {
int width;
int height;
int mid;
int half;
int sideOffset;
int outerOffset;
double X; // unrounded coordinates
double Y;
double stepX;
double stepY;
int x[MAX_ROTATION_SCAN_SIZE];
int y[MAX_ROTATION_SCAN_SIZE];
int xx;
int yy;
int lineStep;
int dep;
int pixel;
int blackness;
int lastBlackness;
int diff;
int maxDiff;
int maxBlacknessAbs;
int maxDepth;
int accumulatedBlackness;
width = right-left+1;
height = bottom-top+1;
maxBlacknessAbs = (int) 255 * deskewScanSize * deskewScanDepth;
if (shiftY==0) { // horizontal detection
if (deskewScanSize == -1) {
deskewScanSize = height;
}
limit(&deskewScanSize, MAX_ROTATION_SCAN_SIZE);
limit(&deskewScanSize, height);
maxDepth = width/2;
half = deskewScanSize/2;
outerOffset = (int)(abs(m) * half);
mid = height/2;
sideOffset = shiftX > 0 ? left-outerOffset : right+outerOffset;
X = sideOffset + half * m;
Y = top + mid - half;
stepX = -m;
stepY = 1.0;
} else { // vertical detection
if (deskewScanSize == -1) {
deskewScanSize = width;
}
limit(&deskewScanSize, MAX_ROTATION_SCAN_SIZE);
limit(&deskewScanSize, width);
maxDepth = height/2;
half = deskewScanSize/2;
outerOffset = (int)(abs(m) * half);
mid = width/2;
sideOffset = shiftY > 0 ? top-outerOffset : bottom+outerOffset;
X = left + mid - half;
Y = sideOffset - (half * m);
stepX = 1.0;
stepY = -m; // (line goes upwards for negative degrees)
}
// fill buffer with coordinates for rotated line in first unshifted position
for (lineStep = 0; lineStep < deskewScanSize; lineStep++) {
x[lineStep] = (int)X;
y[lineStep] = (int)Y;
X += stepX;
Y += stepY;
}
// now scan for edge, modify coordinates in buffer to shift line into search direction (towards the middle point of the area)
// stop either when detectMaxDepth steps are shifted, or when diff falls back to less than detectThreshold*maxDiff
lastBlackness = 0;
diff = 0;
maxDiff = 0;
accumulatedBlackness = 0;
for (dep = 0; (accumulatedBlackness < maxBlacknessAbs) && (dep < maxDepth) ; dep++) {
// calculate blackness of virtual line
blackness = 0;
for (lineStep = 0; lineStep < deskewScanSize; lineStep++) {
xx = x[lineStep];
x[lineStep] += shiftX;
yy = y[lineStep];
y[lineStep] += shiftY;
if ((xx >= left) && (xx <= right) && (yy >= top) && (yy <= bottom)) {
pixel = getPixelDarknessInverse(xx, yy, image);
blackness += (255 - pixel);
}
}
diff = blackness - lastBlackness;
lastBlackness = blackness;
if (diff >= maxDiff) {
maxDiff = diff;
}
accumulatedBlackness += blackness;
}
if (dep < maxDepth) { // has not terminated only because middle was reached
return maxDiff;
} else {
return 0;
}
}
/**
* Detects rotation at one edge of the area specified by left, top, right, bottom.
* Which of the four edges to take depends on whether shiftX or shiftY is non-zero,
* and what sign this shifting value has.
*/
static double detectEdgeRotation(float deskewScanRange, float deskewScanStep, int deskewScanSize, float deskewScanDepth, int shiftX, int shiftY, int left, int top, int right, int bottom, struct IMAGE* image) {
// either shiftX or shiftY is 0, the other value is -i|+i
// depending on shiftX/shiftY the start edge for shifting is determined
double rangeRad;
double stepRad;
double rotation;
int peak;
int maxPeak;
double detectedRotation;
double m;
rangeRad = degreesToRadians((double)deskewScanRange);
stepRad = degreesToRadians((double)deskewScanStep);
detectedRotation = 0.0;
maxPeak = 0;
// iteratively increase test angle, alterating between +/- sign while increasing absolute value
for (rotation = 0.0; rotation <= rangeRad; rotation = (rotation>=0.0) ? -(rotation + stepRad) : -rotation ) {
m = tan(rotation);
peak = detectEdgeRotationPeak(m, deskewScanSize, deskewScanDepth, shiftX, shiftY, left, top, right, bottom, image);
if (peak > maxPeak) {
detectedRotation = rotation;
maxPeak = peak;
}
}
return radiansToDegrees(detectedRotation);
}
/**
* Detect rotation of a whole area.
* Angles between -deskewScanRange and +deskewScanRange are scanned, at either the
* horizontal or vertical edges of the area specified by left, top, right, bottom.
*/
double detectRotation(int deskewScanEdges, int deskewScanRange, float deskewScanStep, int deskewScanSize, float deskewScanDepth, float deskewScanDeviation, int left, int top, int right, int bottom, struct IMAGE* image) {
double rotation[4];
int count;
double total;
double average;
double deviation;
int i;
count = 0;
if ((deskewScanEdges & 1<<LEFT) != 0) {
// left
rotation[count] = detectEdgeRotation(deskewScanRange, deskewScanStep, deskewScanSize, deskewScanDepth, 1, 0, left, top, right, bottom, image);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation left: [%d,%d,%d,%d]: %f\n", left,top,right,bottom, rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1<<TOP) != 0) {
// top
rotation[count] = - detectEdgeRotation(deskewScanRange, deskewScanStep, deskewScanSize, deskewScanDepth, 0, 1, left, top, right, bottom, image);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation top: [%d,%d,%d,%d]: %f\n", left,top,right,bottom, rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1<<RIGHT) != 0) {
// right
rotation[count] = detectEdgeRotation(deskewScanRange, deskewScanStep, deskewScanSize, deskewScanDepth, -1, 0, left, top, right, bottom, image);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation right: [%d,%d,%d,%d]: %f\n", left,top,right,bottom, rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1<<BOTTOM) != 0) {
// bottom
rotation[count] = - detectEdgeRotation(deskewScanRange, deskewScanStep, deskewScanSize, deskewScanDepth, 0, -1, left, top, right, bottom, image);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation bottom: [%d,%d,%d,%d]: %f\n", left,top,right,bottom, rotation[count]);
}
count++;
}
total = 0.0;
for (i = 0; i < count; i++) {
total += rotation[i];
}
average = total / count;
total = 0.0;
for (i = 0; i < count; i++) {
total += sqr(rotation[i]-average);
}
deviation = sqrt(total);
if (verbose >= VERBOSE_NORMAL) {
printf("rotation average: %f deviation: %f rotation-scan-deviation (maximum): %f [%d,%d,%d,%d]\n", average, deviation, deskewScanDeviation, left,top,right,bottom);
}
if (deviation <= deskewScanDeviation) {
return average;
} else {
if (verbose >= VERBOSE_NONE) {
printf("out of deviation range - NO ROTATING\n");
}
return 0.0;
}
}
/**
* Rotates a whole image buffer by the specified radians, around its middle-point.
* Usually, the buffer should have been converted to a qpixels-representation before, to increase quality.
* (To rotate parts of an image, extract the part with copyBuffer, rotate, and re-paste with copyBuffer.)
*/
//void rotate(double radians, struct IMAGE* source, struct IMAGE* target, double* trigonometryCache, int trigonometryCacheBaseSize) {
void rotate(double radians, struct IMAGE* source, struct IMAGE* target) {
const int w = source->width;
const int h = source->height;
const int halfX = (w-1)/2;
const int halfY = (h-1)/2;
const int midX = w/2;
const int midY = h/2;
const int midMax = max(midX,midY);
// create 2D rotation matrix
const float sinval = sinf(radians);
const float cosval = cosf(radians);
const float m11 = cosval;
const float m12 = sinval;
const float m21 = -sinval;
const float m22 = cosval;
// step through all pixels of the target image,
// symmetrically in all four quadrants to reduce trigonometric calculations
int dX;
int dY;
for (dY = 0; dY <= midMax; dY++) {
for (dX = 0; dX <= midMax; dX++) {
// matrix multiplication to get rotated pixel pos (as in quadrant I)
const int diffX = dX * m11 + dY * m21;
const int diffY = dX * m12 + dY * m22;
int x;
int y;
// quadrant I
x = midX + dX;
y = midY - dY;
if ((x < w) && (y >= 0)) {
const int oldX = midX + diffX;
const int oldY = midY - diffY;
const int pixel = getPixel(oldX, oldY, source);
setPixel(pixel, x, y, target);
}
// quadrant II
x = halfX - dY;
y = midY - dX;
if ((x >=0) && (y >= 0)) {
const int oldX = halfX - diffY;
const int oldY = midY - diffX;
const int pixel = getPixel(oldX, oldY, source);
setPixel(pixel, x, y, target);
}
// quadrant III
x = halfX - dX;
y = halfY + dY;
if ((x >=0) && (y < h)) {
const int oldX = halfX - diffX;
const int oldY = halfY + diffY;
const int pixel = getPixel(oldX, oldY, source);
setPixel(pixel, x, y, target);
}
// quadrant IV
x = midX + dY;
y = halfY + dX;
if ((x < w) && (y < h)) {
const int oldX = midX + diffY;
const int oldY = halfY + diffX;
const int pixel = getPixel(oldX, oldY, source);
setPixel(pixel, x, y, target);
}
}
}
}
/**
* Converts an image buffer to a qpixel-representation, i.e. enlarge the whole
* whole image both horizontally and vertically by factor 2 (leading to a
* factor 4 increase in total).
* qpixelBuf must have been allocated before with 4-times amount of memory as
* buf.
*/
void convertToQPixels(struct IMAGE* image, struct IMAGE* qpixelImage) {
int x;
int y;
for (y = 0; y < image->height; y++) {
const int yy = y*2;
for (x = 0; x < image->width; x++) {
const int xx = x*2;
const int pixel = getPixel(x, y, image);
setPixel(pixel, xx, yy, qpixelImage);
setPixel(pixel, xx+1, yy, qpixelImage);
setPixel(pixel, xx, yy+1, qpixelImage);
setPixel(pixel, xx+1, yy+1, qpixelImage);
}
}
}
/**
* Converts an image buffer back from a qpixel-representation to normal, i.e.
* shrinks the whole image both horizontally and vertically by factor 2
* (leading to a factor 4 decrease in total).
* buf must have been allocated before with 1/4-times amount of memory as
* qpixelBuf.
*/
void convertFromQPixels(struct IMAGE* qpixelImage, struct IMAGE* image) {
int x;
int y;
for (y = 0; y < image->height; y++) {
const int yy = y*2;
for (x = 0; x < image->width; x++) {
const int xx = x*2;
const int a = getPixel(xx, yy, qpixelImage);
const int b = getPixel(xx+1, yy, qpixelImage);
const int c = getPixel(xx, yy+1, qpixelImage);
const int d = getPixel(xx+1, yy+1, qpixelImage);
const int r = (red(a) + red(b) + red(c) + red(d)) / 4;
const int g = (green(a) + green(b) + green(c) + green(d)) / 4;
const int bl = (blue(a) + blue(b) + blue(c) + blue(d)) / 4;
const int pixel = pixelValue(r, g, bl);
setPixel(pixel, x, y, image);
}
}
}
/* --- stretching / resizing / shifting ------------------------------------ */
/**
* Stretches the image so that the resulting image has a new size.
*
* @param w the new width to stretch to
* @param h the new height to stretch to
*/
void stretch(int w, int h, struct IMAGE* image) {
struct IMAGE newimage;
int x;
int y;
int matrixX;
int matrixY;
int matrixWidth;
int matrixHeight;
int blockWidth;
int blockHeight;
int blockWidthRest;
int blockHeightRest;
int fillIndexWidth;
int fillIndexHeight;
int fill;
int xx;
int yy;
int sum;
int sumR;
int sumG;
int sumB;
int sumCount;
int pixel;
if (verbose >= VERBOSE_MORE) {
printf("stretching %dx%d -> %dx%d\n", image->width, image->height, w, h);
}
// allocate new buffer's memory
initImage(&newimage, w, h, image->bitdepth, image->color, WHITE);
blockWidth = image->width / w; // (0 if enlarging, i.e. w > image->width)
blockHeight = image->height / h;
if (w <= image->width) {
blockWidthRest = (image->width) % w;
} else { // modulo-operator doesn't work as expected: (3680 % 7360)==3680 ! (not 7360 as expected)
// shouldn't always be a % b = b if a < b ?
blockWidthRest = w;
}
if (h <= image->height) {
blockHeightRest = (image->height) % h;
} else {
blockHeightRest = h;
}
// for each new pixel, get a matrix of pixels from which the new pixel should be derived
// (when enlarging, this matrix is always of size 1x1)
matrixY = 0;
fillIndexHeight = 0;
for (y = 0; y < h; y++) {
fillIndexWidth = 0;
matrixX = 0;
if ( ( (y * blockHeightRest) / h ) == fillIndexHeight ) { // next fill index?
// (If our optimizer is cool, the above "* blockHeightRest / h" will disappear
// when images are enlarged, because in that case blockHeightRest = h has been set before,
// thus we're in a Kripke-branch where blockHeightRest and h are the same variable.
// No idea if gcc's optimizer does this...) (See again below.)
fillIndexHeight++;
fill = 1;
} else {
fill = 0;
}
matrixHeight = blockHeight + fill;
for (x = 0; x < w; x++) {
if ( ( (x * blockWidthRest) / w ) == fillIndexWidth ) { // next fill index?
fillIndexWidth++;
fill = 1;
} else {
fill = 0;
}
matrixWidth = blockWidth + fill;
// if enlarging, map corrdinates directly
if (blockWidth == 0) { // enlarging
matrixX = (x * image->width) / w;
}
if (blockHeight == 0) { // enlarging
matrixY = (y * image->height) / h;
}
// calculate average pixel value in source matrix
if ((matrixWidth == 1) && (matrixHeight == 1)) { // optimization: quick version
pixel = getPixel(matrixX, matrixY, image);
} else {
sumCount = 0;
if (!image->color) {
sum = 0;
for (yy = 0; yy < matrixHeight; yy++) {
for (xx = 0; xx < matrixWidth; xx++) {
sum += getPixelGrayscale(matrixX + xx, matrixY + yy, image);
sumCount++;
}
}
sum = sum / sumCount;
pixel = pixelGrayscaleValue(sum);
} else { // color
sumR = 0;
sumG = 0;
sumB = 0;
for (yy = 0; yy < matrixHeight; yy++) {
for (xx = 0; xx < matrixWidth; xx++) {
pixel = getPixel(matrixX + xx, matrixY + yy, image);
sumR += (pixel >> 16) & 0xff;
sumG += (pixel >> 8) & 0xff;
sumB += pixel & 0xff;
//sumR += getPixelComponent(matrixX + xx, matrixY + yy, RED, image);
//sumG += getPixelComponent(matrixX + xx, matrixY + yy, GREEN, image);
//sumB += getPixelComponent(matrixX + xx, matrixY + yy, BLUE, image);
sumCount++;
}
}
pixel = pixelValue( sumR/sumCount, sumG/sumCount, sumB/sumCount );
}
}
setPixel(pixel, x, y, &newimage);
// pixel may have resulted in a gray value, which will be converted to 1-bit
// when the file gets saved, if .pbm format requested. black-threshold will apply.
if (blockWidth > 0) { // shrinking
matrixX += matrixWidth;
}
}
if (blockHeight > 0) { // shrinking
matrixY += matrixHeight;
}
}
replaceImage(image, &newimage);
}
/**
* Resizes the image so that the resulting sheet has a new size and the image
* content is zoomed to fit best into the sheet, while keeping it's aspect ration.
*
* @param w the new width to resize to
* @param h the new height to resize to
*/
void resize(int w, int h, struct IMAGE* image) {
struct IMAGE newimage;
int ww;
int hh;
float wRat;
float hRat;
if (verbose >= VERBOSE_NORMAL) {
printf("resizing %dx%d -> %dx%d\n", image->width, image->height, w, h);
}
wRat = (float)w / image->width;
hRat = (float)h / image->height;
if (wRat < hRat) { // horizontally more shrinking/less enlarging is needed: fill width fully, adjust height
ww = w;
hh = image->height * w / image->width;
} else if (hRat < wRat) {
ww = image->width * h / image->height;
hh = h;
} else { // wRat == hRat
ww = w;
hh = h;
}
stretch(ww, hh, image);
initImage(&newimage, w, h, image->bitdepth, image->color, image->background);
centerImage(image, 0, 0, w, h, &newimage);
replaceImage(image, &newimage);
}
/**
* Shifts the image.
*
* @param shiftX horizontal shifting
* @param shiftY vertical shifting
*/
void shift(int shiftX, int shiftY, struct IMAGE* image) {
struct IMAGE newimage;
int x;
int y;
int pixel;
// allocate new buffer's memory
initImage(&newimage, image->width, image->height, image->bitdepth, image->color, image->background);
for (y = 0; y < image->height; y++) {
for (x = 0; x < image->width; x++) {
pixel = getPixel(x, y, image);
setPixel(pixel, x + shiftX, y + shiftY, &newimage);
}
}
replaceImage(image, &newimage);
}
/* --- mask-detection ----------------------------------------------------- */
/**
* Finds one edge of non-black pixels headig from one starting point towards edge direction.
*
* @return number of shift-steps until blank edge found
*/
static int detectEdge(int startX, int startY, int shiftX, int shiftY, int maskScanSize, int maskScanDepth, float maskScanThreshold, struct IMAGE* image) {
// either shiftX or shiftY is 0, the other value is -i|+i
int left;
int top;
int right;
int bottom;
const int half = maskScanSize / 2;
int total = 0;
int count = 0;
if (shiftY==0) { // vertical border is to be detected, horizontal shifting of scan-bar
if (maskScanDepth == -1) {
maskScanDepth = image->height;
}
const int halfDepth = maskScanDepth / 2;
left = startX - half;
top = startY - halfDepth;
right = startX + half;
bottom = startY + halfDepth;
} else { // horizontal border is to be detected, vertical shifting of scan-bar
if (maskScanDepth == -1) {
maskScanDepth = image->width;
}
const int halfDepth = maskScanDepth / 2;
left = startX - halfDepth;
top = startY - half;
right = startX + halfDepth;
bottom = startY + half;
}
while (true) { // !
const int blackness = 255 - brightnessRect(left, top, right, bottom, image);
total += blackness;
count++;
// is blackness below threshold*average?
if ((blackness < ((maskScanThreshold*total)/count))||(blackness==0)) { // this will surely become true when pos reaches the outside of the actual image area and blacknessRect() will deliver 0 because all pixels outside are considered white
return count; // ! return here, return absolute value of shifting difference
}
left += shiftX;
right += shiftX;
top += shiftY;
bottom += shiftY;
}
}
/**
* Detects a mask of white borders around a starting point.
* The result is returned via call-by-reference parameters left, top, right, bottom.
*
* @return the detected mask in left, top, right, bottom; or -1, -1, -1, -1 if no mask could be detected
*/
static bool detectMask(int startX, int startY, int maskScanDirections, int maskScanSize[DIRECTIONS_COUNT], int maskScanDepth[DIRECTIONS_COUNT], int maskScanStep[DIRECTIONS_COUNT], float maskScanThreshold[DIRECTIONS_COUNT], int maskScanMinimum[DIMENSIONS_COUNT], int maskScanMaximum[DIMENSIONS_COUNT], int* left, int* top, int* right, int* bottom, struct IMAGE* image) {
int width;
int height;
int half[DIRECTIONS_COUNT];
bool success;
half[HORIZONTAL] = maskScanSize[HORIZONTAL] / 2;
half[VERTICAL] = maskScanSize[VERTICAL] / 2;
if ((maskScanDirections & 1<<HORIZONTAL) != 0) {
*left = startX - maskScanStep[HORIZONTAL] * detectEdge(startX, startY, -maskScanStep[HORIZONTAL], 0, maskScanSize[HORIZONTAL], maskScanDepth[HORIZONTAL], maskScanThreshold[HORIZONTAL], image) - half[HORIZONTAL];
*right = startX + maskScanStep[HORIZONTAL] * detectEdge(startX, startY, maskScanStep[HORIZONTAL], 0, maskScanSize[HORIZONTAL], maskScanDepth[HORIZONTAL], maskScanThreshold[HORIZONTAL], image) + half[HORIZONTAL];
} else { // full range of sheet
*left = 0;
*right = image->width - 1;
}
if ((maskScanDirections & 1<<VERTICAL) != 0) {
*top = startY - maskScanStep[VERTICAL] * detectEdge(startX, startY, 0, -maskScanStep[VERTICAL], maskScanSize[VERTICAL], maskScanDepth[VERTICAL], maskScanThreshold[VERTICAL], image) - half[VERTICAL];
*bottom = startY + maskScanStep[VERTICAL] * detectEdge(startX, startY, 0, maskScanStep[VERTICAL], maskScanSize[VERTICAL], maskScanDepth[VERTICAL], maskScanThreshold[VERTICAL], image) + half[VERTICAL];
} else { // full range of sheet
*top = 0;
*bottom = image->height - 1;
}
// if below minimum or above maximum, set to maximum
width = *right - *left;
height = *bottom - *top;
success = true;
if ( ((maskScanMinimum[WIDTH] != -1) && (width < maskScanMinimum[WIDTH])) || ((maskScanMaximum[WIDTH] != -1) && (width > maskScanMaximum[WIDTH])) ) {
width = maskScanMaximum[WIDTH] / 2;
*left = startX - width;
*right = startX + width;
success = false;;
}
if ( ((maskScanMinimum[HEIGHT] != -1) && (height < maskScanMinimum[HEIGHT])) || ((maskScanMaximum[HEIGHT] != -1) && (height > maskScanMaximum[HEIGHT])) ) {
height = maskScanMaximum[HEIGHT] / 2;
*top = startY - height;
*bottom = startY + height;
success = false;
}
return success;
}
/**
* Detects masks around the points specified in point[].
*
* @param mask point to array into which detected masks will be stored
* @return number of masks stored in mask[][]
*/
int detectMasks(int mask[MAX_MASKS][EDGES_COUNT], bool maskValid[MAX_MASKS], int point[MAX_POINTS][COORDINATES_COUNT], int pointCount, int maskScanDirections, int maskScanSize[DIRECTIONS_COUNT], int maskScanDepth[DIRECTIONS_COUNT], int maskScanStep[DIRECTIONS_COUNT], float maskScanThreshold[DIRECTIONS_COUNT], int maskScanMinimum[DIMENSIONS_COUNT], int maskScanMaximum[DIMENSIONS_COUNT], struct IMAGE* image) {
int left;
int top;
int right;
int bottom;
int i;
int maskCount;
maskCount = 0;
if (maskScanDirections != 0) {
for (i = 0; i < pointCount; i++) {
maskValid[i] = detectMask(point[i][X], point[i][Y], maskScanDirections, maskScanSize, maskScanDepth, maskScanStep, maskScanThreshold, maskScanMinimum, maskScanMaximum, &left, &top, &right, &bottom, image);
if (!(left==-1 || top==-1 || right==-1 || bottom==-1)) {
mask[maskCount][LEFT] = left;
mask[maskCount][TOP] = top;
mask[maskCount][RIGHT] = right;
mask[maskCount][BOTTOM] = bottom;
maskCount++;
if (verbose>=VERBOSE_NORMAL) {
printf("auto-masking (%d,%d): %d,%d,%d,%d", point[i][X], point[i][Y], left, top, right, bottom);
if (maskValid[i] == false) { // (mask had been auto-set to full page size)
printf(" (invalid detection, using full page size)");
}
printf("\n");
}
} else {
if (verbose>=VERBOSE_NORMAL) {
printf("auto-masking (%d,%d): NO MASK FOUND\n", point[i][X], point[i][Y]);
}
}
//if (maskValid[i] == false) { // (mask had been auto-set to full page size)
// if (verbose>=VERBOSE_NORMAL) {
// printf("auto-masking (%d,%d): NO MASK DETECTED\n", point[i][X], point[i][Y]);
// }
//}
}
}
return maskCount;
}
/**
* Permanently applies image masks. Each pixel which is not covered by at least
* one mask is set to maskColor.
*/
void applyMasks(int mask[MAX_MASKS][EDGES_COUNT], int maskCount, int maskColor, struct IMAGE* image) {
int x;
int y;
int i;
if (maskCount<=0) {
return;
}
for (y=0; y < image->height; y++) {
for (x=0; x < image->width; x++) {
// in any mask?
bool m = false;
for (i=0; ((m==false) && (i<maskCount)); i++) {
const int left = mask[i][LEFT];
const int top = mask[i][TOP];
const int right = mask[i][RIGHT];
const int bottom = mask[i][BOTTOM];
if (y>=top && y<=bottom && x>=left && x<=right) {
m = true;
}
}
if (m == false) {
setPixel(maskColor, x, y, image); // delete: set to white
}
}
}
}
/* --- wiping ------------------------------------------------------------- */
/**
* Permanently wipes out areas of an images. Each pixel covered by a wipe-area
* is set to wipeColor.
*/
void applyWipes(int area[MAX_MASKS][EDGES_COUNT], int areaCount, int wipeColor, struct IMAGE* image) {
int x;
int y;
int i;
for (i = 0; i < areaCount; i++) {
int count = 0;
for (y = area[i][TOP]; y <= area[i][BOTTOM]; y++) {
for (x = area[i][LEFT]; x <= area[i][RIGHT]; x++) {
if ( setPixel(wipeColor, x, y, image) ) {
count++;
}
}
}
if (verbose >= VERBOSE_MORE) {
printf("wipe [%d,%d,%d,%d]: %d pixels\n", area[i][LEFT], area[i][TOP], area[i][RIGHT], area[i][BOTTOM], count);
}
}
}
/* --- mirroring ---------------------------------------------------------- */
/**
* Mirrors an image either horizontally, vertically, or both.
*/
void mirror(int directions, struct IMAGE* image) {
int x;
int y;
const bool horizontal = !!((directions & 1<<HORIZONTAL) != 0);
const bool vertical = !!((directions & 1<<VERTICAL) != 0);
int untilX = ((horizontal==true)&&(vertical==false)) ? ((image->width - 1) >> 1) : (image->width - 1); // w>>1 == (int)(w-0.5)/2
int untilY = (vertical==true) ? ((image->height - 1) >> 1) : image->height - 1;
for (y = 0; y <= untilY; y++) {
const int yy = (vertical==true) ? (image->height - y - 1) : y;
if ((vertical==true) && (horizontal==true) && (y == yy)) { // last middle line in odd-lined image mirrored both h and v
untilX = ((image->width - 1) >> 1);
}
for (x = 0; x <= untilX; x++) {
const int xx = (horizontal==true) ? (image->width - x - 1) : x;
const int pixel1 = getPixel(x, y, image);
const int pixel2 = getPixel(xx, yy, image);
setPixel(pixel2, x, y, image);
setPixel(pixel1, xx, yy, image);
}
}
}
/* --- flip-rotating ------------------------------------------------------ */
/**
* Rotates an image clockwise or anti-clockwise in 90-degrees.
*
* @param direction either -1 (rotate anti-clockwise) or 1 (rotate clockwise)
*/
void flipRotate(int direction, struct IMAGE* image) {
struct IMAGE newimage;
int x;
int y;
initImage(&newimage, image->height, image->width, image->bitdepth, image->color, WHITE); // exchanged width and height
for (y = 0; y < image->height; y++) {
const int xx = ((direction > 0) ? image->height - 1 : 0) - y * direction;
for (x = 0; x < image->width; x++) {
const int yy = ((direction < 0) ? image->width - 1 : 0) + x * direction;
const int pixel = getPixel(x, y, image);
setPixel(pixel, xx, yy, &newimage);
}
}
replaceImage(image, &newimage);
}
/* --- blackfilter -------------------------------------------------------- */
/**
* Filters out solidly black areas scanning to one direction.
*
* @param stepX is 0 if stepY!=0
* @param stepY is 0 if stepX!=0
* @see blackfilter()
*/
static void blackfilterScan(int stepX, int stepY, int size, int dep, float threshold, int exclude[MAX_MASKS][EDGES_COUNT], int excludeCount, int intensity, float blackThreshold, struct IMAGE* image) {
int left;
int top;
int right;
int bottom;
int blackness;
int thresholdBlack;
int x;
int y;
int shiftX;
int shiftY;
int l, t, r, b;
int diffX;
int diffY;
int mask[EDGES_COUNT];
bool alreadyExcludedMessage;
thresholdBlack = (int)(WHITE * (1.0-blackThreshold));
if (stepX != 0) { // horizontal scanning
left = 0;
top = 0;
right = size -1;
bottom = dep - 1;
shiftX = 0;
shiftY = dep;
} else { // vertical scanning
left = 0;
top = 0;
right = dep -1;
bottom = size - 1;
shiftX = dep;
shiftY = 0;
}
while ((left < image->width) && (top < image->height)) { // individual scanning "stripes" over the whole sheet
l = left;
t = top;
r = right;
b = bottom;
// make sure last stripe does not reach outside sheet, shift back inside (next +=shift will exit while-loop)
if (r >= image->width || b >= image->height) {
diffX = r-image->width+1;
diffY = b-image->height+1;
l -= diffX;
t -= diffY;
r -= diffX;
b -= diffY;
}
alreadyExcludedMessage = false;
while ((l < image->width) && (t < image->height)) { // single scanning "stripe"
blackness = 255 - darknessInverseRect(l, t, r, b, image);
if (blackness >= 255*threshold) { // found a solidly black area
mask[LEFT] = l;
mask[TOP] = t;
mask[RIGHT] = r;
mask[BOTTOM] = b;
if (! masksOverlapAny(mask, exclude, excludeCount) ) {
if (verbose >= VERBOSE_NORMAL) {
printf("black-area flood-fill: [%d,%d,%d,%d]\n", l, t, r, b);
alreadyExcludedMessage = false;
}
// start flood-fill in this area (on each pixel to make sure we get everything, in most cases first flood-fill from first pixel will delete all other black pixels in the area already)
for (y = t; y <= b; y++) {
for (x = l; x <= r; x++) {
floodFill(x, y, pixelValue(WHITE, WHITE, WHITE), 0, thresholdBlack, intensity, image);
}
}
} else {
if ((verbose >= VERBOSE_NORMAL) && (!alreadyExcludedMessage)) {
printf("black-area EXCLUDED: [%d,%d,%d,%d]\n", l, t, r, b);
alreadyExcludedMessage = true; // do this only once per scan-stripe, otherwise too many mesages
}
}
}
l += stepX;
t += stepY;
r += stepX;
b += stepY;
}
left += shiftX;
top += shiftY;
right += shiftX;
bottom += shiftY;
}
}
/**
* Filters out solidly black areas, as appearing on bad photocopies.
* A virtual bar of width 'size' and height 'depth' is horizontally moved
* above the middle of the sheet (or the full sheet, if depth ==-1).
*/
void blackfilter(int blackfilterScanDirections, int blackfilterScanSize[DIRECTIONS_COUNT], int blackfilterScanDepth[DIRECTIONS_COUNT], int blackfilterScanStep[DIRECTIONS_COUNT], float blackfilterScanThreshold, int blackfilterExclude[MAX_MASKS][EDGES_COUNT], int blackfilterExcludeCount, int blackfilterIntensity, float blackThreshold, struct IMAGE* image) {
if ((blackfilterScanDirections & 1<<HORIZONTAL) != 0) { // left-to-right scan
blackfilterScan(blackfilterScanStep[HORIZONTAL], 0, blackfilterScanSize[HORIZONTAL], blackfilterScanDepth[HORIZONTAL], blackfilterScanThreshold, blackfilterExclude, blackfilterExcludeCount, blackfilterIntensity, blackThreshold, image);
}
if ((blackfilterScanDirections & 1<<VERTICAL) != 0) { // top-to-bottom scan
blackfilterScan(0, blackfilterScanStep[VERTICAL], blackfilterScanSize[VERTICAL], blackfilterScanDepth[VERTICAL], blackfilterScanThreshold, blackfilterExclude, blackfilterExcludeCount, blackfilterIntensity, blackThreshold, image);
}
}
/* --- noisefilter -------------------------------------------------------- */
/**
* Applies a simple noise filter to the image.
*
* @param intensity maximum cluster size to delete
*/
int noisefilter(int intensity, float whiteThreshold, struct IMAGE* image) {
int x;
int y;
int whiteMin;
int count;
int pixel;
int neighbors;
whiteMin = (int)(WHITE * whiteThreshold);
count = 0;
for (y = 0; y < image->height; y++) {
for (x = 0; x < image->width; x++) {
pixel = getPixelDarknessInverse(x, y, image);
if (pixel < whiteMin) { // one dark pixel found
neighbors = countPixelNeighbors(x, y, intensity, whiteMin, image); // get number of non-light pixels in neighborhood
if (neighbors <= intensity) { // ...not more than 'intensity'?
clearPixelNeighbors(x, y, whiteMin, image); // delete area
count++;
}