10 Calculating a moving average
The background of the target we are tracking is intentionally not perfectly blank; it contains what is called salt and pepper noise. The noise in the image will complicate the process of accurately localizing the stripe target when we try to track it. We can reduce the amount of noise by performing a moving average across each row of the image.
10.1 Write a function to compute the moving average
In MATLAB, create and complete the following function:
function avg = movingAverage(x, n)
%MOVINGAVERAGE Moving average
% avg = movingAverage(x, n) returns a vector avg that is the same
% size as x where the elements of avg are the average of x taken
% over a local neighbourhood of x.
%
% More specifically, the value of avg(i) is the average value of
% the values in x from x(i - n) to x(i + n). The values of
% avg(1:n) are equal to avg(n + 1) and the values avg(end - n: end) are
% equal to avg(end - n).
%
% It is assumed that n is greater than 0.
You should pre-allocate the result vector avg
first (like in the script labF
) and then use a loop to compute the values of avg(i)
. Note that the function here is very similar to the second question that you answered in the script labF
; in fact, movingAverage(v, 1)
should return the same vector you computed in part (b) of labF
.
10.2 Test your function
Test your function by averaging the entire grayscale image gray
you computed in the previous part of this lab:
[rows, cols, layers] = size(gray);
avg = zeros(rows, cols);
for i = 1:rows
% average each row of gray
avg(i, :) = movingAverage(gray(i, :), 25);
end
% convert avg from double to an integer value between 0 and 255
avg = uint8(avg);
% show the averaged image avg
imshow(avg)
If you plot the values of one row of the grayscale image and the values of the same row in the averaged image you can see the smoothing effect that the moving average produces:
plot(gray(540, :), 'b') % the horizontal midline of the grayscale image
hold on
plot(avg(540, :), 'r') % the horizontal midline of the moving average image
hold off
My results look like the following:
Notice how the moving average has smoothed the gray level of the pixels in the image greatly reducing the effects of the salt and pepper noise.