Java DIP - 理解卷积
卷积是对两个函数 f 和 g 的数学运算。在这种情况下,函数 f 和 g 是图像,因为图像也是二维函数。
执行卷积
为了对图像执行卷积,请采取以下步骤 −
- 仅翻转蒙版(水平和垂直)一次。
- 将蒙版滑到图像上。
- 将相应元素相乘,然后将它们相加。
- 重复此过程,直到计算出图像的所有值。
我们使用 OpenCV 函数 filter2D 将卷积应用于图像。它可以在 Imgproc 包下找到。其语法如下 −
filter2D(src, dst,depth, kernel, anchor, delta, BORDER_DEFAULT );
函数参数如下所述 −
Sr.No. | 参数 &描述 |
---|---|
1 |
src 源图像。 |
2 |
dst 目标图像。 |
3 |
depth dst的深度。负值(例如 -1)表示深度与源相同。 |
4 |
kernel 它是要扫描图像的内核。 |
5 |
anchor 它是锚点相对于其内核的位置。位置点 (-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 |
原始图像

卷积图像
