MATLAB: How to select a window of pixels around a pixel

looppixelwindow

Hi
I am navigating through each pixel in an image(grayscale binary image) using a for loop. For each pixel, I need to select a window of 5*5 pixels around it and perform certain operations on it. If the operation is successful, i need to move to the next pixel, if not, I need to increase the size of the window till it is successful!
Any help will be appreciated. Thanks in advance.

Best Answer

You can access multiple elements of a matrix using a vector of indices. E.g.:
B = A( (i - 1 : i + 1) , (i-1 : i + 1) )
Consider a 3 x 3 matrix A:
A = [11 22 33 ;
44 55 66 ;
77 88 99 ];
The following command will get the sub-matrix made up of the first two rows and columns of A and store that sub-matrix in B.
B = A( 1:2 , 1:2 )
B =
11 22
44 55
The following code is an example implementation tracking the number of times the number of windows evaluated before the success condition is met.
img = double( imread( 'trees.tif') );
[ nRows , nCols ] = size( img );
result = zeros( nRows , nCols );
halfWinSize = 2;
threshold = 50;
for rI = 1:nRows
for cI = 1:nCols
% These indices specify the start and stop indices of the
% window. The window will go from row rILo to rIHi amd column
% cILo to cIHi
rILo = rI - halfWinSize; % lower row index of window
rIHi = rI + halfWinSize; % upper row index of window
cILo = cI - halfWinSize; % lower column index of window
cIHi = cI + halfWinSize; % upper column index of window
flagConditionMet = false ;
count = 1;
% while success criteria unmet
while( ~ flagConditionMet )
% It is important to make sure that your window indices are valid
% indices before pulling out the window.
if( rILo >= 1 && rIHi <= nRows && cILo >= 1 && cIHi <= nCols )
% Pull out the window around (rI , cI)
imgWindow = img( (rILo : rIHi) , (cILo : cIHi) );
%perform an operation
minVal = min( imgWindow(:) );
%check if successful
flagConditionMet = minVal < threshold;
%increase window bounds if unsuccessful
if( ~ flagConditionMet )
rILo = rILo - 1;
rIHi = rIHi + 1;
cILo = cILo - 1;
cIHi = cIHi + 1;
count = count + 1;
else
%store some result if successful
result( rI , cI ) = count;
end
else
% out of bounds break out of while loop
break;
end
end
end
end
figure;
imshow(result./max( result(:) ))
Related Question