Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Distance Transformation ใน OpenCV พร้อมตัวอย่าง Java

Distance transform โดยทั่วไปเป็นการแทนค่าที่ได้มาจากภาพดิจิทัล ในการดำเนินการนี้ ค่าความเข้มระดับสีเทาของจุดภายใน foreground regions จะถูกเปลี่ยนเป็นระยะห่างจากค่า 0 ที่ใกล้ที่สุด (ขอบเขต)

เมธอด distanceTransform() ของคลาส Imgproc ใช้ Distance Transform บนภาพที่กำหนด เมธอดนี้รับ:

  • สองอ็อบเจ็กต์ Mat แทน source และ destination images
  • ตัวแปร integer แทนประเภทของ distance transformation
  • ค่า integer แทนขนาด mask ที่ใช้

ตัวอย่างโค้ด

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.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DistanceTransform extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        // โหลด OpenCV core library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        
        // อ่านภาพจากไฟล์เก็บใน Matrix object
        String file = "D://images//boy.jpg";
        Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE);
        
        // สร้าง matrix ว่างสำหรับผลลัพธ์
        Mat dst = new Mat();
        Mat binary = new Mat();
        
        // แปลงภาพ grayscale เป็น binary image
        Imgproc.threshold(src, binary, 100, 255, Imgproc.THRESH_BINARY);
        
        // ใช้ distance transform
        Imgproc.distanceTransform(binary, dst, Imgproc.DIST_C, 3);
        Core.convertScaleAbs(dst, dst);
        
        // แปลง 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("Distance Transform");
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

รูปภาพ Input

Distance Transformation ใน OpenCV พร้อมตัวอย่าง Java

ผลลัพธ์

เมื่อรันโปรแกรมจะได้หน้าต่างดังนี้:

Distance Transformation ใน OpenCV พร้อมตัวอย่าง Java