使用 Java 例項講解 OpenCV 自適應閾值


閾值化是一種影像分割的簡單技術。它通常用於建立二值影像。在此技術中,大於給定閾值的畫素將替換為標準值。

自適應閾值是一種方法,其中對於較小的區域計算閾值,因此對於不同的區域有不同的閾值。

adaptiveThreshold()方法在給定影像上執行自適應閾值操作。這是此方法的引數−

  • 兩個 Mat 物件,表示源影像和目標影像。

  • 一個整數變數,表示閾值。

  • 兩個整數變數,分別表示要使用的自適應方法和閾值型別。

  • 一個整數變數型別,表示用於計算閾值的小區畫素大小。

  • 一個雙精度型別的整數變數,表示在兩種方法中使用的常量。

示例

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 AdaptiveThreshold 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, Imgcodecs.IMREAD_GRAYSCALE);
      //Creating an empty matrices to store the destination image.
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      //Applying simple threshold
      Imgproc.adaptiveThreshold(src, dst, 125,
      Imgproc.ADAPTIVE_THRESH_MEAN_C,
      Imgproc.THRESH_BINARY, 11, 12);
      //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("Adaptive Threshold");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}

輸入影像

輸出

執行後,以上程式生成以下視窗−

更新於:2020 年 4 月 13 日

853 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.