Java 數字影像處理 - 理解卷積



卷積是兩個函式 f 和 g 的數學運算。在這種情況下,函式 f 和 g 是影像,因為影像也是一個二維函式。

執行卷積

為了對影像執行卷積,需要執行以下步驟:

  • 僅翻轉一次掩碼(水平和垂直)。
  • 將掩碼滑到影像上。
  • 將相應的元素相乘,然後相加。
  • 重複此過程,直到計算出影像的所有值。

我們使用 **OpenCV** 函式 **filter2D** 將卷積應用於影像。它可以在 **Imgproc** 包下找到。其語法如下所示:

filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );

函式引數如下所述:

序號 引數及說明
1

src

它是源影像。

2

dst

它是目標影像。

3

depth

它是 dst 的深度。負值(例如 -1)表示深度與源相同。

4

kernel

它是要掃描影像的核心。

5

anchor

它是錨點相對於其核心的位置。預設情況下,位置 Point(-1, -1) 表示中心。

6

delta

它是卷積期間要新增到每個畫素的值。預設值為 0。

7

BORDER_DEFAULT

我們預設使用此值。

示例

以下示例演示瞭如何使用 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 convolution {
   public static void main( String[] args ) {
   
      try {
         int kernelSize = 3;
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         
         Mat source = Highgui.imread("grayscale.jpg",  Highgui.CV_LOAD_IMAGE_GRAYSCALE);
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         
         Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {
            {
               put(0,0,0);
               put(0,1,0);
               put(0,2,0);

               put(1,0,0);
               put(1,1,1);
               put(1,2,0);

               put(2,0,0);
               put(2,1,0);
               put(2,2,0);
            }
         };
         
         Imgproc.filter2D(source, destination, -1, kernel);
         Highgui.imwrite("original.jpg", destination);
         
      } catch (Exception e) {
          System.out.println("Error:" + e.getMessage());
      }
   }
}

輸出

在這個例子中,我們用以下濾波器(核心)對我們的影像進行卷積。此濾波器導致產生原始影像本身:

0 0 0
0 1 0
0 0 0

原始影像

Understand Convolution Tutorial

卷積影像

Understand Convolution Tutorial
廣告

© . All rights reserved.