Please explain difference in image variance algorithms ... E-10 for all tests

2 views (last 30 days)
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
% You may need to load your own image or one of Matlab's demo images, like cameraman
load('img.mat')
nrows = size(img,1);
ncols = size(img,2);
nzs = size(img,3);
h = ones(7);
n = sum(h(:));
n1 = n - 1;
%Preinitialize
M2a = zeros(nrows,ncols,nzs);
M1a = zeros(nrows,ncols,nzs);
varImA = zeros(nrows,ncols,nzs);
M2b = zeros(nrows,ncols,nzs);
M1b = zeros(nrows,ncols,nzs);
varImB = zeros(nrows,ncols,nzs);
M2c = zeros(nrows,ncols,nzs);
M1c = zeros(nrows,ncols,nzs);
varImC = zeros(nrows,ncols,nzs);
imgSq = img.^2;
%Algorithm #1
M2a = imfilter(imgSq, h/n1 , 'symmetric');
M1a = imfilter(img, h, 'symmetric').^2 / (n*n1);
varImA = (max((M2a - M1a),0));
%Algorithm #2
M2b = imfilter(imgSq, h/n1 , 'symmetric');
M1b = imfilter(img, h/n, 'symmetric');
M1S = (M1b.^2)*n/n1;
varImB = max((M2b - M1S),0);
%Algorithm #3
for i=1:1:nzs;
M2c(:,:,i) = filter2(h, imgSq(:,:,i)) / n;
end
for i=1:1:nzs;
M1c(:,:,i) = filter2(h, img(:,:,i)) / n;
end
varImC = n/n1.*(M2c-M1c.^2);
% Test the difference (need to crop image borders to get relevant results)
Test1 = varImA(20:end-20,20:end-20,:) - varImB(20:end-20,20:end-20,:);
Test2 = varImA(20:end-20,20:end-20,:) - varImC(20:end-20,20:end-20,:);
Test3 = varImB(20:end-20,20:end-20,:) - varImC(20:end-20,20:end-20,:);
% Display results;
max(Test1(:))
min(Test1(:))
max(Test2(:))
min(Test2(:))
max(Test3(:))
min(Test3(:))
  1 Comment
Jan
Jan on 3 May 2014
Loading cameraman.tif replies an integer matrix, such that it sufficient as test data. There are some typos in "VarImB" and "VarImC", which both need a lowercase "v".

Sign in to comment.

Answers (1)

Jan
Jan on 3 May 2014
Edited: Jan on 3 May 2014
When I use img = rand(256, 256, 3) as input data and fix the typos, I get differences of the magnitude 6.6613e-16. This is 3*eps, which means, that the differences are very tiny. Such differences are caused by the limited precision of the representation of numbers. See FAQ: Why is 0.3-0.2-0.1 not equal to 0.
  1 Comment
Eric Diaz
Eric Diaz on 3 May 2014
That's kind of what I was thinking.
I'm wondering why I am getting differences on the order of E-10 with my image data, which is imported as UINT12 --> double.

Sign in to comment.

Categories

Find more on Image Processing Toolbox 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!