Example usage for org.opencv.imgproc Imgproc HoughLinesP

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

Introduction

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

Prototype

public static void HoughLinesP(Mat image, Mat lines, double rho, double theta, int threshold,
            double minLineLength, double maxLineGap) 

Source Link

Usage

From source file:OCV_HoughLinesP.java

License:Open Source License

@Override
public void run(ImageProcessor ip) {
    // src//  w  ww  . j  a  va2 s.  c om
    int imw = ip.getWidth();
    int imh = ip.getHeight();
    byte[] src_ar = (byte[]) ip.getPixels();

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

    // run
    src_mat.put(0, 0, src_ar);
    Imgproc.HoughLinesP(src_mat, dst_lines, resDist, CV_PI / resAngFact, minVotes, minLen, maxGap);

    // fin
    showData(dst_lines);
}

From source file:com.carver.paul.truesight.ImageRecognition.ImageTools.java

License:Open Source License

public static void getLineFromTopRectMask(Mat mask, Mat lines, int minLineLength) {
    Imgproc.HoughLinesP(mask, lines, 1, Math.PI / 180, 80, minLineLength, 10);
}

From source file:com.joowon.returnA.classifier.cv.PdfPageDivider.java

License:Open Source License

public PdfPageDivider divide() {
    // generate gray scale and blur
    Mat gray = new Mat();
    Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.blur(gray, gray, new Size(3, 3));

    // detect the edges
    Mat edges = new Mat();
    int lowThreshold = 50;
    int ratio = 3;
    Imgproc.Canny(gray, edges, lowThreshold, lowThreshold * ratio);

    lines = new Mat();
    Imgproc.HoughLinesP(edges, lines, 10, Math.PI / 180, 50, 50, 10);
    return this;
}

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  ww  . j av a 2  s  . com*/
            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.shootoff.camera.autocalibration.AutoCalibrationManager.java

License:Open Source License

private Optional<MatOfPoint2f> findIdealCorners(final Mat frame, final MatOfPoint2f estimatedPatternRect) {
    Mat traceMat = null;//from w  ww.  j  a  v  a  2s .  c o m
    if (logger.isTraceEnabled()) {
        Mat traceMatTemp = frame.clone();
        traceMat = new Mat();

        Imgproc.cvtColor(traceMatTemp, traceMat, Imgproc.COLOR_GRAY2BGR);
    }

    // pixel distance, dynamic because we want to allow any resolution or
    // distance from pattern
    final int toleranceThreshold = (int) (minimumDimension / (double) (PATTERN_HEIGHT - 1) / 1.5);

    // Grey scale conversion.
    //final Mat grey = new Mat();
    //Imgproc.cvtColor(frame, grey, Imgproc.COLOR_BGR2GRAY);
    final Mat grey = frame;

    // Find edges
    Imgproc.Canny(grey, grey, CANNY_THRESHOLD_1, CANNY_THRESHOLD_2);

    // Blur the lines, otherwise the lines algorithm does not consider them
    Imgproc.GaussianBlur(grey, grey, gaussianBlurSize, GAUSSIANBLUR_SIGMA);

    if (logger.isTraceEnabled()) {
        logger.trace("tolerance threshold {} minimumDimension {}", toleranceThreshold, minimumDimension);

        String filename = String.format("calibrate-undist-grey-lines.png");
        File file = new File(filename);
        filename = file.toString();
        Highgui.imwrite(filename, grey);
    }

    if (logger.isDebugEnabled())
        logger.debug("estimation {} {} {} {}", estimatedPatternRect.get(0, 0), estimatedPatternRect.get(1, 0),
                estimatedPatternRect.get(2, 0), estimatedPatternRect.get(3, 0));

    // Easier to work off of Points
    final Point[] estimatedPoints = matOfPoint2fToPoints(estimatedPatternRect);

    if (logger.isTraceEnabled()) {
        Core.circle(traceMat, estimatedPoints[0], 1, new Scalar(0, 0, 255), -1);
        Core.circle(traceMat, estimatedPoints[1], 1, new Scalar(0, 0, 255), -1);
        Core.circle(traceMat, estimatedPoints[2], 1, new Scalar(0, 0, 255), -1);
        Core.circle(traceMat, estimatedPoints[3], 1, new Scalar(0, 0, 255), -1);
    }

    // Find lines
    // These parameters are just guesswork right now
    final Mat mLines = new Mat();
    final int minLineSize = (int) (minimumDimension * .90);
    final int lineGap = toleranceThreshold;

    // Do it
    Imgproc.HoughLinesP(grey, mLines, HOUGHLINES_RHO, HOUGHLINES_THETA, HOUGHLINES_THRESHOLD, minLineSize,
            lineGap);

    // Find the lines that match our estimates
    final Set<double[]> verifiedLines = new HashSet<double[]>();

    for (int x = 0; x < mLines.cols(); x++) {
        final double[] vec = mLines.get(0, x);
        final double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3];
        final Point start = new Point(x1, y1);
        final Point end = new Point(x2, y2);

        if (nearPoints(estimatedPoints, start, toleranceThreshold)
                && nearPoints(estimatedPoints, end, toleranceThreshold)) {
            verifiedLines.add(vec);

            if (logger.isTraceEnabled()) {
                Core.line(traceMat, start, end, new Scalar(255, 0, 0), 1);
            }
        }
    }

    if (logger.isTraceEnabled())
        logger.trace("verifiedLines: {}", verifiedLines.size());

    // Reduce the lines to possible corners
    final Set<Point> possibleCorners = new HashSet<Point>();

    for (double[] line1 : verifiedLines) {
        for (double[] line2 : verifiedLines) {
            if (line1 == line2)
                continue;

            Optional<Point> intersection = computeIntersect(line1, line2);

            if (intersection.isPresent())
                possibleCorners.add(intersection.get());
        }
    }

    // Reduce the possible corners to ideal corners
    Point[] idealCorners = new Point[4];
    final double[] idealDistances = { toleranceThreshold, toleranceThreshold, toleranceThreshold,
            toleranceThreshold };

    for (Point pt : possibleCorners) {
        for (int i = 0; i < 4; i++) {
            final double distance = euclideanDistance(pt, estimatedPoints[i]);

            if (distance < idealDistances[i]) {
                idealDistances[i] = distance;
                idealCorners[i] = pt;
            }
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("idealDistances {} {} {} {}", idealDistances[0], idealDistances[1], idealDistances[2],
                idealDistances[3]);

        String filename = String.format("calibrate-lines.png");
        File file = new File(filename);
        filename = file.toString();
        Highgui.imwrite(filename, traceMat);
    }

    // Verify that we have the corners we need
    for (Point pt : idealCorners) {
        if (pt == null)
            return Optional.empty();

        if (logger.isTraceEnabled()) {
            logger.trace("idealCorners {}", pt);
            Core.circle(traceMat, pt, 1, new Scalar(0, 255, 255), -1);
        }
    }

    if (logger.isTraceEnabled()) {
        String filename = String.format("calibrate-lines-with-corners.png");
        File file = new File(filename);
        filename = file.toString();
        Highgui.imwrite(filename, traceMat);
    }

    // Sort them into the correct order
    // 1st-------2nd
    // | |
    // | |
    // | |
    // 3rd-------4th
    idealCorners = sortCorners(idealCorners);

    // build the MatofPoint2f
    final MatOfPoint2f sourceCorners = new MatOfPoint2f();
    sourceCorners.alloc(4);

    for (int i = 0; i < 4; i++) {
        sourceCorners.put(i, 0, new double[] { idealCorners[i].x, idealCorners[i].y });
    }

    return Optional.of(sourceCorners);
}

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.//from w  ww  . ja  v  a  2 s  . co  m
 * 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:gab.opencv.OpenCV.java

License:Open Source License

public ArrayList<Line> findLines(int threshold, double minLineLength, double maxLineGap) {
    ArrayList<Line> result = new ArrayList<Line>();

    Mat lineMat = new Mat();
    Imgproc.HoughLinesP(getCurrentMat(), lineMat, 1, PConstants.PI / 180.0, threshold, minLineLength,
            maxLineGap);//ww  w  . j  a va 2s  .c o m
    for (int i = 0; i < lineMat.width(); i++) {
        double[] coords = lineMat.get(0, i);
        result.add(new Line(coords[0], coords[1], coords[2], coords[3]));
    }

    return result;
}

From source file:opencltest.YetAnotherTestT.java

public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    Mat kernel = new Mat(3, 3, CV_8UC1);
    kernel.put(0, 0, new double[] { 0, 1, 0, 1, 1, 1, 0, 1, 0 });

    Mat source = Imgcodecs.imread("test.smaller.png");
    Mat blur = new Mat();
    Mat edges = new Mat();
    Mat dilated = new Mat();

    Imgproc.GaussianBlur(source, blur, new Size(13, 13), 0);
    Imgproc.Canny(blur, edges, 10, 30, 5, false);
    //        Imgproc.cvtColor(edges, edges, Imgproc.COLOR_RGB2GRAY);
    //        Imgproc.adaptiveThreshold(edges, edges, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 2);
    //        Core.bitwise_not(edges, edges);
    //        Imgproc.dilate(edges, edges, kernel);
    //        Imgproc.dilate(edges, dilated, kernel);
    dilated = edges;//from  ww w  . j av  a 2s  .c  o  m
    //        Core.bitwise_not(edges, edges);

    Mat lines = new Mat();
    Imgproc.HoughLinesP(dilated, lines, 1, Math.PI / 180, 300, 10, 70);

    Mat empty = new Mat(source.height(), source.width(), source.type());
    //        paintLines(empty, lines);

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hier = new Mat();
    Imgproc.findContours(edges, contours, hier, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    Mat foundSquare = new Mat(source.height(), source.width(), CvType.CV_8UC4);
    source.copyTo(foundSquare);

    List<Double> hor = new ArrayList<>();
    for (Iterator<MatOfPoint> iterator = contours.iterator(); iterator.hasNext();) {
        MatOfPoint next = iterator.next();
        Rect bounding = Imgproc.boundingRect(next);
        int tr = 20;
        if (diffLessThan(bounding.size().width - 40, tr) && diffLessThan(bounding.size().height - 40, tr)) {
            Imgproc.rectangle(empty, bounding.tl(), bounding.br(), randomColor(), 3);
            //                hor.add(bounding.x + 0.0);
            hor.add(bounding.x + bounding.width / 2.0 + 0.0);
            drawRect(bounding, foundSquare);
        }
    }

    Imgcodecs.imwrite("test_2.png", source);
    Imgcodecs.imwrite("test_3.png", dilated);
    Imgcodecs.imwrite("test_4.png", empty);
    Imgcodecs.imwrite("test_h.png", foundSquare);

    hor.sort(Double::compare);
    double low = hor.get(0);
    double hih = hor.get(hor.size() - 1);
    double n = hor.size();
    Function<Double, Double> K = (d) -> (Math.abs(d) <= 1) ? ((3.0 / 4.0) * (1 - (d * d))) : 0;//epanechnikov kernel
    List<Double> result = new ArrayList<>();
    double h = 10;
    for (int i = 0; i < source.width() + 1; i++)
        result.add(0.0);
    for (double d = low; d <= hih; d += 1) {
        double sum = 0;
        for (Double di : hor) {
            sum += K.apply((d - di) / h);
        }
        result.set((int) d, sum / (n * h));
        System.out.println(sum / (n * h));
    }
    normalize(result, 255);
    Mat test = new Mat(source.height(), source.width(), source.type());
    source.copyTo(test);
    draw(result, test);
    Imgcodecs.imwrite("test_uwot.png", test);
}