Understand Convolution Tutorial

Advertisements


Convolution is a mathematical operation on two functions f and g. The function f and g in this case are images, since an image is also a two dimensional function.

How to perform convolution?

In order to perform convolution on an image , following steps should be taken.

  • Flip the mask (horizontally and vertically) only once.

  • Slide the mask onto the image.

  • Multiply the corresponding elements and then add them.

  • Repeat this procedure until all values of the image has been calculated.

We are going to use OpenCV function filter2D to apply convolution to images. It can be found under Imgproc package. Its syntax is given below:

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

The arguments of the functions and their description is listed below:

Sr.NoArgument & Description
1src
Source image.
2dst
Destiantion image.
3ddepth:
The depth of dst. A negative value (such as -1) indicates that the depth is the same as the source.
4kernel
The kernel to be scanned through the image.
5anchor
The position of the anchor relative to its kernel. The location Point(-1, -1) indicates the center by default.
6delta
A value to be added to each pixel during the convolution. By default it is 0.
7BORDER_DEFAULT
We let this value by default.

Example

The following example demonstrates the use of Imgproc class to perform convolution on an image of GrayScale.

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());
         }
   }
}

Output

In this example we convolve our image with the following filter(kernel). This filter results in producing original image as it is:

000
010
000

Original Image

Understand Convolution Tutorial

Convolved Image

Understand Convolution Tutorial

Advertisements
Advertisements