forked from unpaper/unpaper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimageprocess.c
1289 lines (1187 loc) · 41.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
// Copyright © 2005-2007 Jens Gulden
// Copyright © 2011-2011 Diego Elio Pettenò
// Copyright © 2013 Michael McMaster <michael@codesrc.com>
// SPDX-FileCopyrightText: 2005 The unpaper authors
//
// SPDX-License-Identifier: GPL-2.0-only
/* --- image processing --------------------------------------------------- */
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "imageprocess.h"
#include "parse.h" //for maksOverlapAny
#include "tools.h"
#include "unpaper.h"
/****************************************************************************
* image processing functions *
****************************************************************************/
static inline bool inMask(int x, int y, Mask mask) {
return (x >= mask[LEFT]) && (x <= mask[RIGHT]) && (y >= mask[TOP]) &&
(y <= mask[BOTTOM]);
}
/**
* Tests if masks a and b overlap.
*/
static inline bool masksOverlap(Mask a, Mask b) {
return (inMask(a[LEFT], a[TOP], b) || inMask(a[RIGHT], a[BOTTOM], b));
}
/**
* Tests if at least one mask in masks overlaps with m.
*/
static bool masksOverlapAny(Mask m,
Mask *masks, int masksCount) {
for (int i = 0; i < masksCount; i++) {
if (masksOverlap(m, masks[i])) {
return true;
}
}
return false;
}
/* --- 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 calculated 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(float m, int shiftX, int shiftY,
AVFrame *image, Mask mask) {
int width = mask[RIGHT] - mask[LEFT] + 1;
int height = mask[BOTTOM] - mask[TOP] + 1;
int mid;
int half;
int sideOffset;
int outerOffset;
float X; // unrounded coordinates
float Y;
float stepX;
float stepY;
int x[MAX_ROTATION_SCAN_SIZE];
int y[MAX_ROTATION_SCAN_SIZE];
int xx;
int yy;
int dep;
int pixel;
int blackness;
int lastBlackness = 0;
int diff = 0;
int maxDiff = 0;
int maxBlacknessAbs = 255 * deskewScanSize * deskewScanDepth;
int maxDepth;
int accumulatedBlackness = 0;
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)(fabsf(m) * half);
mid = height / 2;
sideOffset =
shiftX > 0 ? mask[LEFT] - outerOffset : mask[RIGHT] + outerOffset;
X = sideOffset + half * m;
Y = mask[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)(fabsf(m) * half);
mid = width / 2;
sideOffset =
shiftY > 0 ? mask[TOP] - outerOffset : mask[BOTTOM] + outerOffset;
X = mask[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 (int 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
for (dep = 0; (accumulatedBlackness < maxBlacknessAbs) && (dep < maxDepth);
dep++) {
// calculate blackness of virtual line
blackness = 0;
for (int lineStep = 0; lineStep < deskewScanSize; lineStep++) {
xx = x[lineStep];
x[lineStep] += shiftX;
yy = y[lineStep];
y[lineStep] += shiftY;
if (inMask(xx, yy, mask)) {
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 float detectEdgeRotation(int shiftX, int shiftY, AVFrame *image,
Mask mask) {
// either shiftX or shiftY is 0, the other value is -i|+i
// depending on shiftX/shiftY the start edge for shifting is determined
int maxPeak = 0;
float detectedRotation = 0.0;
// iteratively increase test angle, alternating between +/- sign while
// increasing absolute value
for (float rotation = 0.0; rotation <= deskewScanRangeRad;
rotation = (rotation >= 0.0) ? -(rotation + deskewScanStepRad)
: -rotation) {
float m = tanf(rotation);
int peak = detectEdgeRotationPeak(m, shiftX, shiftY, image, mask);
if (peak > maxPeak) {
detectedRotation = rotation;
maxPeak = peak;
}
}
return 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.
*/
float detectRotation(AVFrame *image, Mask mask) {
float rotation[4];
int count = 0;
float total;
float average;
float deviation;
if ((deskewScanEdges & 1 << LEFT) != 0) {
// left
rotation[count] = detectEdgeRotation(1, 0, image, mask);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation left: [%d,%d,%d,%d]: %f\n", mask[LEFT],
mask[TOP], mask[RIGHT], mask[BOTTOM], rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1 << TOP) != 0) {
// top
rotation[count] = -detectEdgeRotation(0, 1, image, mask);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation top: [%d,%d,%d,%d]: %f\n", mask[LEFT],
mask[TOP], mask[RIGHT], mask[BOTTOM], rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1 << RIGHT) != 0) {
// right
rotation[count] = detectEdgeRotation(-1, 0, image, mask);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation right: [%d,%d,%d,%d]: %f\n", mask[LEFT],
mask[TOP], mask[RIGHT], mask[BOTTOM], rotation[count]);
}
count++;
}
if ((deskewScanEdges & 1 << BOTTOM) != 0) {
// bottom
rotation[count] = -detectEdgeRotation(0, -1, image, mask);
if (verbose >= VERBOSE_NORMAL) {
printf("detected rotation bottom: [%d,%d,%d,%d]: %f\n", mask[LEFT],
mask[TOP], mask[RIGHT], mask[BOTTOM], rotation[count]);
}
count++;
}
total = 0.0;
for (int i = 0; i < count; i++) {
total += rotation[i];
}
average = total / count;
total = 0.0;
for (int i = 0; i < count; i++) {
total += powf(rotation[i] - average, 2);
}
deviation = sqrtf(total);
if (verbose >= VERBOSE_NORMAL) {
printf("rotation average: %f deviation: %f rotation-scan-deviation "
"(maximum): %f [%d,%d,%d,%d]\n",
average, deviation, deskewScanDeviationRad, mask[LEFT], mask[TOP],
mask[RIGHT], mask[BOTTOM]);
}
if (deviation <= deskewScanDeviationRad) {
return average;
} else {
if (verbose >= VERBOSE_NONE) {
printf("out of deviation range - NO ROTATING\n");
}
return 0.0;
}
}
/**
* Nearest-neighbour interpolation.
*/
static int nearest(float x, float y, AVFrame *source) {
// Round to nearest location.
int x1 = (int)roundf(x);
int y1 = (int)roundf(y);
return getPixel(x1, y1, source);
}
/**
* 1-D cubic interpolation. Clamps the return value between 0 and 255 to
* support 8-bit colour images.
*/
static int cubic(float x, int a, int b, int c, int d) {
int result = b + 0.5f * x *
(c - a +
x * (2.0f * a - 5.0f * b + 4.0f * c - d +
x * (3.0f * (b - c) + d - a)));
if (result > 255)
result = 255;
if (result < 0)
result = 0;
return result;
}
/**
* 1-D cubic interpolation
* This function expects (and returns) colour pixel values.
*/
static int cubicPixel(float x, int a, int b, int c, int d) {
int red = cubic(x, red(a), red(b), red(c), red(d));
int green = cubic(x, green(a), green(b), green(c), green(d));
int blue = cubic(x, blue(a), blue(b), blue(c), blue(d));
return pixelValue(red, green, blue);
}
/**
* 2-D bicubic interpolation
*/
static int bicubicInterpolate(float x, float y, AVFrame *source) {
int fx = (int)x;
int fy = (int)y;
int v[4];
for (int i = -1; i < 3; ++i) {
v[i + 1] = cubicPixel(
x - fx, getPixel(fx - 1, fy + i, source), getPixel(fx, fy + i, source),
getPixel(fx + 1, fy + i, source), getPixel(fx + 2, fy + i, source));
}
return cubicPixel(y - fy, v[0], v[1], v[2], v[3]);
}
/**
* 1-D linear interpolation.
*/
static int linear(float x, int a, int b) { return (1.0f - x) * a + x * b; }
/**
* 1-D linear interpolation
* This function expects (and returns) colour pixel values.
*/
static int linearPixel(float x, int a, int b) {
int red = linear(x, red(a), red(b));
int green = linear(x, green(a), green(b));
int blue = linear(x, blue(a), blue(b));
return pixelValue(red, green, blue);
}
/**
* 2-D bilinear interpolation
*/
static int bilinearInterpolate(float x, float y, AVFrame *source) {
int x1 = (int)x;
int x2 = (int)ceilf(x);
int y1 = (int)y;
int y2 = (int)ceilf(y);
// Check edge conditions to avoid divide-by-zero
if (x2 > source->width || y2 > source->height)
return getPixel(x, y, source);
else if (x2 == x1 && y2 == y1)
return getPixel(x, y, source);
else if (x2 == x1) {
int p1 = getPixel(x1, y1, source);
int p2 = getPixel(x1, y2, source);
return linearPixel(y - y1, p1, p2);
} else if (y2 == y1) {
int p1 = getPixel(x1, y1, source);
int p2 = getPixel(x2, y1, source);
return linearPixel(x - x1, p1, p2);
}
int pixel1 = getPixel(x1, y1, source);
int pixel2 = getPixel(x2, y1, source);
int pixel3 = getPixel(x1, y2, source);
int pixel4 = getPixel(x2, y2, source);
int val1 = linearPixel(x - x1, pixel1, pixel2);
int val2 = linearPixel(x - x1, pixel3, pixel4);
return linearPixel(y - y1, val1, val2);
}
/**
* 2-D bilinear interpolation
* The method chosen depends on the global interpolateType variable.
*/
static int interpolate(float x, float y, AVFrame *source) {
if (interpolateType == INTERP_NN) {
return nearest(x, y, source);
} else if (interpolateType == INTERP_LINEAR) {
return bilinearInterpolate(x, y, source);
} else {
return bicubicInterpolate(x, y, source);
}
}
/**
* Rotates a whole image buffer by the specified radians, around its
* middle-point. (To rotate parts of an image, extract the part with copyBuffer,
* rotate, and re-paste with copyBuffer.)
*/
void rotate(const float radians, AVFrame *source, AVFrame *target) {
const int w = source->width;
const int h = source->height;
// create 2D rotation matrix
const float sinval = sinf(radians);
const float cosval = cosf(radians);
const float midX = w / 2.0f;
const float midY = h / 2.0f;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
const float srcX = midX + (x - midX) * cosval + (y - midY) * sinval;
const float srcY = midY + (y - midY) * cosval - (x - midX) * sinval;
const int pixel = interpolate(srcX, srcY, source);
setPixel(pixel, x, y, target);
}
}
}
/* --- stretching / resizing / shifting ------------------------------------ */
static void stretchTo(AVFrame *source, AVFrame *target) {
const float xRatio = source->width / (float)target->width;
const float yRatio = source->height / (float)target->height;
if (verbose >= VERBOSE_MORE) {
printf("stretching %dx%d -> %dx%d\n", source->width, source->height,
target->width, target->height);
}
for (int y = 0; y < target->height; y++) {
for (int x = 0; x < target->width; x++) {
// calculate average pixel value in source matrix
const int pixel = interpolate(x * xRatio, y * yRatio, source);
setPixel(pixel, x, y, target);
}
}
}
void stretch(int w, int h, AVFrame **image) {
AVFrame *newimage;
if ((*image)->width == w && (*image)->height == h)
return;
// allocate new buffer's memory
initImage(&newimage, w, h, (*image)->format, false);
stretchTo(*image, newimage);
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, AVFrame **image) {
AVFrame *stretched, *resized;
int ww;
int hh;
float wRat = (float)w / (*image)->width;
float hRat = (float)h / (*image)->height;
if (verbose >= VERBOSE_NORMAL) {
printf("resizing %dx%d -> %dx%d\n", (*image)->width, (*image)->height, w,
h);
}
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;
}
initImage(&stretched, ww, hh, (*image)->format, true);
stretchTo(*image, stretched);
// Check if any centering needs to be done, otherwise make a new
// copy, center and return that. Check for the stretched
// width/height to be the same rather than comparing the ratio, as
// it is possible that the ratios are just off enough that they
// generate the same width/height.
if ((ww == w) && (hh = h)) {
// don't create one more buffer if the size is the same.
resized = stretched;
} else {
initImage(&resized, w, h, (*image)->format, true);
centerImage(stretched, 0, 0, w, h, resized);
av_frame_free(&stretched);
}
replaceImage(image, &resized);
}
/**
* Shifts the image.
*
* @param shiftX horizontal shifting
* @param shiftY vertical shifting
*/
void shift(int shiftX, int shiftY, AVFrame **image) {
AVFrame *newimage;
// allocate new buffer's memory
initImage(&newimage, (*image)->width, (*image)->height, (*image)->format,
true);
for (int y = 0; y < (*image)->height; y++) {
for (int x = 0; x < (*image)->width; x++) {
const int pixel = getPixel(x, y, *image);
setPixel(pixel, x + shiftX, y + shiftY, newimage);
}
}
replaceImage(image, &newimage);
}
/* --- mask-detection ----------------------------------------------------- */
/**
* Finds one edge of non-black pixels heading 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, AVFrame *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;
unsigned int total = 0;
unsigned 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 uint8_t blackness =
inverseBrightnessRect(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, AVFrame *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[][]
*/
void detectMasks(AVFrame *image) {
int left;
int top;
int right;
int bottom;
maskCount = 0;
if (maskScanDirections != 0) {
for (int 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]);
}
}
}
}
}
/**
* Permanently applies image masks. Each pixel which is not covered by at least
* one mask is set to maskColor.
*/
void applyMasks(Mask *masks, const int masksCount,
AVFrame *image) {
if (masksCount <= 0) {
return;
}
for (int y = 0; y < image->height; y++) {
for (int x = 0; x < image->width; x++) {
// in any mask?
bool m = false;
for (int i = 0; i < masksCount; i++) {
m = m || inMask(x, y, masks[i]);
}
if (m == false) {
setPixel(maskColor, x, y, image);
}
}
}
}
/* --- wiping ------------------------------------------------------------- */
/**
* Permanently wipes out areas of an images. Each pixel covered by a wipe-area
* is set to wipeColor.
*/
void applyWipes(Mask *area, int areaCount,
AVFrame *image) {
for (int i = 0; i < areaCount; i++) {
int count = 0;
for (int y = area[i][TOP]; y <= area[i][BOTTOM]; y++) {
for (int x = area[i][LEFT]; x <= area[i][RIGHT]; x++) {
if (setPixel(maskColor, 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, AVFrame *image) {
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 (int 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 (int 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, AVFrame **image) {
AVFrame *newimage;
// exchanged width and height
initImage(&newimage, (*image)->height, (*image)->width, (*image)->format,
false);
for (int y = 0; y < (*image)->height; y++) {
const int xx = ((direction > 0) ? (*image)->height - 1 : 0) - y * direction;
for (int 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,
unsigned int absBlackfilterScanThreshold,
Mask *exclude,
int excludeCount, int intensity, AVFrame *image) {
int left;
int top;
int right;
int bottom;
int shiftX;
int shiftY;
int l, t, r, b;
int diffX;
int diffY;
bool alreadyExcludedMessage;
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"
uint8_t blackness = darknessRect(l, t, r, b, image);
if (blackness >=
absBlackfilterScanThreshold) { // found a solidly black area
Mask mask = {l, t, r, 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 (int y = t; y <= b; y++) {
for (int x = l; x <= r; x++) {
floodFill(x, y, WHITE24, 0, absBlackThreshold, 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 messages
}
}
}
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(AVFrame *image) {
if ((blackfilterScanDirections & 1 << HORIZONTAL) !=
0) { // left-to-right scan
blackfilterScan(blackfilterScanStep[HORIZONTAL], 0,
blackfilterScanSize[HORIZONTAL],
blackfilterScanDepth[HORIZONTAL],
absBlackfilterScanThreshold, blackfilterExclude,
blackfilterExcludeCount, blackfilterIntensity, image);
}
if ((blackfilterScanDirections & 1 << VERTICAL) != 0) { // top-to-bottom scan
blackfilterScan(0, blackfilterScanStep[VERTICAL],
blackfilterScanSize[VERTICAL],
blackfilterScanDepth[VERTICAL], absBlackfilterScanThreshold,
blackfilterExclude, blackfilterExcludeCount,
blackfilterIntensity, image);
}
}
/* --- noisefilter -------------------------------------------------------- */
/**
* Applies a simple noise filter to the image.
*
* @param intensity maximum cluster size to delete
*/
int noisefilter(AVFrame *image) {
int count;
int neighbors;
count = 0;
for (int y = 0; y < image->height; y++) {
for (int x = 0; x < image->width; x++) {
uint8_t pixel = getPixelDarknessInverse(x, y, image);
if (pixel < absWhiteThreshold) { // one dark pixel found
neighbors = countPixelNeighbors(
x, y, noisefilterIntensity, absWhiteThreshold,
image); // get number of non-light pixels in neighborhood
if (neighbors <=
noisefilterIntensity) { // ...not more than 'intensity'?
clearPixelNeighbors(x, y, absWhiteThreshold, image); // delete area
count++;
}
}
}
}
return count;
}
/* --- blurfilter --------------------------------------------------------- */
/**
* Removes noise using a kind of blurfilter, as alternative to the noise
* filter. This algorithm counts pixels while 'shaking' the area to detect,
* and clears the area if the amount of white pixels exceeds whiteTreshold.
*/
int blurfilter(AVFrame *image) {
const int blocksPerRow = image->width / blurfilterScanSize[HORIZONTAL];
const int total = blurfilterScanSize[HORIZONTAL] *
blurfilterScanSize[VERTICAL]; // Number of pixels in a block
int top = 0;
int right = blurfilterScanSize[HORIZONTAL] - 1;
int bottom = blurfilterScanSize[VERTICAL] - 1;
int maxLeft = image->width - blurfilterScanSize[HORIZONTAL];
int maxTop = image->height - blurfilterScanSize[VERTICAL];
int result = 0;
// Number of dark pixels in previous row
// allocate one extra block left and right
int *prevCounts = calloc(blocksPerRow + 2, sizeof(int));
// Number of dark pixels in current row
int *curCounts = calloc(blocksPerRow + 2, sizeof(int));
// Number of dark pixels in next row
int *nextCounts = calloc(blocksPerRow + 2, sizeof(int));
for (int left = 0, block = 1; left <= maxLeft;
left += blurfilterScanSize[HORIZONTAL]) {
curCounts[block] = countPixelsRect(left, top, right, bottom, 0,
absWhiteThreshold, false, image);
block++;
right += blurfilterScanSize[HORIZONTAL];
}
curCounts[0] = total;
curCounts[blocksPerRow] = total;
nextCounts[0] = total;
nextCounts[blocksPerRow] = total;
// Loop through all blocks. For a block calculate the number of dark pixels in
// this block, the number of dark pixels in the block in the top-left corner
// and similarly for the block in the top-right, bottom-left and bottom-right
// corner. Take the maximum of these values. Clear the block if this number is
// not large enough compared to the total number of pixels in a block.
for (int top = 0; top <= maxTop; top += blurfilterScanSize[HORIZONTAL]) {
right = blurfilterScanSize[HORIZONTAL] - 1;