Java 數字影像處理 - 基本閾值化



閾值化能夠以最簡單的方式實現影像分割。影像分割是指將完整影像劃分為一組畫素,使得每組畫素具有某些共同特徵。影像分割在定義物件及其邊界方面非常有用。

在本節中,我們將對影像執行一些基本的閾值化操作。

我們使用OpenCV函式threshold。它可以在Imgproc包中找到。其語法如下所示:

Imgproc.threshold(source, destination, thresh , maxval , type);

引數說明如下:

序號 引數及描述
1

source

源影像。

2

destination

目標影像。

3

thresh

閾值。

4

maxval

對於THRESH_BINARY和THRESH_BINARY_INV閾值型別,使用的最大值。

5

type

可能的型別包括THRESH_BINARY、THRESH_BINARY_INV、THRESH_TRUNC和THRESH_TOZERO。

除了這些閾值化方法外,Imgproc類還提供了其他方法。簡要描述如下:

序號 方法及描述
1

cvtColor(Mat src, Mat dst, int code, int dstCn)

將影像從一個顏色空間轉換為另一個顏色空間。

2

dilate(Mat src, Mat dst, Mat kernel)

使用特定的結構元素膨脹影像。

3

equalizeHist(Mat src, Mat dst)

均衡灰度影像的直方圖。

4

filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)

將影像與核心進行卷積。

5

GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)

使用高斯濾波器模糊影像。

6

integral(Mat src, Mat sum)

計算影像的積分。

示例

以下示例演示瞭如何使用Imgproc類對影像執行閾值化操作:

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class main {
   public static void main( String[] args ) {
   
      try{

         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg",  Highgui.CV_LOAD_IMAGE_COLOR);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());

         destination = source;
         Imgproc.threshold(source,destination,127,255,Imgproc.THRESH_TOZERO);
         Highgui.imwrite("ThreshZero.jpg", destination);
         
      } catch (Exception e) {
         System.out.println("error: " + e.getMessage());
      }
   }
}

輸出

執行給定程式碼後,將看到以下輸出:

原始影像

Basic Thresholding Tutorial

在上面的原始影像上,執行了一些閾值化操作,輸出如下所示:

二值閾值

Basic Thresholding Tutorial

反二值閾值

Basic Thresholding Tutorial

截斷閾值

Basic Thresholding Tutorial
廣告

© . All rights reserved.