-
Notifications
You must be signed in to change notification settings - Fork 5
/
Img.java
1018 lines (877 loc) · 32.2 KB
/
Img.java
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
package org.genericsystem.cv;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import org.genericsystem.cv.utils.Tools;
import org.genericsystem.layout.Layout;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.KeyPoint;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.features2d.FeatureDetector;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.CLAHE;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.HOGDescriptor;
import org.opencv.photo.Photo;
import org.opencv.utils.Converters;
import org.opencv.ximgproc.Ximgproc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Img implements AutoCloseable, Serializable {
private static Logger log = LoggerFactory.getLogger(Img.class);
private final Mat src;
public Mat getSrc() {
return src;
}
public Img(String path) {
this(Imgcodecs.imread(path), false);
}
public Img(Mat src) {
this(src, true);
}
public Img(Mat src, boolean clone) {
if (clone) {
this.src = new Mat();
src.copyTo(this.src);
} else
this.src = src;
}
public Img(Img model, Zone zone) {
this.src = new Mat(model.getSrc(), zone.getRect());
}
public Img(Img model, Layout shard) {
this.src = new Mat(model.getSrc(), new Rect(new Point(shard.getX1() * model.width(), shard.getY1() * model.height()), new Point(shard.getX2() * model.width(), shard.getY2() * model.height())));
}
public Img morphologyEx(int morphOp, int morph, Size size) {
Mat result = new Mat();
Imgproc.morphologyEx(src, result, morphOp, Imgproc.getStructuringElement(morph, size));
// // Imgproc.morphologyEx(src, result, morphOp, Imgproc.getStructuringElement(morph, size), new Point(-1, -1), 1, Core.BORDER_CONSTANT, new Scalar(255));
return new Img(result, false);
}
public Img laplacian() {
return laplacian(CvType.CV_8U);
}
public Img laplacian(int ddepth) {
Mat result = new Mat();
Imgproc.Laplacian(src, result, ddepth);
return new Img(result, false);
}
public List<MatOfPoint> findContours(Img[] hierarchy, int mode, int method) {
Mat mat = new Mat();
List<MatOfPoint> result = new ArrayList<>();
Imgproc.findContours(src, result, mat, mode, method);
hierarchy[0] = new Img(mat, false);
return result;
}
public List<MatOfPoint> findContours(Img[] hierarchy, int mode, int method, Point point) {
Mat mat = new Mat();
List<MatOfPoint> result = new ArrayList<>();
Imgproc.findContours(src, result, mat, mode, method, point);
hierarchy[0] = new Img(mat, false);
return result;
}
public Img dilate(Mat kernel) {
Mat result = new Mat();
Imgproc.dilate(src, result, kernel);
return new Img(result, false);
}
public Img canny(double threshold1, double threshold2) {
Mat result = new Mat();
Imgproc.Canny(src, result, threshold1, threshold2);
return new Img(result, false);
}
public Img canny(double threshold1, double threshold2, int apertureSize, boolean L2gradient) {
Mat result = new Mat();
Imgproc.Canny(src, result, threshold1, threshold2, apertureSize, L2gradient);
return new Img(result, false);
}
public void drawContours(List<MatOfPoint> contours, int contourIdx, Scalar color, int thickness) {
Imgproc.drawContours(src, contours, contourIdx, color, thickness);
}
public Img gaussianBlur(Size ksize, double sigmaX, double sigmaY) {
Mat result = new Mat();
Imgproc.GaussianBlur(src, result, ksize, sigmaX, sigmaY);
return new Img(result, false);
}
public Img medianBlur(int ksize) {
Mat result = new Mat();
Imgproc.medianBlur(src, result, ksize);
return new Img(result, false);
}
public Img bgr2Gray() {
Mat result = new Mat();
Imgproc.cvtColor(src, result, Imgproc.COLOR_BGR2GRAY);
return new Img(result, false);
}
private static double angle(Point p1, Point p2, Point p0) {
double dx1 = p1.x - p0.x;
double dy1 = p1.y - p0.y;
double dx2 = p2.x - p0.x;
double dy2 = p2.y - p0.y;
return (dx1 * dx2 + dy1 * dy2) / Math.sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10);
}
public Img cropAndDeskew() {
Img blurred = medianBlur(9);
Img gray;
if (src.channels() == 1)
gray = blurred;
else
gray = blurred.bgr2Gray();
Img gray_;
List<MatOfPoint> contours = new ArrayList<>();
double maxArea = 0;
int maxId = -1;
MatOfPoint2f maxContour = null;
gray_ = gray.canny(10, 20, 3, true);
gray_ = gray_.dilate(Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(12, 12)));
contours = gray_.findContours(new Img[1], Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
for (MatOfPoint contour : contours) {
MatOfPoint2f temp = new MatOfPoint2f(contour.toArray());
double area = Imgproc.contourArea(contour);
MatOfPoint2f approxCurve = new MatOfPoint2f();
Imgproc.approxPolyDP(temp, approxCurve, Imgproc.arcLength(temp, true) * 0.02, true);
if (approxCurve.total() == 4 && area >= maxArea) {
double maxCosine = 0;
List<Point> curves = approxCurve.toList();
for (int j = 2; j < 5; j++) {
double cosine = Math.abs(angle(curves.get(j % 4), curves.get(j - 2), curves.get(j - 1)));
maxCosine = Math.max(maxCosine, cosine);
}
if (maxCosine < 0.3) {
maxArea = area;
maxId = contours.indexOf(contour);
maxContour = approxCurve;
}
}
}
Img result;
if (maxId >= 0)
result = transform(maxContour);
else
result = new Img(src);
// TODO: Warning if no contour found.
blurred.close();
gray.close();
gray_.close();
return result;
}
public Img transform(MatOfPoint2f contour2f) {
List<Point> list = new ArrayList<>(Arrays.asList(contour2f.toArray()));
// Put the points in counterclockwise order.
if (isClockwise(list)) {
Point second = list.remove(3);
Point fourth = list.remove(1);
list.add(1, second);
list.add(fourth);
}
// Look for the top left corner of the rectangle.
// The line used as the top of the rectangle makes an angle of 45° max
// with an horizontal line.
int yMinIndex = 0; // Point with min y, and min x if there are two such
// points.
int xMinIndex = 0; // Point with min x, and min y if there are two such
// points.
for (int i = 0; i < list.size(); i++) {
double xCurr = list.get(i).x;
double xMin = list.get(xMinIndex).x;
double yCurr = list.get(i).y;
double yMin = list.get(yMinIndex).y;
if (xCurr < xMin || xCurr == xMin && yCurr < list.get(xMinIndex).y)
xMinIndex = i;
if (yCurr < yMin || yCurr == yMin && xCurr < list.get(yMinIndex).x)
yMinIndex = i;
}
int tlIndex = yMinIndex;
if (yMinIndex != xMinIndex) {
double slope = (list.get(xMinIndex).y - list.get(yMinIndex).y) / (list.get(yMinIndex).x - list.get(xMinIndex).x);
if (slope < 1)
tlIndex = xMinIndex;
}
// Put the top left corner first.
for (int i = 0; i < tlIndex; i++)
list.add(list.remove(0));
// Transform the image.
double height = distance(list.get(0), list.get(1));
double width = distance(list.get(1), list.get(2));
Mat target = new Mat();
List<Point> targets = new LinkedList<>(Arrays.asList(new Point(0, 0), new Point(0, height), new Point(width, height), new Point(width, 0)));
Imgproc.warpPerspective(src, target, Imgproc.getPerspectiveTransform(Converters.vector_Point2f_to_Mat(list), Converters.vector_Point2f_to_Mat(targets)), new Size(width, height), Imgproc.INTER_CUBIC);
Img result = new Img(target, false);
int orientation = result.getOrientation();
if (orientation != 0)
result = result.rotate(orientation);
return result;
}
private double distance(Point p1, Point p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
// angle is 90, 180 or 270 degrees
public Img rotate(int angle) {
Mat result = new Mat();
if (angle == 90) {
Core.transpose(src, result);
Core.flip(result, result, 0);
}
if (angle == 180)
Core.flip(src, result, -1);
if (angle == 270) {
Core.transpose(src, result);
Core.flip(result, result, 1);
}
return new Img(result, false);
}
// List of points corresponding to the ordered vertices of a convex polygon.
private boolean isClockwise(List<Point> points) {
Point p1 = points.get(0);
Point p2 = points.get(1);
Point p3 = points.get(2);
// The points are in clockwise order iff the determinant of the vectors
// p1p2 and p2p3 is positive. (/!\ clockwise basis)
return (p2.x - p1.x) * (p3.y - p2.y) - (p2.y - p1.y) * (p3.x - p2.x) >= 0;
}
public int getOrientation() {
try {
File tmpFile = File.createTempFile("orientation", ".png");
tmpFile.deleteOnExit();
Imgcodecs.imwrite(tmpFile.toString(), src);
Process process = Runtime.getRuntime().exec(new String[] { "../gs-cv/orientation.sh", tmpFile.toString() });
process.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
return Integer.valueOf(stdInput.readLine());
} catch (IOException | InterruptedException e) {
log.warn("Impossible to detect file orientation, returning 0.", e);
return 0;
}
}
public Size size() {
return src.size();
}
public int height() {
return src.height();
}
public int width() {
return src.width();
}
public double[] get(int row, int col) {
return src.get(row, col);
}
public Img cvtColor(int code) {
Mat result = new Mat();
Imgproc.cvtColor(src, result, code);
return new Img(result, false);
}
public ImageIcon getImageIcon() {
return new ImageIcon(Tools.mat2bufferedImage(src));
}
public void rectangle(Rect rect, Scalar color, int thickNess) {
Imgproc.rectangle(src, rect.br(), rect.tl(), color, thickNess);
}
public ImageView getImageView() {
return getImageView(AbstractApp.displayWidth);
}
public ImageView getImageView(double width) {
Mat conv = new Mat();
src.convertTo(conv, CvType.CV_8UC1);
Mat target = new Mat();
Imgproc.resize(conv, target, new Size(width, Math.floor((width / conv.width()) * conv.height())));
MatOfByte buffer = new MatOfByte();
Imgcodecs.imencode(".png", target, buffer);
ImageView imageView = new ImageView(new Image(new ByteArrayInputStream(buffer.toArray())));
imageView.setPreserveRatio(true);
imageView.setFitWidth(width);
return imageView;
}
public int channels() {
return src.channels();
}
public Img range(Scalar scalar, Scalar scalar2, boolean hsv) {
Img ranged = this;
if (hsv)
ranged = ranged.cvtColor(Imgproc.COLOR_BGR2HSV);
Mat result = new Mat(ranged.size(), ranged.type(), new Scalar(0, 0, 0));
Mat mask = new Mat();
Core.inRange(ranged.getSrc(), scalar, scalar2, mask);
ranged.getSrc().copyTo(result, mask);
Img resultImg = new Img(result, false);
if (hsv)
resultImg = resultImg.cvtColor(Imgproc.COLOR_HSV2BGR);
return resultImg;
}
public int type() {
return src.type();
}
public Img gaussianBlur(Size size) {
Mat result = new Mat();
Imgproc.GaussianBlur(src, result, size, 0);
return new Img(result, false);
}
public Img multiply(Scalar scalar) {
Mat result = new Mat();
Core.multiply(src, scalar, result);
return new Img(result, false);
}
public Img mser() {
Img gray = bgr2Gray();
MatOfKeyPoint keypoint = new MatOfKeyPoint();
FeatureDetector detector = FeatureDetector.create(FeatureDetector.MSER);
detector.detect(gray.getSrc(), keypoint);
List<KeyPoint> listpoint = keypoint.toList();
Mat result = Mat.zeros(gray.size(), CvType.CV_8UC1);
for (int ind = 0; ind < listpoint.size(); ind++) {
KeyPoint kpoint = listpoint.get(ind);
int rectanx1 = (int) (kpoint.pt.x - 0.5 * kpoint.size);
int rectany1 = (int) (kpoint.pt.y - 0.5 * kpoint.size);
int width = (int) (kpoint.size);
int height = (int) (kpoint.size);
if (rectanx1 <= 0)
rectanx1 = 1;
if (rectany1 <= 0)
rectany1 = 1;
if ((rectanx1 + width) > gray.width())
width = gray.width() - rectanx1;
if ((rectany1 + height) > gray.height())
height = gray.height() - rectany1;
Rect rectant = new Rect(rectanx1, rectany1, width, height);
Mat roi = new Mat(result, rectant);
roi.setTo(new Scalar(255));
}
Img img = new Img(result, false);
Img result_ = img.morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(17, 3));
img.close();
return result_;
}
public Img grad(double k1, double k2) {
// Img gray = bgr2Gray();
Img grad = morphologyEx(Imgproc.MORPH_GRADIENT, Imgproc.MORPH_RECT, new Size(k1, k2));
return grad;
// return grad.thresHold(0.0, 255.0, Imgproc.THRESH_OTSU + Imgproc.THRESH_BINARY);
// return threshold.morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(17, 3));
}
// public Img classic() {
// Img gray = gray();
// Img threshold = gray.thresHold(0, 255, Imgproc.THRESH_OTSU +
// Imgproc.THRESH_BINARY);
// return threshold.morphologyEx(Imgproc.MORPH_CLOSE, new
// StructuringElement(Imgproc.MORPH_RECT, new Size(17, 3)));
// }
public Img sobel() {
Img gray = bgr2Gray();
Img sobel = gray.sobel(CvType.CV_8UC1, 3, 0, 5, 1, 10, Core.BORDER_DEFAULT);
// Img threshold = sobel.thresHold(0, 255, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU);
return sobel;
}
public Img bernsen() {
return bernsen(31, 15);
}
public Img otsu() {
return bgr2Gray().thresHold(0, 255, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU);
}
public Img otsuAfterGaussianBlur() {
return otsuAfterGaussianBlur(new Size(5, 5));
}
public Img otsuInv() {
return bgr2Gray().thresHold(0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
}
public Img equalizeHisto() {
Mat result = new Mat();
List<Mat> channels = new ArrayList<>();
Core.split(src, channels);
Imgproc.equalizeHist(channels.get(0), channels.get(0));
Imgproc.equalizeHist(channels.get(1), channels.get(1));
Imgproc.equalizeHist(channels.get(2), channels.get(2));
Core.merge(channels, result);
for (Mat channel : channels)
channel.release();
return new Img(result, false);
}
public Img resize() {
Mat result = new Mat();
Imgproc.resize(src, result, new Size(50, 50), 10, 10, Imgproc.INTER_AREA);
return new Img(result, false);
}
public Img equalizeHistoAdaptative() {
CLAHE clahe = Imgproc.createCLAHE(2.0, new Size(8, 8));
Mat result = new Mat();
List<Mat> channels = new ArrayList<>();
Core.split(src, channels);
clahe.apply(channels.get(0), channels.get(0));
clahe.apply(channels.get(1), channels.get(1));
clahe.apply(channels.get(2), channels.get(2));
Core.merge(channels, result);
for (Mat channel : channels)
channel.release();
return new Img(result, false);
}
public Img equalizeHistoAdaptative2() {
return equalizeHistoAdaptative(2.0, new Size(8, 8));
}
public Img adaptativeMeanThreshold() {
return adaptativeMeanThreshold(11, 2);
}
public Img adaptativeGaussianThreshold() {
return adaptativeGaussianThreshold(11, 2);
}
public Img niblackThreshold() {
return niblackThreshold(17, 0.1);
}
public Img sauvolaThreshold() {
return sauvolaThreshold(17, 0.3);
}
public Img nickThreshold() {
return nickThreshold(11, 0.1);
}
public Img wolfThreshold() {
return wolfThreshold(11, 0.3);
}
// Equalize histograms using a Contrast Limited Adaptive Histogram
// Equalization algorithm
public Img equalizeHistoAdaptative(double clipLimit, Size titleGridSize) {
Mat result = new Mat();
Mat channelL = new Mat();
CLAHE clahe = Imgproc.createCLAHE(clipLimit, titleGridSize);
Core.extractChannel(result, channelL, 0);
clahe.apply(channelL, channelL);
Core.insertChannel(channelL, result, 0);
Imgproc.cvtColor(result, result, Imgproc.COLOR_Lab2BGR);
channelL.release();
return new Img(result, false);
}
public Img otsuAfterGaussianBlur(Size blurSize) {
// Same as otsu filtering, but a Gaussian blur is applied first
return bgr2Gray().gaussianBlur(blurSize).thresHold(0, 255, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU);
}
public Img sobel(int ddepth, int dx, int dy, int ksize, double scale, double delta, int borderType) {
Mat result = new Mat();
Imgproc.Sobel(src, result, ddepth, dx, dy, ksize, scale, delta, borderType);
return new Img(result, false);
}
public Img adaptativeThresHold(double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C) {
Mat result = new Mat();
Imgproc.adaptiveThreshold(src, result, maxValue, adaptiveMethod, thresholdType, blockSize, C);
return new Img(result, false);
}
public Img thresHold(double thresh, double maxval, int type) {
Mat result = new Mat();
Imgproc.threshold(src, result, thresh, maxval, type);
return new Img(result, false);
}
// TODO: make it faster (compute with integral image?)
public Img bernsen(int ksize, int contrast_limit) {
Img gray = bgr2Gray();
Mat ret = Mat.zeros(gray.size(), gray.type());
for (int i = 0; i < gray.cols(); i++) {
for (int j = 0; j < gray.rows(); j++) {
double mn = 999, mx = 0;
int ti = 0, tj = 0;
int tlx = i - ksize / 2;
int tly = j - ksize / 2;
int brx = i + ksize / 2;
int bry = j + ksize / 2;
if (tlx < 0)
tlx = 0;
if (tly < 0)
tly = 0;
if (brx >= gray.cols())
brx = gray.cols() - 1;
if (bry >= gray.rows())
bry = gray.rows() - 1;
for (int ik = -ksize / 2; ik <= ksize / 2; ik++) {
for (int jk = -ksize / 2; jk <= ksize / 2; jk++) {
ti = i + ik;
tj = j + jk;
if (ti > 0 && ti < gray.cols() && tj > 0 && tj < gray.rows()) {
double pix = gray.get(tj, ti)[0];
if (pix < mn)
mn = pix;
if (pix > mx)
mx = pix;
}
}
}
double median = 0.5 * (mn + mx);
if (median < contrast_limit) {
ret.put(j, i, 0);
} else {
double pix = gray.get(j, i)[0];
ret.put(j, i, pix > median ? 255 : 0);
}
}
}
return new Img(ret, false);
}
public int rows() {
return src.rows();
}
public int cols() {
return src.cols();
}
public Img dilateBlacks(double valueThreshold, double saturatioThreshold, double blueThreshold, Size dilatation) {
return range(new Scalar(0, 0, 0), new Scalar(255, saturatioThreshold, valueThreshold), true).range(new Scalar(0, 0, 0), new Scalar(blueThreshold, 255, 255), false).morphologyEx(Imgproc.MORPH_DILATE, Imgproc.MORPH_RECT, dilatation);
}
public Img adaptativeMeanThreshold(int blockSize, double C) {
return bgr2Gray().adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, blockSize, C);
}
public Img adaptativeGaussianThreshold(int blockSize, double C) {
return bgr2Gray().adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, blockSize, C);
}
public Img adaptativeGaussianInvThreshold(int blockSize, double C) {
return bgr2Gray().adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY_INV, blockSize, C);
}
public Img niblackThreshold(int blockSize, double k) {
Mat result = new Mat();
Ximgproc.niBlackThreshold(bgr2Gray().getSrc(), result, 255, Imgproc.THRESH_BINARY, blockSize, k, Ximgproc.BINARIZATION_NIBLACK);
return new Img(result, false);
}
public Img sauvolaThreshold(int blockSize, double k) {
Mat result = new Mat();
Ximgproc.niBlackThreshold(bgr2Gray().getSrc(), result, 255, Imgproc.THRESH_BINARY_INV, blockSize, k, Ximgproc.BINARIZATION_SAUVOLA);
return new Img(result, false);
}
public Img nickThreshold(int blockSize, double k) {
Mat result = new Mat();
Ximgproc.niBlackThreshold(bgr2Gray().getSrc(), result, 255, Imgproc.THRESH_BINARY, blockSize, k, Ximgproc.BINARIZATION_NICK);
return new Img(result, false);
}
public Img wolfThreshold(int blockSize, double k) {
Mat result = new Mat();
Ximgproc.niBlackThreshold(bgr2Gray().getSrc(), result, 255, Imgproc.THRESH_BINARY_INV, blockSize, k, Ximgproc.BINARIZATION_WOLF);
return new Img(result, false);
}
public Img resize(Size size) {
Mat result = new Mat();
Imgproc.resize(src, result, size);
return new Img(result, false);
}
/**
* Resizes the image so that the larger side’s length is equal to maxLength, preserving the proportions. Does nothing if both sides of the original image are smaller than maxLength.
*
* @param maxLength
* The maximum side length of the resized image.
* @return This if no change was made, a resized image otherwise.
*/
public Img resize(int maxLength) {
if (src.width() <= maxLength && src.height() <= maxLength)
return this;
if (src.width() >= src.height())
return resize(new Size(maxLength, src.height() * maxLength / src.width()));
return resize(new Size(src.width() * maxLength / src.height(), maxLength));
}
public Img resize(double coeff) {
Mat result = new Mat();
Imgproc.resize(src, result, new Size(src.width() * coeff, src.height() * coeff));
return new Img(result, false);
}
public Img bilateralFilter(int d, double sigmaColor, double sigmaSpace) {
Mat result = new Mat();
Imgproc.bilateralFilter(src, result, d, sigmaColor, sigmaSpace);
return new Img(result, false);
}
public Img bilateralFilter() {
return bilateralFilter(10, 80, 80);
}
public Img distanceTransform() {
Mat result = new Mat();
Imgproc.distanceTransform(src, result, Imgproc.DIST_L2, 5);
return new Img(result, false);
}
public Img absDiff(Img img) {
Mat result = new Mat();
Core.absdiff(src, img.getSrc(), result);
return new Img(result, false);
}
public Img absDiff(Scalar scalar) {
Mat result = new Mat();
Core.absdiff(src, scalar, result);
return new Img(result, false);
}
public Img hsvChannel(int channel) {
Mat result = new Mat();
Imgproc.cvtColor(src, result, Imgproc.COLOR_BGR2HSV);
List<Mat> channels = new ArrayList<>();
Core.split(result, channels);
return new Img(channels.get(channel), false);
}
public Img bgrChannel(int channel) {
List<Mat> channels = new ArrayList<>();
Core.split(src, channels);
return new Img(channels.get(channel), false);
}
public Img eraseCorners(double proportion) {
Img result = new Img(src);
int width = Double.valueOf(src.width() * proportion).intValue();
int height = Double.valueOf(src.height() * proportion).intValue();
Mat roi = new Mat(result.getSrc(), new Rect(0, 0, width, height));
roi.setTo(new Scalar(255, 255, 255));
roi = new Mat(result.getSrc(), new Rect(0, src.height() - height, width, height));
roi.setTo(new Scalar(255, 255, 255));
roi = new Mat(result.getSrc(), new Rect(src.width() - width, src.height() - height, width, height));
roi.setTo(new Scalar(255, 255, 255));
roi = new Mat(result.getSrc(), new Rect(src.width() - width, 0, width, height));
roi.setTo(new Scalar(255, 255, 255));
return result;
}
public Img fastNlMeansDenoising() {
Mat result = new Mat();
Photo.fastNlMeansDenoising(src, result);
return new Img(result, false);
}
public int findBestHisto(List<Img> imgs) {
List<Map<Integer, Double>> results = new ArrayList<>();
for (Img img : imgs)
results.add(compareHistogramm(computeHistogramm(), img));
List<Integer> methods = Arrays.asList(Imgproc.HISTCMP_CORREL, Imgproc.HISTCMP_CHISQR, Imgproc.HISTCMP_INTERSECT, Imgproc.HISTCMP_BHATTACHARYYA, Imgproc.HISTCMP_CHISQR_ALT, Imgproc.HISTCMP_KL_DIV);
Map<Integer, Integer> mins = new HashMap<>();
for (Integer method : methods) {
double min = results.get(0).get(method);
int index = 0;
for (int i = 0; i < results.size(); i++) {
if (min > results.get(i).get(method)) {
min = results.get(i).get(method);
index = i;
// System.out.println("method=" + method + " index=" +
// index);
}
}
mins.put(index, mins.get(index) != null ? mins.get(index) + 1 : 1);
}
TreeMap<Integer, Integer> reverse = mins.entrySet().stream().collect(Collectors.toMap(entry -> entry.getValue(), entry -> entry.getKey(), (u, v) -> {
return u;
}, TreeMap::new));
// System.out.println("Number of algos : " +
// reverse.lastEntry().getKey());
return reverse.lastEntry().getValue();
}
public Mat computeHistogramm() {
MatOfInt channels = new MatOfInt(0, 1, 2);
MatOfInt histSize = new MatOfInt(8, 8, 8);
MatOfFloat ranges = new MatOfFloat(0, 256, 0, 256, 0, 256);
Mat rgb = cvtColor(Imgproc.COLOR_BGR2RGB).getSrc();
Mat hist = new Mat();
Imgproc.calcHist(Arrays.asList(rgb), channels, Mat.ones(rgb.size(), CvType.CV_8UC1), hist, histSize, ranges);
// Core.normalize(hist, hist, 0, 1, Core.NORM_MINMAX, -1, new Mat());
Core.normalize(hist, hist);
return hist;
}
public Map<Integer, Double> compareHistogramm(Mat histo, Img img) {
Map<Integer, Double> results = new HashMap<>();
List<Integer> methods = Arrays.asList(Imgproc.HISTCMP_CORREL, Imgproc.HISTCMP_CHISQR, Imgproc.HISTCMP_INTERSECT, Imgproc.HISTCMP_BHATTACHARYYA, Imgproc.HISTCMP_CHISQR_ALT, Imgproc.HISTCMP_KL_DIV);
for (int method : methods) {
double result = Imgproc.compareHist(histo, img.computeHistogramm(), method);
switch (method) {
case Imgproc.HISTCMP_CORREL:
result = -result;
break;
case Imgproc.HISTCMP_INTERSECT:
result = -result;
break;
}
results.put(method, result);
// System.out.println("for Algo " + method + " comparison : " +
// result + "\n");
}
// System.out.println("results : " + results);
return results;
}
public List<Boolean> projectVertically() {
Mat result = new Mat();
Core.reduce(getSrc(), result, 1, Core.REDUCE_SUM, CvType.CV_64F);
List<Double> histoVertical = new ArrayList<>();
Converters.Mat_to_vector_double(result, histoVertical);
return histoVertical.stream().map(value -> value != 0).collect(Collectors.toList());
}
public List<Boolean> projectHorizontally() {
Mat result = new Mat();
Core.reduce(getSrc(), result, 0, Core.REDUCE_SUM, CvType.CV_64F);
Core.transpose(result, result);
List<Double> histoHorizontal = new ArrayList<>();
Converters.Mat_to_vector_double(result, histoHorizontal);
return histoHorizontal.stream().map(value -> value != 0).collect(Collectors.toList());
}
private Img range(Scalar scalar, Scalar scalar2) {
Mat result = new Mat();
Core.inRange(getSrc(), scalar, scalar2, result);
return new Img(result, false);
}
public Img add(Img img) {
Mat result = new Mat();
Core.add(getSrc(), img.getSrc(), result);
return new Img(result, false);
}
public Img bitwise_and(Img img) {
Mat result = new Mat();
Core.bitwise_and(getSrc(), img.getSrc(), result);
return new Img(result, false);
}
public Img bitwise_or(Img img) {
Mat result = new Mat();
Core.bitwise_or(getSrc(), img.getSrc(), result);
return new Img(result, false);
}
public Img bitwise_xor(Img img) {
Mat result = new Mat();
Core.bitwise_xor(getSrc(), img.getSrc(), result);
return new Img(result, false);
}
public Img bitwise_not() {
Mat result = new Mat();
Core.bitwise_not(getSrc(), result);
return new Img(result, false);
}
public Img transpose() {
Mat result = new Mat();
Core.transpose(src, result);
return new Img(result, false);
}
public Img houghLinesP(double rho, double theta, int threshold) {
Mat result = new Mat();
Imgproc.HoughLinesP(src, result, rho, theta, threshold);
return new Img(result, false);
}
public Mat houghLinesP(int rho, double theta, int threshold, double mineLineLenght, double maxLineGap) {
Mat result = new Mat();
Imgproc.HoughLinesP(src, result, rho, theta, threshold, mineLineLenght, maxLineGap);
return result;
}
public Image toJfxImage() {
MatOfByte byteMat = new MatOfByte();
Imgcodecs.imencode(".bmp", getSrc(), byteMat);
return new Image(new ByteArrayInputStream(byteMat.toArray()));
}
public ImageView toJfxImageView() {
return new ImageView(toJfxImage());
}
public MatOfFloat getHogDescriptor() {
MatOfFloat imgDescriptor = new MatOfFloat();
HOGDescriptor hog = new HOGDescriptor(new Size(64, 64), new Size(16, 16), new Size(16, 16), new Size(16, 16), 4);
hog.compute(src, imgDescriptor);
return imgDescriptor;
}
@Override
public void close() {
src.release();
}
public Layout buildLayout() {
return this.buildLayout(new Size(0.04, 0.008), 5);
}
public Layout buildLayout(Size morph, int level) {
Layout root = new Layout(null, 0, 1, 0, 1).tighten(this);
return root.recursiveSplit(morph, level, root.getRoi(this));
}
public static void main(String[] args) {
System.out.println(Arrays.toString(open(Arrays.asList(true, true, false, true, true, false, true, false, true), 2)));
}
public static boolean[] close(List<Boolean> histo, int k) {
boolean[] closed = new boolean[histo.size()];
for (int i = 0; i < histo.size() - 1; i++)
if (histo.get(i) && !histo.get(i + 1)) {
for (int j = k + 1; j > 0; j--)
if (i + j < histo.size()) {
if (histo.get(i + j)) {
Arrays.fill(closed, i, i + j + 1, true);
i += j - 1;
break;
}
closed[i] = histo.get(i);
}
} else
closed[i] = histo.get(i);
if (!closed[histo.size() - 1])
closed[histo.size() - 1] = histo.get(histo.size() - 1);
return closed;
}
public static boolean[] open(List<Boolean> histo, int k) {
boolean[] closed = new boolean[histo.size()];
for (int i = 0; i < histo.size() - 1; i++)
if (!histo.get(i) && histo.get(i + 1)) {
for (int j = k + 1; j > 0; j--)
if (i + j < histo.size()) {
if (!histo.get(i + j)) {
Arrays.fill(closed, i, i + j + 1, false);
i += j - 1;
break;
}
closed[i] = histo.get(i);
}
} else
closed[i] = histo.get(i);
if (!closed[histo.size() - 1])
closed[histo.size() - 1] = histo.get(histo.size() - 1);
return closed;
}
private List<Boolean> getRow(int row) {
List<Boolean> result = new ArrayList<>(src.cols());
for (int col = 0; col < src.cols(); col++)
result.add(src.get(row, col)[0] != 0);
return result;
};
public List<Boolean> getCol(int col) {
List<Boolean> result = new ArrayList<>(src.rows());
for (int row = 0; row < src.rows(); row++)
result.add(src.get(row, col)[0] != 0);
return result;
};
public Img cleanTables(double close) {
Mat result = new Mat(src.size(), CvType.CV_8U, new Scalar(255));
boolean[][] hHistos = new boolean[src.cols()][src.rows()];
for (int col = 0; col < src.cols(); col++)
hHistos[col] = open(getCol(col), Long.valueOf(Math.round(close * src.rows())).intValue());
boolean[][] vHistos = new boolean[src.rows()][src.cols()];
for (int row = 0; row < src.rows(); row++)
vHistos[row] = open(getRow(row), Long.valueOf(Math.round(close * src.cols())).intValue());
for (int col = 0; col < src.cols(); col++)
for (int row = 0; row < src.rows(); row++)
result.put(row, col, getSrc().get(row, col)[0] != 0 ^ (hHistos[col][row] || vHistos[row][col]) ? 255 : 0);
return new Img(result, false);
// Img hImg = this.morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(close * getSrc().width(), 1));
// Img vImg = this.morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(1, close * getSrc().height()));
// return new Img(this.bitwise_xor(hImg.bitwise_and(vImg)).getSrc());
}
public Img cleanTablesInv(double close) {
Img hImg = this.morphologyEx(Imgproc.MORPH_OPEN, Imgproc.MORPH_RECT, new Size(close * getSrc().width(), 1));
Img vImg = this.morphologyEx(Imgproc.MORPH_OPEN, Imgproc.MORPH_RECT, new Size(1, close * getSrc().height()));
return new Img(this.bitwise_xor(hImg.bitwise_or(vImg)).getSrc());
}
public Img cleanFaces(double px, double py) {
Img result = new Img(getSrc());