Here's a quick tip. A user question came in recently that involved a step of finding the pixels adjacent to foreground pixels in a binary image. Suppose you have a binary mask image, like this one:
bw = imread('circles.png');
imshow(bw)
How can you find all the black pixels in bw that are immediately adjacent to a white pixel? You can do this using imdilate and a logical operation.
Use imdilate to "grow" the mask by one pixel:
bw2 = imdilate(bw, ones(3,3));
Now use a logical operation to find which pixels are white in bw2 but black in bw:
bw3 = bw2 & ~bw;
imshow(bw3)
title('Adjacent pixels')
Or do it in one step:
adjacent_pixels = imdilate(bw, ones(3,3)) & ~bw;
Get
the MATLAB code
Published with MATLAB® 7.4

Is this not more of an edge detection problem? Can we not just find the gradient and obtain this output? May be I am missing something here, but, dilation by one pixel and checking for that pixel effectively shows us the edges, right? Is there some place where a mere gradient finder won’t work?
VS
VS—Using a gradient finder / edge detector is significant overkill for this problem. Dilation is simpler and much faster.
Does this method provide the same results as using ‘bwboundaries’? If not, how do the two differ?
Thanks,
TJ
TJ—No, this method returns different results in a different form. This method finds background pixels adjacent to objects, returning the result as a new mask image. bwboundaries traces the perimeter pixels, returning them as an ordered list.
Steve,
If I want to record the locations of the white pixels in bw3 (the ‘adjacent pixels’ image), I can do [r,c] = find(bw3==1) and get them. However, this method orders the pixels by ascending values of column locations. Is there a simple way to get the locations with having them ordered or sorted? For instance, if I want the pixels on the circumference of a circle listed in a clockwise or a counter-clockwise fashion, neither ‘find’ nor ‘bwboundaries’ would do the task.
Thanks,
Vijay
Vijay—Why isn’t bwboundaries suitable for your task?
Steve,
There was a typo in my previous message. It should have read “Is there a simple way to get the locations WITHOUT having them ordered or sorted”. Anyway, I checked the documentation on ‘bwboundaries’ and found that it indeed does what I want. Thank you for your quick response.
Sincerely,
Vijay