How do I remove/replace border pixels from my image?

8 views (last 30 days)
I am new to Matlab and will need some help. I have a segmented image in which I would want to remove background (or black) pixels (with value == 1) from the image borders. I have been able to obtain an image mask of the border pixels that I do not want. The interior_blackPixels are useful, but I want to get rid of the outer_blackPixels. The code so far is shown below:
img = [1 1 1 1 1 1 1 1
1 1 1 1 2 2 2 1
1 1 1 2 2 2 2 1
1 1 1 2 2 2 2 1
1 1 2 2 2 2 2 1
1 1 2 2 2 2 2 1
1 3 3 1 1 1 3 1
1 3 3 1 1 1 3 1
1 3 3 3 3 3 3 1
1 1 1 1 1 1 1 1];
% Get the black pixels image array
blackPixels = (img == 1);
% Obtain the other pixels by negating the black pixels
otherPixels = ~blackPixels
% Get the border black pixels (or mask)
outer_blackPixels = blackPixels & ~imclearborder(blackPixels)
interior_blackPixels = blackPixels & ~outer_blackPixels
Please note that I do not mind replacing the pixel values of the outer_blackPixels to ‘0’ as this will not affect my analysis. Hence, I would expect my final image to be something like this:
% set all the border pixels to zeros
new_borderValues = img(outer_blackPixels) == 0
img = [0 0 0 0 0 0 0 0
0 0 0 0 2 2 2 0
0 0 0 2 2 2 2 0
0 0 0 2 2 2 2 0
0 0 2 2 2 2 2 0
0 0 2 2 2 2 2 0
0 3 3 1 1 1 3 0
0 3 3 1 1 1 3 0
0 3 3 3 3 3 3 0
0 0 0 0 0 0 0 0];
The main challenge for me however is that I am not sure how to retrieve the final image wit the black pixel borders replaced (as shown above) using the mask (outer_blackPixels) that I have. Any help/suggestions would be appreciated. Thanks!

Accepted Answer

Massimo Zanetti
Massimo Zanetti on 19 Dec 2016
You basically don't need your interior_blackPixels. Indeed, your expected image is obtained by simply setting outer_blackPixels of img to 0. Try this:
img(outer_blackPixels)=0
Is this what you need?
  1 Comment
burges
burges on 20 Dec 2016
Oh that works perfectly. I also realized that adding the following lines should work as well.
% logical pixels of interest
A = otherPixels | interior_blackPixels
% new image
newimg = img .*A
In any case, yours is straightforward and simple. Many thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Images 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!