I need a code that produce a moving average matrix with a 5*5 window

28 次查看(过去 30 天)
Hello everyone,
I have an image of 2781 * 1680, and I want to calculate the average of each pixel with a 5 * 5 sliding window that will move throughout the matrix. Knowing that I use matlab 2010 and that I do not have the function movmean.

采纳的回答

Chad Greene
Chad Greene 2017-9-26
The conv2 function performs 2D convolution of two matrices. One of those matrices is your 2781x1680 dataset, and the other matrix is 5x5 in size.
Convolution works like a weighted moving average. For the sake of simplicity let's talk about a 3x3 moving window. It will look like this:
C = conv2(A,B,'same');
When convolving some matrix A with a 3x3 matrix B, the value assigned to each pixel will be the sum of the central pixel in A and all eight of its neighboring pixels, but in the 3x3 moving window each pixel in A is multiplied by the corresponding value in B before summing. It's not just a moving average, it's a weighted moving average. If you let B=ones(3,3), the resulting C would be a a 3x3 moving average of A, but would have about 9 times the magnitude of A. You have to divide B by 9 (for a 3x3 moving average) to keep C from having about 9 times the magnitude of A. Run this section of code to see what I mean:
A = peaks(50)+randn(50);
B = ones(3,3)/3^2;
C = conv2(A,B,'same');
figure
subplot(1,2,1)
imagesc(A)
axis image
colorbar
subplot(1,2,2)
imagesc(C)
axis image
colorbar
Look closely at the values on the colorbar. They're about the same in both images. Some of the highest highs and lowest lows in A have been smoothed out, so the range of values in C is slightly smaller, but still, about the same. Now run the same section of code, but let
B = ones(3,3);
or for that matter, try
B = 15;
Note the 'same' option just makes sure the output matrix C is the same size as A.

更多回答(1 个)

John D'Errico
John D'Errico 2017-9-26
编辑:John D'Errico 2017-9-26
I'll bet that you do have a simple function that will solve the problem.
Hint:
help conv2
If that is insufficient, then what does
ones(5,5)/25
do for you?

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by