Mittwoch, 30. September 2015

Local Variance – MATLAB CODE

Variance Formula:
Let us understand how global variance works. First let us theoretically define variance in simple terms. In lay man terms, variance is defined as how divergent values are from the average value.

Consider a matrix A=[5 5 5;5 5 5]. The variance of the matrix A is zero.. In the given example, the average is 5 and all the elements in the matrix are equal to 5. So finding deviation in the above example is not possible.

Let us consider another matrix B =[3 7 1;5 4 2]. The variance of the matrix B is 3.8889.. Let us arrive at the result using theoretical formula as follows:
Variance of B = Mean of B^2 – (mean of B)^2
                        = 17.333 – 13.444
                        = 3.888
MATLAB CODE:
Var(B(:),1)
Local Variance
Instead of finding variance for the whole matrix, variance is computed based on a small sliding window.
Steps to Perform:

MATLAB CODE:
I = imread('cameraman.tif');
figure,imagesc(I);colormap(gray);title('Original Image');

I = double(I);
%Define the window size
sz = 5;
mn=floor(sz/2);
%Preallocate the matrix
Output = zeros(size(I));
%Pad the matrix with zeros
I = padarray(I,[mnmn]);

for i=1:size(I,1)-mn*2
for j=1:size(I,2)-mn*2
tmp = I(i:i+(sz-1),j:j+(sz-1));
mu = mean(tmp(:));
        tmp2 = mean(tmp(:).^2);
Output(i,j)=tmp2 - mu.^2;
end
end

figure,imagesc(Output);colormap(gray);



Quick Implementation:




Keine Kommentare:

Kommentar veröffentlichen