使用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