Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
How to obtain teh variance of an image

Subject: How to obtain teh variance of an image

From: Susan

Date: 17 Apr, 2010 16:37:05

Message: 1 of 6

Hello there,

I have to admit, I am fairly new to Matlab and am running into a few problems. I am interested in image processing and I wish to read in an image, process it grid by grid (of which size I enter) and then return the obtained values to an empty array. I have attempted to use the 'blkproc' function and although it has been successful for calculating the std2 of my image, use of var (for variance) is not working.

Below you will see that to calculate the variance of each grid, I attempt to obtain the mean of the grayscale pixel values for the [MxN] grid and then apply it to each element of that grid (i.e. gridx_element, gridy_element).

Any help with my code (or if I'm using blkproc incorrectly) would very much appreciated - maybe a fresh pair of eyes will do the trick!

Kindest regards.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

i = imread('F:\\Technique comparison\\4.bmp');
Image = rgb2gray(i);

[height width]= size(Image);

% Defining grid size
N = 8;
M = 8;

SV = zeros(width, height);

% To determine how many grids in x and y direction
x = width/N;
y = height/M;

% FOR loop to determine grid
for a = 1:1:x
    for b = 1:1:y
        
         Imean(a,b) = mean(mean(Image((N*a)-(N-1):N*a,(M*b)-(M-1):M*b)));
         
% FOR loop to access [a,b] grid elements
         for gridx_element = (N*a)-(N-1):1:N*a
             for gridy_element = (M*b)-(M-1):1:M*b;
                 
                 SV(gridx_element, gridy_element) = (Imean(a,b) - (Image(gridx_element, gridy_element))).^2/(sqrt(N*M));
                 
            end
         end
         hold on;
    end
end
hold on;

figure, imshow(SV(:, :)), title('Computed Speckle Variance of OCT Image');

Subject: How to obtain teh variance of an image

From: Roger Stafford

Date: 17 Apr, 2010 19:36:05

Message: 2 of 6

"Susan " <Cooma_kista@yahoo.co.uk> wrote in message <hqco3h$snm$1@fred.mathworks.com>...
> Hello there,
>
> I have to admit, I am fairly new to Matlab and am running into a few problems. I am interested in image processing and I wish to read in an image, process it grid by grid (of which size I enter) and then return the obtained values to an empty array. I have attempted to use the 'blkproc' function and although it has been successful for calculating the std2 of my image, use of var (for variance) is not working.
>
> Below you will see that to calculate the variance of each grid, I attempt to obtain the mean of the grayscale pixel values for the [MxN] grid and then apply it to each element of that grid (i.e. gridx_element, gridy_element).
>
> Any help with my code (or if I'm using blkproc incorrectly) would very much appreciated - maybe a fresh pair of eyes will do the trick!
>
> Kindest regards.
> .......

  As for using 'blkproc' why don't you just square the results you get from 'std2' to get the desired variance values. After all, the variance is simply the square of the standard deviation. The reason you have trouble with passing the raw 'var' to 'blkproc' is that 'var' returns a row of column variances for a block rather than a single scalar. The same is true of 'std', which is no doubt why 'std2' was written. You could of course write your own version of what you could call 'var2' as: "var2(A) = var(A(:));" and pass that to 'blkproc'. It would correctly compute the desired single scalar variance for the entire A block.

  As for the code you have written, you shouldn't divide by sqrt(N*M). That is a serious error. You're confusing variance with standard deviation. You should divide by M*N if you are doing population variance or by M*N-1 if it is sample variance.

  In your for-loops you haven't added the variance terms together to form a single variance for each block. You just have the separate squared quantities occupying another block the same size as the block they were derived from. I think you want these all summed and placed in a single entry in a smaller matrix just as you have done for the mean values.

Roger Stafford

Subject: How to obtain teh variance of an image

From: Susan

Date: 17 Apr, 2010 20:44:05

Message: 3 of 6

Hi Roger,

Indeed, I did use the blkproc function and square it to obtain the variance using the 'anonymous' form of the blkproc function. The code I used to implement this is given by the following. The only remaining objective I wish to accomplish is to implement a threshold variance value above which all other values are zero and I wish to assign a colour to the remaining pixels (it is a rgb to grayscale image). I placed the 'if' loop within the following and it doesn't seem to work.

Any comments and/or suggestions I would very much appreciate!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% variance of image grids
SV = zeros(height, width);

for y = 1:1:width
    for x = 1:1:height
        SV(x,y) = I2(x,y).^2;

% Apply Threshold
         if SV(x,y) > (0.1*(min(min(SV))+min(min(SV))))
             SV(x,y) = 0;
        else
             SV(x,y);
         end

    end
    hold on;
end
subplot(4,1,3);
imshow(SV, []), title('Var of Image'), colormap(hot);

Subject: How to obtain teh variance of an image

From: ImageAnalyst

Date: 18 Apr, 2010 19:11:02

Message: 4 of 6

Susan:
Like I said in your duplicate post, that code looks bogus. Here's
something you may want to take a look at:
Be sure to fix any lines split into two by the newsreader.

% Demo to take the local mean, variance, and standard deviation
% of a gray scale image.
% userImage, if passed in, is used as the image.
% If userImage is not passed in, user is asked to use a demo image.
% Code written by ImageAnalyst
function local_variance(userImage)
% Clean up.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.

% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
% Don't use these lines if you're calling this from another m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end

% Initialize.
fontSize = 20;
if nargin == 0
    % No image passed in on the command line.
    % Read in one of the standard MATLAB demo images
    % as our original gray scale image and display it.
    promptMessage = sprintf('Which image do you want to use.\nThe
coins or the cameraman?');
    button = questdlg(promptMessage, 'Select Image', 'Coins',
'Cameraman', 'Coins');
    if strcmp(button, 'Coins')
        grayImage = double(imread('coins.png')); % Cast to double.
    else
        grayImage = double(imread('cameraman.tif')); % Cast to double.
    end
else
    % Use the image array passed in on the command line.
    grayImage = double(userImage); % Cast to double.
end

% Start timing.
startTime = tic;

subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.

% Blur the image with a 5 by 5 averaging (box filter) window.
blurredImage = conv2(grayImage, ones(5,5)/25);
subplot(2, 2, 2);
imshow(blurredImage, []);
title('Blurred Image', 'FontSize', fontSize);

% Perform a variance filter.
% Output image is the variance of the input image in a 3 by 3 sliding
window.
VarianceFilterFunction = @(x) var(x(:));
varianceImage = nlfilter(grayImage, [3 3], VarianceFilterFunction);
% An alternate way of doing the variance filter is on the next line:
% varianceImage = reshape(std(im2col(originalImage,[3 3],'sliding')),
size(originalImage)-2);
subplot(2, 2, 3);
imshow(varianceImage, [])
title('Variance Image', 'FontSize', fontSize);

% Compute the square root of the variance image to get the standard
deviation.
standardDeviationImage = sqrt(varianceImage);
subplot(2, 2, 4);
imshow(standardDeviationImage, [])
title('Standard Deviation Image', 'FontSize', fontSize);
elapsedTime = toc(startTime);

message = sprintf('Done!\n\nElapsed time = %.2f seconds.',
elapsedTime);
msgbox(message);
return; % End of local_variance() function.

Subject: How to obtain teh variance of an image

From: David Young

Date: 19 Apr, 2010 17:54:04

Message: 5 of 6

It's possible that you will find the patch_var function, available from the file exchange here:

http://www.mathworks.com/matlabcentral/fileexchange/27269-image-correspondences-using-cross-correlation

useful for computing the variances of image patches, especially if you want it done quickly.

Subject: i would like to know about adaptive shrinkage and how it could be obtained in matlab

From: karthi karthika

Date: 7 Oct, 2010 16:43:05

Message: 6 of 6

"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <hqd2j5$5vn$1@fred.mathworks.com>...
> "Susan " <Cooma_kista@yahoo.co.uk> wrote in message <hqco3h$snm$1@fred.mathworks.com>...
> > Hello there,
> >
> > I have to admit, I am fairly new to Matlab and am running into a few problems. I am interested in image processing and I wish to read in an image, process it grid by grid (of which size I enter) and then return the obtained values to an empty array. I have attempted to use the 'blkproc' function and although it has been successful for calculating the std2 of my image, use of var (for variance) is not working.
> >
> > Below you will see that to calculate the variance of each grid, I attempt to obtain the mean of the grayscale pixel values for the [MxN] grid and then apply it to each element of that grid (i.e. gridx_element, gridy_element).
> >
> > Any help with my code (or if I'm using blkproc incorrectly) would very much appreciated - maybe a fresh pair of eyes will do the trick!
> >
> > Kindest regards.
> > .......
>
> As for using 'blkproc' why don't you just square the results you get from 'std2' to get the desired variance values. After all, the variance is simply the square of the standard deviation. The reason you have trouble with passing the raw 'var' to 'blkproc' is that 'var' returns a row of column variances for a block rather than a single scalar. The same is true of 'std', which is no doubt why 'std2' was written. You could of course write your own version of what you could call 'var2' as: "var2(A) = var(A(:));" and pass that to 'blkproc'. It would correctly compute the desired single scalar variance for the entire A block.
>
> As for the code you have written, you shouldn't divide by sqrt(N*M). That is a serious error. You're confusing variance with standard deviation. You should divide by M*N if you are doing population variance or by M*N-1 if it is sample variance.
>
> In your for-loops you haven't added the variance terms together to form a single variance for each block. You just have the separate squared quantities occupying another block the same size as the block they were derived from. I think you want these all summed and placed in a single entry in a smaller matrix just as you have done for the mean values.
>
> Roger Stafford

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us