calculating the average in a matrix

2 views (last 30 days)
Jack Williams
Jack Williams on 16 May 2011
I want to calculate the average of a 3x3 matrix and replace the middle value with the calculated average of it and the 8 around it. I also want to repeat this in order to 'smooth' an image. my image is a 200x200 matrix read from a png file.( I read it using imread earlier). so what I am doing (or trying to do) is going through the whole image and averaging out the values in 3x3 matrices. (I am ignoring the border ones because they don't have 8 values surrounding them) This is the code that I wrote:
[rows, cols, colors]= size(image{1});
for rows=2:1:199, cols=2:1:199;
ave=mean(mean([image{1}(rows,cols), image{1}(rows+1, cols), image{1}(rows-1, cols), image{1}(rows,cols+1), image{1}(rows,cols-1), image{1}(rows-1,cols+1), image{1}(rows-1,cols-1), image{1}(rows+1, cols+1), image{1}(rows+1, cols-1)]));
image{1}(rows,cols,colors)= ave;
end
firstly, can anyone see something wrong with the code?
I then wanted to add up all of the pixels that were above 220 in this new image so I wrote :
sum(sum(image{1}>220))
But I get 0 when im pretty sure im supposed to get a few. So there is something wrong somewhere with my coding and I think it has to do with the line
image{1}(rows,cols,colors)= ave;
or maybe my for loop is wrong.
Any help is greatly appreciated!
Thanks

Answers (1)

Sean de Wolski
Sean de Wolski on 16 May 2011
I = your_image;
Ismoothed = cast(conv2(double(I),ones(3)/9,'valid'),class(I));
A windowing average is just a convolution with a kernel of ones(size_window)/n_elements_in_window.
EDIT: changed same to valid since OP is ignoring border values.
  3 Comments
Sean de Wolski
Sean de Wolski on 16 May 2011
No. I don't I didn't look at your code. Unless this is a homework assignment and you're forced to do this with double for-loops then there is no reason to do a windowing average in that manner.
Sean de Wolski
Sean de Wolski on 16 May 2011
There still isn't any reason to use cell arrays even if you have to do double for-loops
for ii = size(I,1)-1:-1:2;
for jj = size(I,2)-1:-1:2
Ismoothed(ii,jj) = sum(sum(I(ii-1:ii+1,jj-1:jj+1)))/9;
end
end

Sign in to comment.

Categories

Find more on Images in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!