## Please explain difference in results between these variance algorithms which should be null?

### Eric Diaz (view profile)

on 29 Apr 2014
Latest activity Commented on by Eric Diaz

on 30 Apr 2014

### Image Analyst (view profile)

Can someone please explain why these different algorithms are giving slightly different results for the variance of an image?
%References:
% Load images and get basic parameters
nrows=size(img,1);
ncols=size(img,2);
nzs=size(img,3);
h = ones(7);
n = sum(h(:));
n1 = n - 1;
%Preinitialize
conv1=zeros(nrows,ncols,nzs);
conv2=zeros(nrows,ncols,nzs);
varIm=zeros(nrows,ncols,nzs);
En=zeros(nrows,ncols,nzs);
Mn=zeros(nrows,ncols,nzs);
Vn=zeros(nrows,ncols,nzs);
gImgSq=mat2gray(Img.^2);
gImg=mat2gray(Img);
%Algorithm #1
conv1 = imfilter(gImgSq, h/n1 , 'symmetric');
conv2 = imfilter(gImg, h, 'symmetric').^2 / (n*n1);
VarIm = (max((conv1 - conv2),0));
%Algorithm #2
for i=1:1:nzs;
En(:,:,i)=filter2(h, gImgSq(:,:,i)) / n;
end
for i=1:1:nzs;
Mn(:,:,i)=filter2(h, gImg(:,:,i)) / n;
end
Vn = n/n1.*(En-Mn.^2);
%Test the difference
Test= VarIm - Vn;

### Image Analyst (view profile)

on 29 Apr 2014

Look up what mat2gray() does and I think you'll see the answer. If not, ask.

Eric Diaz

### Eric Diaz (view profile)

on 29 Apr 2014
Not sure. Are you trying to say that it has something to do with the double type? Want to throw me another bone here... I would prefer just an explanation as opposed to this vagueness
Image Analyst

### Image Analyst (view profile)

on 30 Apr 2014
mat2gray says "The returned matrix I contains values in the range 0.0 (black) to 1.0 (full intensity or white)" So if you put both the image and the image squared through that function, it will normalize both to 0-1, which destroys the relationship. Let's say the max value was 200, and so the max squared value will be 4000. But you put them both through mat2gray, and now that location has a value of 1 for both the image and the image squared. Here, run this illustration to see how the relative relationship changes:
workspace
x=1:20;
y1 = x;
y2 = x.^2;
subplot(2,1,1);
plot(x,y1, x,y2, 'LineWidth', 3);
grid on;
title('No mat2gray');
ym1 = mat2gray(x);
ym2 = mat2gray(x.^2);
subplot(2,1,2);
plot(x,ym1, x,ym2, 'LineWidth', 3);
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
title('With mat2gray');
Eric Diaz

### Eric Diaz (view profile)

on 30 Apr 2014
Oh, I see what you are saying. Thank you for the clarification.
I'm wondering though whether in the end that would cause the problem I am getting. The reason that I'm wondering that is because both algorithms square the same variables, convert to grayscale and take the differences. Does this come down to a significant digits and/or catastrophic cancellation problem?