How to find out windowwise mean and standard deviation of some particular pixels.

1 view (last 30 days)
I have a .txt file with 50 rows and 2 columns indicating 50 pixel positions in an image.I am reading that file with the following statement:
file_id=fopen('C:\Users\Mahua Nandy\PixelPositions_im1.txt','r'); Input=fscanf(file_id,'%d',[2,50]); fclose(file_id);
Input is coming in column order(2 rows and 50 columns).Now I want to find out 3x3 windowwise mean and standard deviation of those particular 50 pixels.
Please help me to code it

Answers (2)

Image Analyst
Image Analyst on 17 Feb 2013
First I guess you have to create an image - all black I guess.
maxRows = max(Input(1,:));
maxColumns = max(Input(2, :));
grayImage = zeros(maxrows, maxColumns, 'uint8');
Then you have to run down your list of coordinates, figuring out their gray level (from some other image I assume), then assigning/transferring them to the new image (the one that contains only the 50 pixels):
for c = 1 : maxColumns
for r = 1 : maxRows
row = Input(1, r);
column = Input(2, c);
% Transfer the gray level from the other image to
% this location on the new image.
grayImage(row, column) = initialImage(row, column);
end
end
Then you have to use conv2() and stdfilt() to take the mean and std dev in a 3x3 window in the new image which contains the 50 pixels.
meanImage = conv2(grayImage, ones(3)/9, 'same');
stdImage = stdfilt(grayImage);
Be aware though that most of the image will be just black pixels so the mean will be very low. Upload your image first, if you have any follow up questions.
  6 Comments
Image Analyst
Image Analyst on 19 Feb 2013
That's what conv2 does. And what exactly is in the space between your 50 isolated pixels? In an image, there has to be SOMETHING.

Sign in to comment.


Thorsten
Thorsten on 19 Feb 2013
Edited: Thorsten on 19 Feb 2013
Hi Mahua Nandy(Pal), that's all quite straight forward:
1. Let's say you have your image in I and your particular positions in variables x and y
I = imread('cameraman.tif');
x = 10; y = 20; % just for testing
To get the 3 x 3 neighborhood N around (x, y) from your image, use
N = I(y-1:y+1, x-1:x+1);
That gives you a 3 x 3 matrix. The mean and std are
m = mean(N(:));
s = std(N(:));
If you have 50 values of x and y stored in Input, you just do it in a loop:
for i=1:size(Input, 1)
x = Input(i, 1);
y = Input(i, 2);
N = I(y-1:y+1, x-1:x+1);
m(i) = mean(N(:));
s(i) = std(N(:));
end
Done!
Two caveats:
1. verify that each row of Input is [x y] and not [y x]; if the columns are given as y x use
x(i) = Input(i, 2);
y(i) = Input(i, 1);
2. ensure that no x, y lies at the boundary of I, such that x-1, x+1m, y-1 and y+1 is always a valid index to the image. To be one the save side, you could use the statement
N = I(max(1, y-1):min(size(I, 1), y+1), ...
max(1, x-1):min(size(I, 2), x+1);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!