Example usage for org.opencv.imgproc Imgproc findContours

List of usage examples for org.opencv.imgproc Imgproc findContours

Introduction

In this page you can find the example usage for org.opencv.imgproc Imgproc findContours.

Prototype

public static void findContours(Mat image, List<MatOfPoint> contours, Mat hierarchy, int mode, int method) 

Source Link

Usage

From source file:com.davidmiguel.gobees.monitoring.algorithm.processors.ContoursFinder.java

License:Open Source License

@Override
public Mat process(@NonNull Mat frame) {
    if (frame.empty()) {
        Log.e("Invalid input frame.");
        return null;
    }//  w  w  w  .j ava2  s.  c  o  m
    Mat tmp = frame.clone();
    // Finding outer contours
    contourList.clear();
    Imgproc.findContours(tmp, contourList, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    // Filter bees
    Mat contours = new Mat(tmp.rows(), tmp.cols(), CvType.CV_8UC3);
    tmp.release();
    double area;
    Scalar color;
    numBees = 0;
    for (int i = 0; i < contourList.size(); i++) {
        area = Imgproc.contourArea(contourList.get(i));
        if (area > minArea && area < maxArea) {
            color = GREEN;
            numBees++;
        } else {
            color = RED;
        }
        // Draw contour
        Imgproc.drawContours(contours, contourList, i, color, -1);
    }
    return contours;
}

From source file:com.example.afs.makingmusic.process.MotionDetector.java

License:Open Source License

@Override
public void process(Frame frame) {
    Mat image = frame.getImageMatrix();/*from   w  ww  .j  a v a  2s  .  c  o  m*/
    Core.flip(image, image, 1);
    backgroundSubtractor.apply(image, foregroundMask);
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(foregroundMask.clone(), contours, new Mat(), Imgproc.RETR_LIST,
            Imgproc.CHAIN_APPROX_SIMPLE);
    Collections.shuffle(contours);
    int contourCount = contours.size();
    for (int contourIndex = 0; contourIndex < contourCount; contourIndex++) {
        MatOfPoint contour = contours.get(contourIndex);
        double contourArea = Imgproc.contourArea(contour);
        if (contourArea > MotionDetector.MINIMUM_AREA) {
            Rect item = Imgproc.boundingRect(contour);
            frame.addItem(item);
            itemCount++;
        }
    }
    Injector.getMetrics().setItems(itemCount);
}

From source file:com.github.mbillingr.correlationcheck.ImageProcessor.java

License:Open Source License

public List<Point> extractPoints() {
    Mat gray = new Mat();//work_width, work_height, CvType.CV_8UC1);
    Mat binary = new Mat();

    Mat kernel = Mat.ones(3, 3, CvType.CV_8UC1);

    debugreset();//from w ww  . ja  v a  2s .  com

    Mat image = load_transformed();
    working_image = image.clone();
    debugsave(image, "source");

    Imgproc.cvtColor(image, gray, Imgproc.COLOR_RGB2GRAY);
    debugsave(gray, "grayscale");

    Imgproc.GaussianBlur(gray, gray, new Size(15, 15), 0);
    debugsave(gray, "blurred");

    //Imgproc.equalizeHist(gray, gray);
    //debugsave(gray, "equalized");

    Imgproc.adaptiveThreshold(gray, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY_INV,
            129, 5);
    //Imgproc.threshold(gray, binary, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
    //Imgproc.threshold(gray, binary, 128, 255, Imgproc.THRESH_BINARY_INV);
    debugsave(binary, "binary");

    Imgproc.morphologyEx(binary, binary, Imgproc.MORPH_CLOSE, kernel);
    debugsave(binary, "closed");

    Imgproc.morphologyEx(binary, binary, Imgproc.MORPH_OPEN, kernel);
    debugsave(binary, "opened");

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(binary, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE); // is binary is now changed
    Imgproc.drawContours(image, contours, -1, new Scalar(0, 0, 255), 3);
    debugsave(image, "contours");

    List<PointAndArea> points = new ArrayList<>();

    for (MatOfPoint cnt : contours) {
        MatOfPoint2f c2f = new MatOfPoint2f();
        c2f.fromArray(cnt.toArray());
        RotatedRect rr = Imgproc.minAreaRect(c2f);

        double area = Imgproc.contourArea(cnt);

        if (rr.size.width / rr.size.height < 3 && rr.size.height / rr.size.width < 3 && rr.size.width < 64
                && rr.size.height < 64 && area > 9 && area < 10000) {
            points.add(new PointAndArea((int) area, rr.center));
        }
    }

    List<Point> final_points = new ArrayList<>();

    Collections.sort(points);
    Collections.reverse(points);
    int prev = -1;
    for (PointAndArea p : points) {
        Log.i("area", Integer.toString(p.area));
        if (prev == -1 || p.area >= prev / 2) {
            prev = p.area;
            Imgproc.circle(image, p.point, 10, new Scalar(0, 255, 0), 5);
            final_points.add(new Point(1 - p.point.y / work_height, 1 - p.point.x / work_width));
        }
    }
    debugsave(image, "circles");

    return final_points;
}

From source file:com.mitzuli.core.ocr.OcrPreprocessor.java

License:Open Source License

/**
 * Binarizes and cleans the input image for OCR, saving debugging images in the given directory.
 *
 * @param input the input image, which is recycled by this method, so the caller should make a defensive copy of it if necessary.
 * @param debugDir the directory to write the debugging images to, or null to disable debugging.
 * @return the preprocessed image./* www.  j a va 2  s  . c  om*/
 */
static Image preprocess(final Image input, final File debugDir) {
    // TODO Temporary workaround to allow to manually enable debugging (the global final variable should be used)
    boolean DEBUG = debugDir != null;

    // Initialization
    final Mat mat = input.toGrayscaleMat();
    final Mat debugMat = DEBUG ? input.toRgbMat() : null;
    input.recycle();
    final Mat aux = new Mat(mat.size(), CvType.CV_8UC1);
    final Mat binary = new Mat(mat.size(), CvType.CV_8UC1);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "1_input.jpg"));

    // Binarize the input image in mat through adaptive Gaussian thresholding
    Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 51,
            13);
    // Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 31, 7);

    // Edge detection
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_3X3); // Open
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_3X3); // Close
    Core.addWeighted(mat, 0.5, aux, 0.5, 0, mat); // Average
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_GRADIENT, KERNEL_3X3); // Gradient
    Imgproc.threshold(mat, mat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); // Edge map
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "2_edges.jpg"));

    // Extract word level connected-components from the dilated edge map
    Imgproc.dilate(mat, mat, KERNEL_3X3);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "3_dilated_edges.jpg"));
    final List<MatOfPoint> wordCCs = new ArrayList<MatOfPoint>();
    Imgproc.findContours(mat, wordCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter word level connected-components individually and calculate their average attributes
    final List<MatOfPoint> individuallyFilteredWordCCs = new ArrayList<MatOfPoint>();
    final List<MatOfPoint> removedWordCCs = new ArrayList<MatOfPoint>();
    double avgWidth = 0, avgHeight = 0, avgArea = 0;
    for (MatOfPoint cc : wordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.height >= 6 // bounding box height >= 6
                && boundingBox.area() >= 50 // bounding box area >= 50
                && (double) boundingBox.width / (double) boundingBox.height >= 0.25 // bounding box aspect ratio >= 1:4
                && boundingBox.width <= 0.75 * mat.width() // bounding box width <= 0.75 image width
                && boundingBox.height <= 0.75 * mat.height()) // bounding box height <= 0.75 image height
        {
            individuallyFilteredWordCCs.add(cc);
            avgWidth += boundingBox.width;
            avgHeight += boundingBox.height;
            avgArea += boundingBox.area();
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    wordCCs.clear();
    avgWidth /= individuallyFilteredWordCCs.size();
    avgHeight /= individuallyFilteredWordCCs.size();
    avgArea /= individuallyFilteredWordCCs.size();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, removedWordCCs, -1, BLUE, -1);
        removedWordCCs.clear();
    }

    // Filter word level connected-components in relation to their average attributes
    final List<MatOfPoint> filteredWordCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint cc : individuallyFilteredWordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.width >= 0.125 * avgWidth // bounding box width >= 0.125 average width
                && boundingBox.width <= 8 * avgWidth // bounding box width <= 8 average width
                && boundingBox.height >= 0.25 * avgHeight // bounding box height >= 0.25 average height
                && boundingBox.height <= 4 * avgHeight) // bounding box height <= 4 average height
        {
            filteredWordCCs.add(cc);
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    individuallyFilteredWordCCs.clear();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, filteredWordCCs, -1, GREEN, -1);
        Imgproc.drawContours(debugMat, removedWordCCs, -1, PURPLE, -1);
        removedWordCCs.clear();
    }

    // Extract paragraph level connected-components
    mat.setTo(BLACK);
    Imgproc.drawContours(mat, filteredWordCCs, -1, WHITE, -1);
    final List<MatOfPoint> paragraphCCs = new ArrayList<MatOfPoint>();
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_30X30);
    Imgproc.findContours(aux, paragraphCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter paragraph level connected-components according to the word level connected-components inside
    final List<MatOfPoint> textCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint paragraphCC : paragraphCCs) {
        final List<MatOfPoint> wordCCsInParagraphCC = new ArrayList<MatOfPoint>();
        aux.setTo(BLACK);
        Imgproc.drawContours(aux, Collections.singletonList(paragraphCC), -1, WHITE, -1);
        Core.bitwise_and(mat, aux, aux);
        Imgproc.findContours(aux, wordCCsInParagraphCC, new Mat(), Imgproc.RETR_EXTERNAL,
                Imgproc.CHAIN_APPROX_SIMPLE);
        final Rect boundingBox = Imgproc.boundingRect(paragraphCC);
        final double center = mat.size().width / 2;
        final double distToCenter = center > boundingBox.x + boundingBox.width
                ? center - boundingBox.x - boundingBox.width
                : center < boundingBox.x ? boundingBox.x - center : 0.0;
        if (DEBUG) {
            System.err.println("****************************************");
            System.err.println("\tArea:                " + boundingBox.area());
            System.err.println("\tDistance to center:  " + distToCenter);
            System.err.println("\tCCs inside:          " + wordCCsInParagraphCC.size());
        }
        if ((wordCCsInParagraphCC.size() >= 10 || wordCCsInParagraphCC.size() >= 0.3 * filteredWordCCs.size())
                && mat.size().width / distToCenter >= 4) {
            textCCs.addAll(wordCCsInParagraphCC);
            if (DEBUG) {
                System.err.println("\tText:                YES");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_GREEN, 5);
            }
        } else {
            if (DEBUG) {
                System.err.println("\tText:                NO");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_RED, 5);
            }
        }
    }
    filteredWordCCs.clear();
    paragraphCCs.clear();
    mat.setTo(WHITE);
    Imgproc.drawContours(mat, textCCs, -1, BLACK, -1);
    textCCs.clear();
    if (DEBUG)
        Image.fromMat(debugMat).write(new File(debugDir, "4_filtering.jpg"));

    // Obtain the final text mask from the filtered connected-components
    Imgproc.erode(mat, mat, KERNEL_15X15);
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_30X30);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "5_text_mask.jpg"));

    // Apply the text mask to the binarized image
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "6_binary.jpg"));
    binary.setTo(WHITE, mat);
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "7_binary_text.jpg"));

    // Dewarp the text using Leptonica
    Pix pixs = Image.fromMat(binary).toGrayscalePix();
    Pix pixsDewarp = Dewarp.dewarp(pixs, 0, Dewarp.DEFAULT_SAMPLING, 5, true);
    final Image result = Image.fromGrayscalePix(pixsDewarp);
    if (DEBUG)
        result.write(new File(debugDir, "8_dewarp.jpg"));

    // Clean up
    pixs.recycle();
    mat.release();
    aux.release();
    binary.release();
    if (debugMat != null)
        debugMat.release();

    return result;
}

From source file:com.mycompany.objectdetection.ObjectDetector.java

public void findObjects() {

    //        Imgproc.cvtColor(img, imgGrayscale, Imgproc.COLOR_RGBA2GRAY, 1); 
    //        Core.convertScaleAbs(img, imgGrayscale);
    //        Core.normalize(imgGrayscale, imgMeanShifted, 0.0, 1.0, NORM_MINMAX);
    preProcessImg();/*from   w  w  w. ja v a 2s .  c o m*/

    toGrayScale(imgMeanShifted);
    detectEdges(imgGrayscale);
    Imgproc.findContours(imgCanny, contours, imgCanny, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    objList = new ArrayList();

    for (MatOfPoint mop : contours) {
        MatOfPoint2f m2p;
        m2p = new MatOfPoint2f(mop.toArray());
        Double peri = Imgproc.arcLength(m2p, true);
        Imgproc.approxPolyDP(m2p, m2p, 0.02 * peri, true);
        Imgproc.drawContours(imgOut, contours, -1, new Scalar(0, 0, 255), 2);

        float area = img.width() * img.height();
        Rect rect = Imgproc.boundingRect(mop);
        objList.add(rect);
        Imgproc.rectangle(imgOut, rect.tl(), rect.br(), new Scalar(255, 0, 0));
    }

    Collections.sort(objList, new Comparator<Rect>() {
        @Override
        public int compare(Rect r1, Rect r2) {
            return (int) (r2.area() - r1.area());
        }

    });

    List<Rect> arr = objList;

    while (arr.size() > 0) {
        //System.out.println("---->" + arr);
        Rect bigRect = arr.get(0);
        arr.remove(0);
        Rect bigRect2 = new Rect();

        while (!equals(bigRect, bigRect2)) {
            bigRect2 = bigRect;
            for (int i = 0; i < arr.size(); ++i) {
                // System.out.println("elotte"+arr.get(i));
                if (doOverlap(bigRect, arr.get(i))) {
                    //System.out.println("utana"+arr.get(i));
                    bigRect = union(bigRect, arr.get(i));
                    arr.remove(i);
                    break;
                }
            }

        }

        mainRect = bigRect;

        if (objList.size() > 5 && mainRect.area() >= img.width() * img.height() * 3 / 100) {
            Imgproc.rectangle(imgOut, bigRect.tl(), bigRect.br(), new Scalar(255, 255, 0));
            mainObjects.add(mainRect);
        } else if (objList.size() <= 5) {
            mainObjects.add(mainRect);
        }
    }

}

From source file:com.orange.documentare.core.image.connectedcomponents.ConnectedComponentsDetector.java

License:Open Source License

/**
 * Retrieve image connected components in image
 * @param imageMat/*  w  w  w . ja  v a  2  s  . co  m*/
 * @param filter to apply to remove some connected components (based on size, etc)
 * @return connected components
 */
private ConnectedComponents detect(Mat imageMat, ConnectedComponentsFilter filter) {
    Mat binaryMat = Binarization.getFrom(imageMat);
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(binaryMat, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
    return buildConnectedComponents(contours, filter);
}

From source file:com.sikulix.core.Finder.java

License:Open Source License

public boolean hasChanges(Mat base, Mat current) {
    int PIXEL_DIFF_THRESHOLD = 5;
    int IMAGE_DIFF_THRESHOLD = 5;
    Mat bg = new Mat();
    Mat cg = new Mat();
    Mat diff = new Mat();
    Mat tdiff = new Mat();

    Imgproc.cvtColor(base, bg, Imgproc.COLOR_BGR2GRAY);
    Imgproc.cvtColor(current, cg, Imgproc.COLOR_BGR2GRAY);
    Core.absdiff(bg, cg, diff);/*from w  w w .  j  a  va 2  s .c o  m*/
    Imgproc.threshold(diff, tdiff, PIXEL_DIFF_THRESHOLD, 0.0, Imgproc.THRESH_TOZERO);
    if (Core.countNonZero(tdiff) <= IMAGE_DIFF_THRESHOLD) {
        return false;
    }

    Imgproc.threshold(diff, diff, PIXEL_DIFF_THRESHOLD, 255, Imgproc.THRESH_BINARY);
    Imgproc.dilate(diff, diff, new Mat());
    Mat se = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
    Imgproc.morphologyEx(diff, diff, Imgproc.MORPH_CLOSE, se);

    List<MatOfPoint> points = new ArrayList<MatOfPoint>();
    Mat contours = new Mat();
    Imgproc.findContours(diff, points, contours, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    int n = 0;
    for (Mat pm : points) {
        log.trace("(%d) %s", n++, pm);
        printMatI(pm);
    }
    log.trace("contours: %s", contours);
    printMatI(contours);
    return true;
}

From source file:com.ttolley.pongbot.opencv.CvWorker.java

@Override
protected Void doInBackground() throws Exception {
    try {/*from ww  w .  ja v a 2s.  c  o m*/
        //-- 2. Read the video stream  
        Mat webcam_image = new Mat();

        if (capture.isOpened()) {
            while (true) {
                capture.read(webcam_image);
                if (!webcam_image.empty()) {
                    PublishObject publishObject = new PublishObject(webcam_image);
                    for (Map.Entry<FilterType, Filter> entry : filters.entrySet()) {
                        Mat hsv_image = new Mat();
                        Mat thresholded = new Mat();
                        Filter filter = entry.getValue();
                        // One way to select a range of colors by Hue  
                        Imgproc.cvtColor(webcam_image, hsv_image, Imgproc.COLOR_BGR2HSV);
                        Core.inRange(hsv_image, filter.hsv_min, filter.hsv_max, thresholded);
                        // Morph open
                        final Size erodeSizeObj = new Size(filter.erodeSize, filter.erodeSize);
                        final Size dilateSizeObj = new Size(filter.dilateSize, filter.dilateSize);
                        Imgproc.erode(thresholded, thresholded,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, erodeSizeObj));
                        Imgproc.dilate(thresholded, thresholded,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, erodeSizeObj));
                        // Morph close
                        Imgproc.dilate(thresholded, thresholded,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, dilateSizeObj));
                        Imgproc.erode(thresholded, thresholded,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, dilateSizeObj));

                        Mat temp = new Mat();
                        thresholded.copyTo(temp);
                        List<MatOfPoint> contours = new ArrayList();
                        Mat heirarchy = new Mat();
                        Imgproc.findContours(temp, contours, heirarchy, Imgproc.RETR_TREE,
                                Imgproc.CHAIN_APPROX_SIMPLE);
                        FilteredObject.Target largestTarget = findTarget(contours, webcam_image, filter);
                        publishObject.addObject(entry.getKey(), new FilteredObject(largestTarget, thresholded));
                    }
                    publish(publishObject);

                } else {
                    System.out.println(" --(!) No captured frame -- Break!");
                    break;
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Unable to loop");
        System.out.println(getStackTrace(ex));
    }
    return null;
}

From source file:cpsd.ImageGUI.java

private void AnalyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalyzeButtonActionPerformed
    try {//from ww w  .  j  a  v  a 2s  .c  o m
        double pixelArea = 1;
        double imageSize = 1;
        if (magnification == 50)
            pixelArea = 1.2996;
        else if (magnification == 100)
            pixelArea = 0.329476;
        else if (magnification == 200)
            pixelArea = 0.08162;
        else {
            imageSize = pow(10, 10) * pow(magnification, -2);
            pixelArea = (imageSize) / (resolution1 * resolution2);
        }
        Mat source = ImageClass.getInstance().getImage();
        Mat destination = new Mat(source.rows(), source.cols(), source.type());
        //Imgproc.adaptiveThreshold(source,destination,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY_INV,13,2);
        //Imgproc.GaussianBlur(destination,destination,new org.opencv.core.Size(0,0),5);
        threshold(source, destination, 30, 255, CV_THRESH_BINARY);
        distanceTransform(destination, destination, CV_DIST_L2, 3);
        normalize(destination, destination, 0, 1, NORM_MINMAX);
        threshold(destination, destination, 0.5, 1, CV_THRESH_BINARY);
        destination.convertTo(destination, CV_8U);
        /*ImageClass.getInstance().setImage(destination);
        displayImage();*/
        ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        MatOfInt4 hierarchy = new MatOfInt4();
        // Rect roi = new Rect(100,100,destination.cols()-100,destination.rows()-100);
        //  Mat imageROI = destination.submat(roi);
        /*ImageClass.getInstance().setImage(imageROI);
        displayImage();*/
        //Imgproc.Canny(source,destination,0.05,0.15);
        Imgproc.findContours(destination, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
        int total = contours.size();
        int count = 0;

        //System.out.println(total);
        MatOfPoint[] cntrs = contours.toArray(new MatOfPoint[contours.size()]);
        ArrayList<Double> value = new ArrayList<Double>();
        double temp = 0;
        for (int i = 0; i < contours.size(); i++) {
            if (contourArea(cntrs[i]) > 1/*&& contourArea(cntrs[i])<3000*/) {
                temp = 2 * Math.sqrt((contourArea(cntrs[i]) * (pixelArea)) / Math.PI);
                //temp = contourArea(cntrs[i]);
                if (temp > 0) {
                    value.add(count, temp);
                    System.out.println("area of contour " + count++ + " is : " + contourArea(cntrs[i]));
                }
            }
        }
        System.out.println("total number of contours : " + count);
        double[] values = new double[count];
        for (int i = 0; i < count; i++) {
            //temp = value.get(i);//2*Math.sqrt((value.get(i)*127.024)/Math.PI);
            //if(temp>0)
            values[i] = value.get(i);
            //System.out.println("the diameter of particle "+i+ "is "+values[i]);
            // values[i]=(contourArea(cntrs[i])*127.024)/100;
        }
        //int number = 300;
        /*HistogramDataset dataset = new HistogramDataset();
        dataset.setType(HistogramType.FREQUENCY);
        XYSeries series = new XYSeries("Particle Size Distribution");
        try{
        dataset.addSeries("Histogram1",values,number,0,300);
                
        for(int i=0;i<300;i++){
            if(dataset.getYValue(0,i)>0)
           series.add(dataset.getXValue(0,i),dataset.getYValue(0,i));
        }
        // XYDataset xydataset = new XYSeriesCollection(series);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        XYDataset xydataset = new XYSeriesCollection(series);
        String plotTitle = "Particle Size Distribution";
        String xAxis = "particle diameter in microns";
        String yAxis = "particle count";
        PlotOrientation orientation = PlotOrientation.VERTICAL;
        boolean show = true;
        boolean toolTips = true;
        boolean urls = false;
        JFreeChart chart1 = ChartFactory.createXYLineChart(plotTitle,xAxis,yAxis,xydataset,orientation,show,toolTips,urls);
        JFreeChart chart2 = ChartFactory.createHistogram(plotTitle,xAxis,yAxis,dataset,orientation,show,toolTips,urls);
                
        int width1 = 500;
        int height1 = 500;
        ChartFrame frame1 = new ChartFrame("Coal PSD",chart1);
        frame1.setSize(width1,height1);
        frame1.setVisible(true);
        frame1.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        int width2 = 500;
        int height2 = 500;
        ChartFrame frame2 = new ChartFrame("Coal PSD",chart2);
        frame2.setSize(width2,height2);
        frame2.setVisible(true);
        frame2.setDefaultCloseOperation(DISPOSE_ON_CLOSE);*/
    } catch (NullPointerException e) {
        System.err.println("..........Please load a valid Image..........");
    }
    // TODO add your handling code here:
}

From source file:cubesolversimulator.VisualInputForm.java

private void getContour() {
    Mat dilate = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(7, 7));

    Imgproc.dilate(edge, edge, dilate);// w w  w  . ja va2s  .c o m
    Imgproc.dilate(edge, edge, dilate);

    Highgui.imwrite("dilate.jpg", edge);

    List<MatOfPoint> contours = new ArrayList<>();

    Imgproc.findContours(edge, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    Imgproc.drawContours(contour, contours, -1, new Scalar(255, 255, 255));

    Highgui.imwrite("Contour.jpg", contour);

    img4 = new JLabel("");
    img4.setSize(jPanel7.getSize());
    image4 = new ImageIcon(new ImageIcon("D:\\Project_work\\CubeSolverSimulator\\dilate.jpg").getImage()
            .getScaledInstance(img4.getWidth(), img4.getHeight(), Image.SCALE_FAST));
    img4.setIcon(image4);
    img4.repaint();
    jPanel7.add(img4);
    jPanel7.repaint();
    findRect(contours);
}