Image Convolutions in OpenCV

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.

Performing Convolution

In order to perform convolution on an image, following steps are 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.

Syntax

void filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta, int borderType);
  • src: (input) This is the image that you want to convolve.
  • dst: (input) This image stores the final result of the convolution. It should be the same size and have the same number of channels as src. This can be the same as src (in place operation is supported).
  • ddepth: (input) This is the desired bit depth of the final result (8, 16, 32, etc). It it is negative, the depth is the same as the source image.
  • kernel: (input) The convolution kernel used to convolve the source image. This has to be a single channel, floating point matrix. If you want to apply different kernels to different channels, you need to split the channels, and convolve each of them them individually.
  • anchor: (input) The relative position of the anchor in the kernel matrix. If this is set to (-1,-1), the center of the kernel is used as the anchor point.
  • delta: (input) A value that is added to all pixels after convolution.
  • borderType: (input) Possible values for this include:
    • BORDER_REPLICATE
    • BORDER_CONSTANT
    • BORDER_REFLECT_101
    • BORDER_WARP
    • BORDER_TRANSPARENT
    • BORDER_DEFAULT (same as reflect)
    • BORDER_ISOLATED

Example

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include "iostream"
 
using namespace cv;
 
void conv2(Mat src, int kernel_size)
{
    Mat dst,kernel;
    kernel = Mat::ones( kernel_size, kernel_size, CV_32F )/ (float)(kernel_size*kernel_size);
 
    /// Apply filter
    filter2D(src, dst, -1 , kernel, Point( -1, -1 ), 0, BORDER_DEFAULT );
	namedWindow("filter1", CV_WINDOW_AUTOSIZE );
	imshow("filter1",dst);
}
 
int main ( int argc, char** argv )
{
    // Load an image
    IplImage* newImg = cvLoadImage("Desert.jpg",1);

    cvNamedWindow("Original Image", 1);
    //display the image in the window
    cvShowImage("Original Image", newImg);

    Mat src = cvarrToMat(newImg);
 
    // Load an image
    if( !src.data )  { return -1; }
 
    conv2(src,3);
 
    waitKey(0);
 
    return 0;
}

Output

Untitled

Share

You may also like...