Example usage for org.opencv.imgproc Imgproc Canny

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

Introduction

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

Prototype

public static void Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize,
            boolean L2gradient) 

Source Link

Usage

From source file:OCV_Canny.java

License:Open Source License

@Override
public void run(ImageProcessor ip) {
    // srcdst/*from  w  w w. j  a  v a  2 s  .  co m*/
    int imw = ip.getWidth();
    int imh = ip.getHeight();
    byte[] srcdst_bytes = (byte[]) ip.getPixels();

    // mat
    Mat src_mat = new Mat(imh, imw, CvType.CV_8UC1);
    Mat dst_mat = new Mat(imh, imw, CvType.CV_8UC1);

    // run
    src_mat.put(0, 0, srcdst_bytes);
    Imgproc.Canny(src_mat, dst_mat, thr1, thr2, SIZE_VAL[ind_size], l2grad);
    dst_mat.get(0, 0, srcdst_bytes);
}

From source file:carmelo.JavaFXOpenCV.java

private Mat procesarImagen(Mat src) {
    Mat dst = new Mat();

    Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(dst, dst, new Size(7, 7), 1.5, 1.5);
    Imgproc.Canny(dst, dst, 0, 30, 3, false);

    return dst;/*from   ww w . j a va  2  s .  co  m*/
}

From source file:com.mycompany.linedetection.LineDetector.java

public void findLines() {
    Imgproc.Canny(img, edgeDetectedImg, 100, 200, 3, true);
    Mat lines = new Mat();

    int width = img.width();
    int height = img.height();
    double diagonal = Math.sqrt(width * width + height * height);
    int minOfWidthHeight = (width < height) ? width : height;

    Imgproc.HoughLinesP(edgeDetectedImg, lines, 1, Math.PI / 180, minOfWidthHeight * 10 / 100,
            diagonal * 25 / 100, diagonal * 4 / 100);

    int firstN = (lines.rows() < 5) ? lines.rows() : 5;

    for (int x = 0; x < lines.rows(); x++) {
        double[] vec = lines.get(x, 0);
        double[] vec1 = lines.get(x, 1);
        double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3];
        Point startPoint = new Point(x1, y1);
        Point endPoint = new Point(x2, y2);

        double angle_inv = horizontalLine.getAngle(new Line(x1, y1, x2, y2));
        double angle = horizontalLine.getAngle(new Line(x2, y2, x1, y1));
        if ((angle >= diagAngle1 - DIAGONAL_TRESHOLD && angle <= diagAngle1 + DIAGONAL_TRESHOLD)
                || (angle >= diagAngle2 - DIAGONAL_TRESHOLD && angle <= diagAngle2 + DIAGONAL_TRESHOLD)
                || (angle_inv >= diagAngle1 - DIAGONAL_TRESHOLD && angle_inv <= diagAngle1 + DIAGONAL_TRESHOLD)
                || (angle_inv >= diagAngle2 - DIAGONAL_TRESHOLD
                        && angle_inv <= diagAngle2 + DIAGONAL_TRESHOLD)) {
            diagonalLineList.add(new Line(x1, y1, x2, y2));
            Imgproc.line(img, startPoint, endPoint, new Scalar(255, 255, 0), 4);
        } else {//from  w  w w  .j av  a2s.  c om
            lineList.add(new Line(x1, y1, x2, y2));
        }

    }

    Collections.sort(lineList, new Comparator<Line>() {
        @Override
        public int compare(Line l1, Line l2) {
            return (int) (l2.getLength() - l1.getLength());
        }

    });

    ArrayList arr = new ArrayList<Line>();

    for (int i = 0; i < firstN + 1; i++) {
        if (lineList.size() >= firstN + 1) {
            double x1 = lineList.get(i).getX1(), y1 = lineList.get(i).getY1(), x2 = lineList.get(i).getX2(),
                    y2 = lineList.get(i).getY2();
            Point startPoint = new Point(x1, y1);
            Point endPoint = new Point(x2, y2);
            arr.add(lineList.get(i));
            Imgproc.line(img, startPoint, endPoint, new Scalar(0, 0, 255), 3);
        }
    }
    lineList = arr;
}

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

public void detectEdges(Mat m) {
    Imgproc.Canny(m, imgCanny, THRESHOLD1, THRESHOLD2, APERTURE_SIZE, true);
}

From source file:cpsd.ImageGUI.java

private void cannyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cannyButtonActionPerformed
    try {// ww w . java 2s . c om
        Mat source = ImageClass.getInstance().getImage();

        Mat destination = new Mat(source.rows(), source.cols(), source.type());
        threshold(source, destination, 50, 255, CV_THRESH_BINARY);
        // ImageClass.getInstance().setImage(destination);
        // Imgproc.GaussianBlur(destination,destination,new org.opencv.core.Size(0,0),10);
        // fastNlMeansDenoising(destination,destination,3,7,21);
        // source = ImageClass.getInstance().getImage();
        Imgproc.Canny(destination, destination, 0.05, 0.15, 3, true);
        ImageClass.getInstance().setImage(destination);
    } catch (NullPointerException e) {
        System.err.println("..........Please load a valid Image..........");
    }
    displayImage(); // TODO add your handling code here:
}

From source file:cv.recon.util.CannyDetector.java

License:Open Source License

/**
 * Apply Canny detector to Mat.//w  w  w . j  av a  2  s .  c  o  m
 * @param src Input Mat
 * @param dst Output Mat
 */
public void detect(Mat src, Mat dst) {
    Mat src_gray = new Mat();
    Mat detected_edges = new Mat();

    Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_RGB2GRAY);
    Imgproc.blur(src_gray, detected_edges, new Size(3, 3));
    Imgproc.Canny(detected_edges, detected_edges, lowThreshold, lowThreshold * ratio, kernel_size, true);

    dst.setTo(new Scalar(0));
    src.copyTo(dst, detected_edges);
}

From source file:de.hu_berlin.informatik.spws2014.mapever.entzerrung.CornerDetector.java

License:Open Source License

/**
 * Guesses the most likly corners of a distorted map within an image.
 * Expects OpenCV to be initialized.// w  ww  .j a va  2s .c om
 * The results are already pretty good but could propably be improved
 * via tweaking the parameters or adding some additional line filtering
 * criteria(like them being kind of parallel for instance...)
 * 
 * @param gray_img A grayscale image in OpenCVs Mat format.
 * @return An array of propable corner points in the following form: {x0,y0,x1,y1,x2,y2,x3,y3} or null on error.
 **/
public static Point[] guess_corners(Mat gray_img) {
    Mat lines = new Mat();
    Imgproc.Canny(gray_img, gray_img, THRESHOLD0, THRESHOLD1, APERTURE_SIZE, false);
    Imgproc.HoughLinesP(gray_img, lines, RHO, THETA, HOUGH_THRESHOLD,
            Math.min(gray_img.cols(), gray_img.rows()) / MIN_LINE_LENGTH_FRACTION, MAX_LINE_GAP);

    double[][] edge_lines = filter_lines(lines, gray_img.size());

    Point[] ret_val = new Point[4];
    ret_val[0] = find_intercept_point(edge_lines[0], edge_lines[2]);
    ret_val[1] = find_intercept_point(edge_lines[0], edge_lines[3]);
    ret_val[2] = find_intercept_point(edge_lines[1], edge_lines[3]);
    ret_val[3] = find_intercept_point(edge_lines[1], edge_lines[2]);

    // do sanity checks and return null on invalid coordinates
    for (int i = 0; i < 4; i++) {
        // check if coordinates are outside image boundaries
        if (ret_val[i].x < 0 || ret_val[i].y < 0 || ret_val[i].x > gray_img.width()
                || ret_val[i].y > gray_img.height()) {
            return null;
        }

        // check if point equal to other point
        for (int j = i + 1; j < 4; j++) {
            if (ret_val[j].x == ret_val[i].x && ret_val[j].y == ret_val[i].y) {
                return null;
            }
        }
    }

    return ret_val;
}

From source file:depthDataFromStereoCamsOpenCV.ProcessImages.java

/**
 * Applies Canny edge detection algorithm
 * @param Mat image/*from  w w  w .ja va 2  s.  c o  m*/
 * @return Mat
 */
public static Mat applyCannyEdgeDetectorOpenCV_Mat(Mat image) {
    //TODO
    //all these parameters have to be investigated
    Mat result = image.clone();
    int lowThreshold = 40;
    int ratio = 120;
    int kernel_size = 3;

    Imgproc.blur(result, result, new Size(2, 2));
    Imgproc.Canny(result, result, lowThreshold, ratio, kernel_size, true);
    //Imgproc.threshold(result,result,64, 254,Imgproc.THRESH_BINARY_INV);
    return result;
}

From source file:edu.fiu.cate.breader.BaseSegmentation.java

/**
 * Finds the bounding box for the book on the stand using 
 * the high resolution image.//from   ww w . ja va 2  s  . c o  m
 * @param src- High Resolution image of the book
 * @return Rectangle delineating the book
 */
public Rect highRes(Mat src) {
    Mat dst = src.clone();
    Imgproc.blur(src, dst, new Size(100.0, 100.0), new Point(-1, -1), Core.BORDER_REPLICATE);
    Imgproc.threshold(dst, dst, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
    Imgproc.Canny(dst, dst, 50, 200, 3, false);

    List<MatOfPoint> contours = new LinkedList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(dst, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE,
            new Point(0, 0));

    Mat color = new Mat();
    Imgproc.cvtColor(src, color, Imgproc.COLOR_GRAY2BGR);
    for (int k = 0; k < contours.size(); k++) {
        byte[] vals = ITools.getHeatMapColor((float) k / (float) contours.size());
        Imgproc.drawContours(color, contours, k, new Scalar(vals[0], vals[1], vals[2]), 8);
    }
    new IViewer("HighRes Contours ", BReaderTools.bufferedImageFromMat(color));

    Point center = new Point(src.cols() / 2, src.rows() / 2);
    //Check hierarchy tree
    int[] res = polySearch(center, hierarchy, contours, 0);
    while (res[0] != 1 && res[2] != -1) {
        res = polySearch(center, hierarchy, contours, res[2]);
        if (res[0] == 1)
            break;
    }

    MatOfInt tHull = new MatOfInt();
    int index = 0;
    if (res[1] != -1) {
        index = res[1];
    }
    Imgproc.convexHull(contours.get(index), tHull);

    //get bounding box
    MatOfPoint cont = contours.get(index);
    Point[] points = new Point[tHull.rows()];
    for (int i = 0; i < tHull.rows(); i++) {
        int pIndex = (int) tHull.get(i, 0)[0];
        points[i] = new Point(cont.get(pIndex, 0));
    }
    Rect out = Imgproc.boundingRect(new MatOfPoint(points));
    return out;
}

From source file:edu.fiu.cate.breader.BaseSegmentation.java

/**
 * Finds the bounding box for the book on the stand using 
 * the depth average image./*from   w ww  .  java2  s.co m*/
 * @param src- The Depth average image
 * @return Rectangle delineating the book
 */
public Rect lowResDist(Mat src) {
    Mat dst = src.clone();

    Imgproc.blur(src, dst, new Size(5, 5), new Point(-1, -1), Core.BORDER_REPLICATE);
    //      Imgproc.threshold(dst, dst, 0,255,Imgproc.THRESH_BINARY_INV+Imgproc.THRESH_OTSU);
    Imgproc.Canny(dst, dst, 50, 200, 3, false);
    //      Canny(src, dst, 20, 60, 3);

    List<MatOfPoint> contours = new LinkedList<>();
    Mat hierarchy = new Mat();
    /// Find contours
    Imgproc.findContours(dst, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE,
            new Point(0, 0));

    Mat color = new Mat();
    Imgproc.cvtColor(src, color, Imgproc.COLOR_GRAY2BGR);
    for (int k = 0; k < contours.size(); k++) {
        byte[] vals = ITools.getHeatMapColor((float) k / (float) contours.size());
        Imgproc.drawContours(color, contours, k, new Scalar(vals[0], vals[1], vals[2]), 1);
    }
    new IViewer("LowRes Contours ", BReaderTools.bufferedImageFromMat(color));

    for (int k = 0; k < contours.size(); k++) {
        MatOfPoint2f tMat = new MatOfPoint2f();
        Imgproc.approxPolyDP(new MatOfPoint2f(contours.get(k).toArray()), tMat, 5, true);
        contours.set(k, new MatOfPoint(tMat.toArray()));
    }

    List<Point> points = new LinkedList<Point>();
    for (int i = 0; i < contours.size(); i++) {
        points.addAll(contours.get(i).toList());
    }

    MatOfInt tHull = new MatOfInt();
    Imgproc.convexHull(new MatOfPoint(points.toArray(new Point[points.size()])), tHull);

    //get bounding box
    Point[] tHullPoints = new Point[tHull.rows()];
    for (int i = 0; i < tHull.rows(); i++) {
        int pIndex = (int) tHull.get(i, 0)[0];
        tHullPoints[i] = points.get(pIndex);
    }
    Rect out = Imgproc.boundingRect(new MatOfPoint(tHullPoints));
    return out;
}