I am unable to understand what happening in this code of Variance of 3*3 neighborhood

1 view (last 30 days)
what is (2*r+1)*(2*r+1) window? and I cannot understand what's happening inside loop? Please help me out...Code in given below.
function Out = ImVar(I,r)
% Calculate the neighbourhood variance of each pixel in I at (2*r+1)*(2*r+1) window.
% Code Author: Fei KOU
% Email: koufei@hotmail.com
% Date: 12/2/2014
[M,N,n] = size(I);
Out = double(zeros(M,N,n));
for k = 1:n
for i = 1:M
for j = 1:N
xlow = max (1,(i-r));
xupp = min (M,(i+r));
ylow = max (1,j-r);
yupp = min (N,j+r);
S1=0;
S2=0;
S3=0;
for ii=xlow:xupp
for jj=ylow:yupp
S1=S1+I(ii,jj,k);
S2=S2+I(ii,jj,k)^2;
S3=S3+1;
end
end
S1=S1/S3;
S2=S2/S3;
Out(ii,jj,k) = S2-S1^2;
end
end
end

Answers (1)

dpb
dpb on 4 Dec 2018
Just the point(s) r away from each point in the input image array in each plane. If the image were 256x256, and r were 5, say, then xlow, xupp for each point would start out at
xlow = max (1,(i-r));
for i=1, max(1,1-5) --> 1 similarly until i>r at which time then max(1,I-r) --> max(1,5-5) --> max(1,0) --> 1
xupp is symmetric excepting it's preventing the subsequent loop over ii from exceeding M just as xlow prevents addressing elements outside the array on the lower range.
Take and element out in the middle somewhere-- i=130, j=100
xlow=max( 1,130-5) --> 125
xupp=min(256,130+5) --> 135
ylow=max( 1,100-5) --> 95
yupp=min(256,100+5) --> 105
so, the variance is computed for each point over that square of points around each i,j of the array.
The function blockproc in the Image Processing Toolbox does this for any aribtrary function handle rather than having to "roll your own".
  2 Comments
Image Analyst
Image Analyst on 14 Jan 2019
r is like the radius, or really the half width of the scanning square box window. So what he means by (2*r+1)*(2*r+1) is that the neighborhood (scanning filter window) is (2*r+1) high by (2*r+1) wide.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!