We will start off with an easy-to-follow example, so that all the theory described previously is demonstrated. For our purposes, we will be using one of the images from the previous chapters. In this example, we will also introduce some new MATLAB functions, to facilitate your understanding. Let's start:
holiday_image2.bmp
:>> img = imread('holiday_image2.bmp'),
fspecial
and then rotate it 180 degrees:>> kernel = fspecial('average',3); >> kernel = rot90(kernel,2)
kernel = 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111 0.1111
>> con1 = conv2(img,kernel); % Default usage ('full') >> con2 = conv2(img,kernel,'same'), % convolution using 'same' >> con3 = conv2(img,kernel,'valid'), % convolution using 'valid'
Warning: CONV2 on values of class UINT8 is obsolete. Use CONV2(DOUBLE(A),DOUBLE(B)) or CONV2(SINGLE(A),SINGLE(B)) instead.
UNIT8
type will not be supported by conv2
in the future. To be on the safe side, you might want to use the suggestion by MATLAB and convert your image to single
prior to convolving it:>> img = single(img); >> kernel = fspecial('average',3); % Create 3x3 averaging kernel >> con1 = conv2(img,kernel); % Default usage ('full') >> con2 = conv2(img,kernel,'same'), % convolution using 'same' >> con3 = conv2(img,kernel,'valid'), % convolution using 'valid'
imshow
, to avoid having to convert our results to UNIT8
:>> figure;subplot(2,2,1),imshow(img,[]),title('Original') >> subplot(2,2,2),imshow(con1,[]),title('full') >> subplot(2,2,3),imshow(con2,[]),title('same') >> subplot(2,2,4),imshow(con3,[]),title('valid')
>> tower_original = img(51:210,321:440); >> tower_blurred = con2(51:210,321:440); figure >> subplot(1,2,1),imshow(tower_original),title('Original tower') >> subplot(1,2,2),imshow(tower_blurred),title('Blurred tower')
The process described in the previous example demonstrated the usage of convolution in its various implementations, using the averaging kernel produced using fspecial
. This function is designed to generate kernels for popular filtering tasks, as we will further analyze in the following sections. In our case, we created a 3x3 kernel of values equal to 1/9 (which is almost equal to 0.1111, hence the result in step 2). Then, the three different choices of convolution were applied and the results were displayed along with the original image. Of course, a detail such as the size of the borders cannot be easily observed in full scale, so we observed the difference in the sizes of the results. Finally, we displayed a part of the original image next to the same part of the same
convolution result, to prove that the result of the averaging process is a blurring of the image.