How do I select a window of pixels around a pixel?
3 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
AJ von Alt
on 20 Jan 2014
Edited: AJ von Alt
on 20 Jan 2014
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(:) ))
More Answers (1)
deep tank
on 7 Apr 2015
Hello AJ von Alt and Rachel
Can you help me to develop matlab code for equation highlighted as RED (page 3 of 5) in attached file.....I feel it is similar to above query.
Thanks in advanced.
Regards, Dipesh
0 Comments
See Also
Categories
Find more on Read, Write, and Modify Image in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!