# Convolution and Correlation –> Image filtering and Template matching

In image processing, most of the time the used of convolution and correlation for filtering is more to personal preferences, as they perform almost the same operation. They are identical if the kernel is symmetrical.

In general, we use convolution for image smoothing, while correlation for template matching.

Figure 1: Convolution Operation for an Image and Kernel

Figure 2: Correlation Operation for an Image and Kernel

There are couples of functions in Scilab could be used for convolution or correlation, such as function “conv2” and “filter2”. However, these 2 functions from Scilab core functions only support image of double data type. So in our example, we are going to use a function from Image Processing module, which is “imfilter”. By default, imfilter performs correlation.

**Convolution as Image Filtering**

- Load and visualise an image which is distorted by noise.

*–>S = imread(‘balloons_noise.png’);*

*–>imshow(S);*

- Create an filter kernel, which will perform averaging operation on the image.

*–>h = 1/25.*ones(5,5)*

h =

0.04 0.04 0.04 0.04 0.04

0.04 0.04 0.04 0.04 0.04

0.04 0.04 0.04 0.04 0.04

0.04 0.04 0.04 0.04 0.04

0.04 0.04 0.04 0.04 0.04

- Apply the filter kernel to the image by using “imfilter” function.

*–>S2 = imfilter(S,h);*

*–>imshow(S2);*

**Correlation as Template Matching**

- Load the image of an article and visualize it.

*–>S = imread(‘text.png’);*

*–>imshow(S);*

- In image processing, we used to treat the object as white and background as black, hence, we convert the image to negative image by using “imcomplement” function.

*–>S2 = imcomplement(S);*

*–>imshow(S2);*

- Now, load a template of letter a which is cropped from the original text as the kernel, and convert to its complement image.

*–>h = imread(‘a.png’);*

*–>h2 = imcomplement(h);*

*–>imshow(h2);*

* *

- Convert both image and template (kernel) to double data type.

*–>S3 = im2double(S2);*

*–>h3 = im2double(h2);*

- Use the “imfilter” function to perform correlation, then normalizes and shows the image.

*–>S4 = imfilter(S3,h3);*

*–>S5 = imnorm(S4);*

*–>imshow(S5);*

* *

- Do note that the letter which is the most “correlated” to the template would have highest intensity. In ideal condition, the location should return a value of ‘1’ in normalized image. In practical, we set a threshold of 0.9 to identify the location of letter ‘a’ (template).

*–>a_loc = S5 > 0.9;*

*–>[rows, cols] = find(a_loc);*

*–>imshow(S);*

*–>sz = size(S);*

*–>plot(cols,sz(1)-rows,’r.’);*

* *