您可以使用hough线变换在给定的图像中检测直线。在opencv中有两种可用的hough线变换方法,分别是标准hough线变换和概率hough线变换。
您可以使用imgproc类的houghlines()方法应用标准hough线变换。该方法接受以下参数:
表示源图像和存储线条参数(r,φ)的向量的两个mat对象。
表示参数r(像素)和φ(弧度)的分辨率的两个double变量。
表示“检测”一条线所需的最小交点数的整数。
您可以使用imgproc类的houghlinesp()方法(相同的参数)应用概率hough线变换。
您可以使用imgproc类的canny()方法在给定的图像中检测边缘。该方法接受以下参数:
表示源图像和目标图像的两个mat对象。
用于保存阈值值的两个double变量。
要使用canny边缘检测器检测给定图像的边缘,请按照以下步骤进行:
使用imgcodecs类的imread()方法读取源图像的内容。
使用imgproc类的cvtcolor()方法将其转换为灰度图像。
使用imgproc类的blur()方法将结果(灰度)图像模糊化,内核值为3。
使用imgproc的canny()方法在模糊图像上应用canny边缘检测算法。
创建一个所有值都为0的空矩阵。
使用mat类的copyto()方法将检测到的边缘添加到其中。
示例import java.awt.image;import java.awt.image.bufferedimage;import java.io.ioexception;import javafx.application.application;import javafx.embed.swing.swingfxutils;import javafx.scene.group;import javafx.scene.scene;import javafx.scene.image.imageview;import javafx.scene.image.writableimage;import javafx.stage.stage;import org.opencv.core.core;import org.opencv.core.cvtype;import org.opencv.core.mat;import org.opencv.core.point;import org.opencv.core.scalar;import org.opencv.highgui.highgui;import org.opencv.imgcodecs.imgcodecs;import org.opencv.imgproc.imgproc;public class houghlinetransform extends application { public void start(stage stage) throws ioexception { //loading the opencv core library system.loadlibrary( core.native_library_name ); string file ="d:\images\road4.jpg"; mat src = imgcodecs.imread(file); //converting the image to gray mat gray = new mat(); imgproc.cvtcolor(src, gray, imgproc.color_rgba2gray); //detecting the edges mat edges = new mat(); imgproc.canny(gray, edges, 60, 60*3, 3, false); // changing the color of the canny mat cannycolor = new mat(); imgproc.cvtcolor(edges, cannycolor, imgproc.color_gray2bgr); //detecting the hough lines from (canny) mat lines = new mat(); imgproc.houghlines(edges, lines, 1, math.pi/180, 150); for (int i = 0; i < lines.rows(); i++) { double[] data = lines.get(i, 0); double rho = data[0]; double theta = data[1]; double a = math.cos(theta); double b = math.sin(theta); double x0 = a*rho; double y0 = b*rho; //drawing lines on the image point pt1 = new point(); point pt2 = new point(); pt1.x = math.round(x0 + 1000*(-b)); pt1.y = math.round(y0 + 1000*(a)); pt2.x = math.round(x0 - 1000*(-b)); pt2.y = math.round(y0 - 1000 *(a)); imgproc.line(cannycolor, pt1, pt2, new scalar(0, 0, 255), 3); } //converting matrix to javafx writable image image img = highgui.tobufferedimage(cannycolor); writableimage writableimage= swingfxutils.tofximage((bufferedimage) img, null); //setting the image view imageview imageview = new imageview(writableimage); imageview.setx(10); imageview.sety(10); imageview.setfitwidth(575); imageview.setpreserveratio(true); //setting the scene object group root = new group(imageview); scene scene = new scene(root, 595, 400); stage.settitle("hough line transform"); stage.setscene(scene); stage.show(); } public static void main(string args[]) { launch(args); }}
输入图像
输出执行后,上述代码会产生以下输出 −
以上就是使用java实现opencv霍夫线变换的详细内容。