Java OpenCV示例:Canny邊緣檢測。
Canny邊緣檢測器被稱為最優檢測器,因為它僅檢測存在的邊緣,每個邊緣只產生一個響應,並將邊緣畫素與檢測到的畫素之間的距離最小化。
Imgproc類的**Canny()**方法對給定影像應用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.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 { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); String file ="D:\Images\win2.jpg"; Mat src = Imgcodecs.imread(file); //Creating an empty matrices to store edges, source, destination Mat gray = new Mat(src.rows(), src.cols(), src.type()); Mat edges = new Mat(src.rows(), src.cols(), src.type()); Mat dst = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0)); //Converting the image to Gray Imgproc.cvtColor(src, gray, Imgproc.COLOR_RGB2GRAY); //Blurring the image Imgproc.blur(gray, edges, new Size(3, 3)); //Detecting the edges Imgproc.Canny(edges, edges, 100, 100*3); //Copying the detected edges to the destination matrix src.copyTo(dst, edges); //Converting matrix to JavaFX writable image Image img = HighGui.toBufferedImage(dst); 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("Gaussian Blur Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } }
輸入影像
輸出
執行上述操作後,將產生以下輸出:
廣告