MATLAB Answers


Finding Local mean value of pixels of window

Asked by Emerson Nithiyaraj on 19 Mar 2019
Latest activity Commented on by Nehal fawzy on 7 Apr 2019
Accepted Answer by Jan
I want to solve the equation (1,2) in the attached picture which (2) tells the local mean value of the window. But i don't have any idea about how to evaluate this equation using matlab code. I could only guess w indicates window size. If i fix w=5 in this equation (2), then m and n starts from negative values. What does g(m,n) means? Can anyone please help me to solve this concept? I have tried some coding and please helpme to solve this.
for i = 1:size(a,1) %a is my input image
for j = 1:size(a,2)
for m = i-(w/2):i+(w/2)
for n = j-(w/2):j+(w/2)
Output(i,j)= (1/(w*w))*Output(m,n);

  1 Comment

can u help me i work in u point when i enter u code with image (a)
there is error
Output(i,j)= (1/(w*w))*Output(m,n);
how i can rewrite it

Sign in to comment.

1 Answer

Answer by Jan
on 19 Mar 2019
Edited by Jan
on 19 Mar 2019
 Accepted Answer

A simple approach:
w = 5;
w2 = floor(w / 2);
sA = size(a);
SumA = zeros(sA);
DivA = zeros(sA);
for i = 1:sA(1) %a is my input image
for j = 1:sA(2)
for m = max(1, i-w2):min(i+w2, sA(1)) % Consider boundaries
for n = max(1, j-w2):min(j+w2, sA(2))
SumA(i,j) = SumA(i, j) + a(m,n);
DivA(i,j) = DivA(i, j) + 1;
Output = SumA ./ DivA;
Now the Output is the average over 5x5 elements except for the edges, which use less elements for averaging.
This can be done much faster with conv2:
Output = conv2(ones(5,1)/5, ones(1,5)/5, a, 'same');
This differs at the boundaries.


Thankyou for your response. So when I implement your first program it has used less numbers of components for averaging edge components as shown in DivA variable.
But i couldnt get the same answer along the edges when i run the program that you have given and when i use the conv2 function for the same input data. Since conv2 function uses fixed window size ,say 5 all through the input data. But in the first program the window size keeps on changing in the edges so it produces different values at edges. Could you please clarify? Is there any way to get same values at edges too?
Below Output 1 belongs to conv2 function's output, Output belongs to the first code's output. ans.jpg
Can You please tell me the difference between these two lines. Does these two representations of conv2 function using 5*5 window provides any changes?
Output1 = conv2(ones(5,1)/5, ones(1,5)/5, a, 'same');
Output2 = conv2(a,ones(5)/25,'same');

Sign in to comment.