In: Computer Science
(Using Matlab) Write a function to "smooth" a black-and-white image by replacing each pixel by the average of itself and its neighbors. In MATLAB a black-and-white image is just a matrix of 1s and 0s - 1 represents white, and 0 represents black.
To keep the algorithm simple, ignore the edges of the image - that is, do not change the first and last rows and columns.
function name = smooth_image()
input argument = input matrix
output argument = output matrix
The algorithm can be described as follows:
function f=smooth(arrIn)
%copy the matrix
y=arrIn;
side1 = size(y)(1,1); %determine the row of the matrix
side2 = size(y)(1,2); %determine the column of the matrix
t = ones(3)/9; % create a smoothing filter .. it is matrix of ones divided by 9 to give average value
for m = 2:side1-1 %traverse the matrix from row 2 to previous to
the end row
for n=2:side2-1 % traverse the matrix from
column 2 to previous to the end of column
mat = arrIn(m-1:m+1,n-1:n+1); % get the 3x3
matrix to be processed
y(m,n)=round(conv2(mat,t)(3,3)); % convolution
is done between the matrices and centre value which represents the
mean value is taken and put back into y matrix
end
end
f=y; % y matrix returned
end
=====================================================
example matrix and its smoothed matrix
===================================================
N.B: convolution of two matrix is simply multiplying the given matrix by the other matrix while shifting the other matrix over the first matrix.
So for each location in the matrix, that location is aligned with the center of the other matrix and respective elements are multiplied together and summed.
Here in this case the other matrix is 3x3, so when 3x3 matrix convoluted with 3x3 matrix it will give 5x5 matrix. element (3,3) will be the one needed because it will be the one where each of the respective element will be multiplied with each other and summed up..