Erosion และ dilation เป็น 2 morphological operations พื้นฐาน ตามชื่อ Morphological operations คือชุดการดำเนินการที่ประมวลผลภาพตามรูปร่างของมัน
ใน dilation operation จะเพิ่มพิกเซลเข้าไปที่ขอบเขตภาพ และใน erosion operation จะลบพิกเซลออกจากขอบเขตภาพ จำนวนพิกเซลที่เพิ่มขึ้นใน dilation ขึ้นอยู่กับมิติของ structuring element ที่ใช้
Morphological Gradient คือการดำเนินการที่เท่ากับความต่างระหว่าง dilation และ erosion ของภาพ ค่าพิกเซลแต่ละจุดในภาพผลลัพธ์บ่งชี้ความเข้มของความคมชัดในพิกเซลใกล้เคียง ใช้ใน edge detection, segmentation และหาขอบเขตของวัตถุ
ตัวอย่างโค้ด
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 MorphologicalGradient extends Application {
@Override
public void start(Stage stage) throws IOException {
// โหลด OpenCV core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// อ่านข้อมูลภาพ
String file = "D:\\Images\\morph_input1.jpg";
Mat src = Imgcodecs.imread(file);
// สร้าง destination matrix
Mat dst = new Mat(src.rows(), src.cols(), src.type());
// เตรียม kernel matrix
Mat kernel = Mat.ones(5, 5, CvType.CV_32F);
// ใช้ morphologyEx แบบ GRADIENT
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_GRADIENT, kernel);
// แปลง matrix เป็น JavaFX writable image
Image img = HighGui.toBufferedImage(dst);
WritableImage writableImage = SwingFXUtils.toFXImage((BufferedImage) img, null);
// ตั้งค่า ImageView
ImageView imageView = new ImageView(writableImage);
imageView.setX(10);
imageView.setY(10);
imageView.setFitWidth(575);
imageView.setPreserveRatio(true);
// ตั้งค่า Scene
Group root = new Group(imageView);
Scene scene = new Scene(root, 595, 400);
stage.setTitle("Morphological Gradient");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
รูปภาพ Input

รูปภาพ Output
