Path: blob/master/samples/java/tutorial_code/ImgTrans/HoughLine/HoughLines.java
16354 views
/**1* @file HoughLines.java2* @brief This program demonstrates line finding with the Hough transform3*/45import org.opencv.core.*;6import org.opencv.core.Point;7import org.opencv.highgui.HighGui;8import org.opencv.imgcodecs.Imgcodecs;9import org.opencv.imgproc.Imgproc;1011class HoughLinesRun {1213public void run(String[] args) {14// Declare the output variables15Mat dst = new Mat(), cdst = new Mat(), cdstP;1617//! [load]18String default_file = "../../../../data/sudoku.png";19String filename = ((args.length > 0) ? args[0] : default_file);2021// Load an image22Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_GRAYSCALE);2324// Check if image is loaded fine25if( src.empty() ) {26System.out.println("Error opening image!");27System.out.println("Program Arguments: [image_name -- default "28+ default_file +"] \n");29System.exit(-1);30}31//! [load]3233//! [edge_detection]34// Edge detection35Imgproc.Canny(src, dst, 50, 200, 3, false);36//! [edge_detection]3738// Copy edges to the images that will display the results in BGR39Imgproc.cvtColor(dst, cdst, Imgproc.COLOR_GRAY2BGR);40cdstP = cdst.clone();4142//! [hough_lines]43// Standard Hough Line Transform44Mat lines = new Mat(); // will hold the results of the detection45Imgproc.HoughLines(dst, lines, 1, Math.PI/180, 150); // runs the actual detection46//! [hough_lines]47//! [draw_lines]48// Draw the lines49for (int x = 0; x < lines.rows(); x++) {50double rho = lines.get(x, 0)[0],51theta = lines.get(x, 0)[1];5253double a = Math.cos(theta), b = Math.sin(theta);54double x0 = a*rho, y0 = b*rho;55Point pt1 = new Point(Math.round(x0 + 1000*(-b)), Math.round(y0 + 1000*(a)));56Point pt2 = new Point(Math.round(x0 - 1000*(-b)), Math.round(y0 - 1000*(a)));57Imgproc.line(cdst, pt1, pt2, new Scalar(0, 0, 255), 3, Imgproc.LINE_AA, 0);58}59//! [draw_lines]6061//! [hough_lines_p]62// Probabilistic Line Transform63Mat linesP = new Mat(); // will hold the results of the detection64Imgproc.HoughLinesP(dst, linesP, 1, Math.PI/180, 50, 50, 10); // runs the actual detection65//! [hough_lines_p]66//! [draw_lines_p]67// Draw the lines68for (int x = 0; x < linesP.rows(); x++) {69double[] l = linesP.get(x, 0);70Imgproc.line(cdstP, new Point(l[0], l[1]), new Point(l[2], l[3]), new Scalar(0, 0, 255), 3, Imgproc.LINE_AA, 0);71}72//! [draw_lines_p]7374//! [imshow]75// Show results76HighGui.imshow("Source", src);77HighGui.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst);78HighGui.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP);79//! [imshow]8081//! [exit]82// Wait and Exit83HighGui.waitKey();84System.exit(0);85//! [exit]86}87}8889public class HoughLines {90public static void main(String[] args) {91// Load the native library.92System.loadLibrary(Core.NATIVE_LIBRARY_NAME);93new HoughLinesRun().run(args);94}95}969798