public ArrayList Mat findRectangles Mat src Size minSizes Size maxSize

 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
public ArrayList<Mat> findRectangles(Mat src, Size minSizes, Size maxSizes) {
Mat grayImage = new Mat();
Imgproc.cvtColor(src, grayImage, Imgproc.COLOR_BGR2GRAY);
Mat denoisingImage = new Mat();
Photo.fastNlMeansDenoising(grayImage, denoisingImage);
Mat histogramEqualizationImage = new Mat();
Imgproc.equalizeHist(denoisingImage, histogramEqualizationImage);
Mat morphologicalOpeningImage = new Mat();
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Imgproc.morphologyEx(histogramEqualizationImage, morphologicalOpeningImage, Imgproc.MORPH_RECT, kernel);
Mat subtractImage = new Mat();
Core.subtract(histogramEqualizationImage, morphologicalOpeningImage, subtractImage);
Mat thresholdImage = new Mat();
double threshold = Imgproc.threshold(subtractImage, thresholdImage, 50, 255, Imgproc.THRESH_OTSU);
thresholdImage.convertTo(thresholdImage, CvType.CV_16SC1);
Mat edgeImage = new Mat();
thresholdImage.convertTo(thresholdImage, CvType.CV_8U);
Imgproc.Canny(thresholdImage, edgeImage, threshold, threshold * 3, 3, true);
Mat dilatedImage = new Mat();
Imgproc.dilate(thresholdImage, dilatedImage, kernel);
ArrayList<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(dilatedImage, contours, new Mat(), Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
contours.sort(Collections.reverseOrder(Comparator.comparing(Imgproc::contourArea)));
ArrayList<Mat> findedRects = new ArrayList<>();
for (MatOfPoint contour: contours.subList(0, 10)) {
System.out.println(Imgproc.contourArea(contour));
MatOfPoint2f point2f = new MatOfPoint2f();
MatOfPoint2f approxContour2f = new MatOfPoint2f();
MatOfPoint approxContour = new MatOfPoint();
contour.convertTo(point2f, CvType.CV_32FC2);
double arcLenght = Imgproc.arcLength(point2f, true);
Imgproc.approxPolyDP(point2f, approxContour2f, arcLenght * 0.03, true);
approxContour2f.convertTo(approxContour, CvType.CV_32S);
Rect rect = Imgproc.boundingRect(approxContour);
if((rect.height > minSizes.height && rect.height < maxSizes.height)&&
(rect.width > minSizes.width && rect.width < maxSizes.width)) {
double ratio = (double)rect.height / rect.width;
Mat submat = src.submat(rect);
Imgproc.resize(submat, submat, new Size(400, 400 * ratio));
findedRects.add(submat);
}
}
return findedRects;
}