Please explain difference in results between these variance algorithms which should be null?
1 view (last 30 days)
Show older comments
Can someone please explain why these different algorithms are giving slightly different results for the variance of an image?
%References:
- http://en.wikipedia.org/wiki/Variance#Formulae_for_the_variance
- http://www.mathworks.com/help/images/ref/stdfilt.html
- http://mathworld.wolfram.com/Variance.html
% Load images and get basic parameters
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
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;
0 Comments
Accepted Answer
Image Analyst
on 29 Apr 2014
Look up what mat2gray() does and I think you'll see the answer. If not, ask.
3 Comments
Image Analyst
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');
More Answers (0)
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!