使用Java解釋OpenCV中的形態學開運算。
形態學操作是一組根據給定形狀處理影像的操作。腐蝕和膨脹是兩種基本的形態學操作。
在膨脹過程中,額外的畫素被新增到影像邊界。
在腐蝕過程中,額外的畫素從影像邊界移除。
新增/移除的畫素總數取決於所用結構元素的尺寸。您可以分別使用erode()和dilate()方法執行腐蝕和膨脹操作。
除了膨脹之外,OpenCV還提供了更多形態學變換,例如開運算、閉運算、形態學梯度、頂帽、黑帽。
形態學開運算
這是一種等同於先對影像進行腐蝕,然後對結果影像進行膨脹的操作。使用它,您可以從前景影像中去除小物體,同時保留大物體的特徵。
您可以使用**morphologyEx()**方法將其應用於影像。此方法接受:
兩個Mat物件,分別表示源影像和目標影像。
一個整數變數,表示形態學操作的型別。
一個Mat物件,表示核心矩陣。
要將形態學開運算應用於影像,您需要透過將**Imgproc.MORPH_OPEN**作為(第3個)引數呼叫上述方法,以及源目標和核心矩陣。
示例
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.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class MorphologicalOpening extends Application {
public void start(Stage stage) throws IOException {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading image data
String file ="D:\Images\morph_input2.jpg";
Mat src = Imgcodecs.imread(file);
//Creating destination matrix
Mat dst = new Mat(src.rows(), src.cols(), src.type());
//Preparing the kernel matrix object
Mat kernel = Mat.ones(5,5, CvType.CV_32F);
//Applying dilate on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_OPEN, kernel);
//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("Dilation Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}輸入影像

輸出
執行上述程式後,將生成以下輸出:

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP