Java 示例演示 OpenCV 中的 Canny 边缘检测。
javaobject oriented programmingprogramming更新于 2025/10/9 6:36:17
Canny 边缘检测器被称为最佳检测器,因为它仅检测现有边缘,每页仅给出一个响应,并最小化边缘像素和检测到的像素之间的距离。
Imgproc 类的 Canny() 方法将 Canny 边缘检测算法应用于给定图像。此方法接受 −
两个 Mat 对象,分别表示源图像和目标图像。
两个双精度变量,用于保存阈值。
使用 canny 边缘检测器 −
检测给定图像的边缘使用 Imgcodecs 类的 imread() 方法读取源图像的内容。
使用 Imgproc 类的 cvtColor() 方法将其转换为灰度图像。
使用 Imgproc 类的 blur() 方法,使用内核值为 3 对生成的(灰色)图像进行模糊处理。
应用 canny使用 Imgproc 的 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.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class EdgeDetection extends Application {
public void start(Stage stage) throws IOException {
//加载 OpenCV 核心库
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
String file ="D:\Images\win2.jpg";
Mat src = Imgcodecs.imread(file);
//创建一个空矩阵来存储边、源、目标
Mat gray = new Mat(src.rows(), src.cols(), src.type());
Mat edge = new Mat(src.rows(), src.cols(), src.type());
Mat dst = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0));
//将图像转换为灰度
Imgproc.cvtColor(src, gray, Imgproc.COLOR_RGB2GRAY);
//模糊图像
Imgproc.blur(gray, edges, new Size(3, 3));
//检测边缘
Imgproc.Canny(edges, edges, 100, 100*3);
//将检测到的边缘复制到目标矩阵
src.copyTo(dst, edge);
//将矩阵转换为 JavaFX 可写图像
Image img = HighGui.toBufferedImage(dst);
WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
//设置图像视图
ImageView imageView = new ImageView(writableImage);
imageView.setX(10);
imageView.setY(10);
imageView.setFitWidth(575);
imageView.setPreserveRatio(true);
//设置场景对象
Group root = new Group(imageView);
Scene scene = new Scene(root, 595, 400);
stage.setTitle("Gaussian Blur Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
输入图片

输出
执行后,上述代码产生以下输出 −

相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

