Path: blob/master/samples/java/tutorial_code/ImgTrans/HoughCircle/HoughCircles.java
16354 views
package sample;1/**2* @file HoughCircles.java3* @brief This program demonstrates circle finding with the Hough transform4*/56import org.opencv.core.*;7import org.opencv.core.Point;8import org.opencv.highgui.HighGui;9import org.opencv.imgcodecs.Imgcodecs;10import org.opencv.imgproc.Imgproc;1112class HoughCirclesRun {1314public void run(String[] args) {1516//! [load]17String default_file = "../../../../data/smarties.png";18String filename = ((args.length > 0) ? args[0] : default_file);1920// Load an image21Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);2223// Check if image is loaded fine24if( src.empty() ) {25System.out.println("Error opening image!");26System.out.println("Program Arguments: [image_name -- default "27+ default_file +"] \n");28System.exit(-1);29}30//! [load]3132//! [convert_to_gray]33Mat gray = new Mat();34Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);35//! [convert_to_gray]3637//![reduce_noise]38Imgproc.medianBlur(gray, gray, 5);39//![reduce_noise]4041//! [houghcircles]42Mat circles = new Mat();43Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,44(double)gray.rows()/16, // change this value to detect circles with different distances to each other45100.0, 30.0, 1, 30); // change the last two parameters46// (min_radius & max_radius) to detect larger circles47//! [houghcircles]4849//! [draw]50for (int x = 0; x < circles.cols(); x++) {51double[] c = circles.get(0, x);52Point center = new Point(Math.round(c[0]), Math.round(c[1]));53// circle center54Imgproc.circle(src, center, 1, new Scalar(0,100,100), 3, 8, 0 );55// circle outline56int radius = (int) Math.round(c[2]);57Imgproc.circle(src, center, radius, new Scalar(255,0,255), 3, 8, 0 );58}59//! [draw]6061//! [display]62HighGui.imshow("detected circles", src);63HighGui.waitKey();64//! [display]6566System.exit(0);67}68}6970public class HoughCircles {71public static void main(String[] args) {72// Load the native library.73System.loadLibrary(Core.NATIVE_LIBRARY_NAME);74new HoughCirclesRun().run(args);75}76}777879