CSC 370

Exploring Convolution

 

The goal of this lab exercise is to investigate the behavior of the convolution operation, first in one dimension and then in two.

Convolution in One Dimension

Set up the following variables in your Matlab workspace:

% 1D functions:
a = [zeros(1,100), ones(1,100)];
b = [zeros(1,100), 1, zeros(1,100)];
c = [zeros(1,50), linspace(0,1,100), ones(1,50)];
d = [zeros(1,50), linspace(0,1,50), linspace(1,0,50), zeros(1,50)];
% filter kernels:
f = fspecial('gaussian',[1 21],3);
g = [-1 1];

Use the plot command to visualize the shape of each one. Next, visualize the result of convolving each of the first four with each of the last two. You should use a command something like this:

plot(conv(a,f,'valid'));

Does the order of the inputs matter?

The 'valid' argument omits areas subject to edge effects. Investigate the other options for this argument, and see if you can understand the results they give.

Convolution in Two Dimensions

Set up the following variables in your Matlab workspace:

% 2D functions:
a2 = [zeros(200,100), ones(200,100)];
b2 = padarray(1,[100 100]);
c2 = padarray(ones(1,100),[100,50]);
d2 = padarray(ones(100,100),[50,50]);
e2 = padarray(padarray(zeros(100,100),[1 1],1),[50,50]);
% filter kernels:
f2 = fspecial('gaussian',[21 21],3);
g2 = [-1 1];
h2 = [-1 1]';

Use the imshow and surf commands to visualize the shape of these 2D functions, and the results of convolving each of the first five with each of the last three. Do the results look as you predicted?

Next, try the three filters on some real images. You may load your own, or use some of the ones that are provided built-in to Matlab. Here's one example of loading an image and convolving it using convn (for RGB color images). Note that imread brings the image in as unsigned integer data scaled from 0 to 255, and the data must be type converted and rescaled to range from 0 to 1 before doing any mathematical computations like a convolution.

img = imread('peppers.png');
imshow(img)
imshow(convn(double(img)/255,f2,'valid'))

Exercises

Try to devise filters that will acoomplish the following:

  1. Shift the image by one pixel upwards.
  2. Create a "double exposure", where the same image is superimposed on itself with a shifted position.
  3. Create a motion-blur effect, as though the camera was moved in a straight line while the shutter was open.
  4. Write your own convolution function in Matlab. (See here for pseudocode and hints.)