Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Mat clonedMat = imgSource.clone();
- Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
- //convert the image to black and white does (8 bit)
- Imgproc.Canny(imgSource, imgSource, 50, 50);
- //apply gaussian blur to smoothen lines of dots
- Imgproc.GaussianBlur(imgSource, imgSource, new Size(5, 5), 5);
- //find the contours
- List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
- Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
- double maxArea = -1;
- int maxAreaIdx = -1;
- MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
- MatOfPoint2f approxCurve = new MatOfPoint2f();
- List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
- MatOfPoint2f maxCurve = new MatOfPoint2f();
- for (int idx = 0; idx < contours.size(); idx++) {
- temp_contour = contours.get(idx);
- double contourarea = Imgproc.contourArea(temp_contour);
- //compare this contour to the previous largest contour found
- if (contourarea > maxArea) {
- //check if this contour is a square
- MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() );
- int contourSize = (int)temp_contour.total();
- Imgproc.approxPolyDP(new_mat, approxCurve, contourSize*0.05, true);
- if (approxCurve.total() == 4) {
- maxCurve = approxCurve;
- maxArea = contourarea;
- maxAreaIdx = idx;
- largest_contours.add(temp_contour);
- MatOfPoint points = new MatOfPoint( approxCurve.toArray() );
- Rect rect = Imgproc.boundingRect(points);
- if(isDebug)
- {
- Imgproc.drawContours(clonedMat, contours, idx, new Scalar(0,0,255), 5);
- }
- }
- }
- }
- String temp_string = null;
- try
- {
- //BGR
- point1 = maxCurve.get(1, 0);
- p1 = new org.opencv.core.Point(point1[0]+30, point1[1]+30);
- //Imgproc.circle(clonedMat, p1, 20, new Scalar(255, 0, 0), 5); //blue
- temp_string = "Point 1: (" + p1.x + ", " + p1.y + ")";
- point2 = maxCurve.get(0, 0);
- p2 = new org.opencv.core.Point(point2[0]-30, point2[1]+30);
- //Imgproc.circle(clonedMat, p2, 20, new Scalar(0, 255, 0), 5);//green
- temp_string += "\nPoint 2: (" + p2.x + ", " + p2.y + ")";
- point3 = maxCurve.get(3, 0);
- p3 = new org.opencv.core.Point(point3[0]-50, point3[1]-50);
- //Imgproc.circle(clonedMat, p3, 20, new Scalar(0, 0, 255), 5);//red
- temp_string += "\nPoint 3: (" + p3.x + ", " + p3.y + ")";
- point4 = maxCurve.get(2, 0);
- p4 = new org.opencv.core.Point(point4[0]+50, point4[1]-50);
- //Imgproc.circle(clonedMat, p4, 20, new Scalar(0, 255, 255), 5); // yellow
- temp_string += "\nPoint 4: (" + p4.x + ", " + p4.y + ")";
- }catch (NullPointerException e)
- {
- this.cancel(true);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement