Filter2D操作將影象與核心進行折積。可以使用imgproc
類的Filter2D()
方法在影象上執行此操作。 以下是這種方法的語法 -
filter2D(src, dst, ddepth, kernel)
該方法接受以下引數 -
Mat
物件。Mat
物件。Mat
物件。以下程式演示如何在給定影象上執行Filter2D濾鏡操作。
package com.yiibai.filtering;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Filter2D {
public static void main(String[] args) {
// Loading the OpenCV core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Reading the Image from the file and storing it in to a Matrix object
String file = \\\"F:/worksp/opencv/images/sample2.jpg\\\";
Mat src = Imgcodecs.imread(file);
// Creating an empty matrix to store the result
Mat dst = new Mat();
// Creating kernel matrix
Mat kernel = Mat.ones(2, 2, CvType.CV_32F);
for (int i = 0; i < kernel.rows(); i++) {
for (int j = 0; j < kernel.cols(); j++) {
double[] m = kernel.get(i, j);
for (int k = 1; k < m.length; k++) {
m[k] = m[k] / (2 * 2);
}
kernel.put(i, j, m);
}
}
Imgproc.filter2D(src, dst, -1, kernel);
Imgcodecs.imwrite(\\\"F:/worksp/opencv/images/sample2filter2d.jpg\\\", dst);
System.out.println(\\\"Image Processed\\\");
}
}
假定以下是上述程式中指定的輸入影象sample2.jpg
。
執行上面範例程式碼,得到以下結果 -