Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Circle Detection using Java


I have been trying to use opencv in java to detect circles. I've had success using c++ and c#(emgucv) but i'm having trouble in java

            Mat frame = new Mat();  

            Mat hsv = new Mat();
            Imgproc.cvtColor(frame, hsv, Imgproc.COLOR_RGB2HSV);

            Mat threshold = new Mat();
            Core.inRange(hsv, new Scalar(H_MIN, S_MIN, V_MIN,1), new Scalar(H_MAX,S_MAX,V_MAX,1), threshold);

    //      Imgproc.GaussianBlur(threshold, threshold,new Size(3,3), 1.5);

            Mat circles = new Mat();

            Imgproc.HoughCircles(threshold, circles, Imgproc.CV_HOUGH_GRADIENT, 2, threshold.height() / 4, 100, 50, 10, 400);

            /*Drawing image to frame*/
            MatOfByte imgBytes = new MatOfByte();

            Highgui.imencode(".png", threshold, imgBytes);

            byte[] byteData = imgBytes.toArray();

            InputStream in = new ByteArrayInputStream(byteData);

            display = scale(, this.getWidth(), this.getHeight());

            for (int i = 0; i < circles.cols(); i++){

                double[] vecCircle = circles.get(0, i);

                int x = (int) vecCircle[0];
                int y = (int) vecCircle[1];
                int r = (int) vecCircle[2];

                drawCircle(display.createGraphics(), x, y, r);


In this case i'm drawing circles to a buffered image, but they dont seem to be around anything circular.

I've seen a Converter class for Mat to vector but it throws errors. So what is the correct way of doing this?