Fill 4-connected cells exclusively

7 views (last 30 days)
Dear all,
yesterday a asked a question about how to fill 4-connected cells. Several comments about the use of 'imfill' were given to me. I thank the contributors for them but the option chosen does not give exactly what I need. The example matrix that I gave was probably not a good one.
I show another example. If:
BW1 = logical([1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0
1 1 1 1 0 1 1 1
1 0 0 1 1 0 1 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0]);
with the command:
BW2 = imfill(BW1,4,'holes');
you get:
BW2 =
1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0
1 1 1 1 1 0 1 0
1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1
1 0 0 1 1 1 1 0
1 0 0 0 1 1 1 0
1 0 0 0 1 1 1 0
but I would like to fill only the cells with 0 which are 4-connected with 1s, that is, I would like to get the following matrix instead:
BW3 =
1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0
1 1 1 1 1 1 1 1
1 0 0 1 1 0 1 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0
Do you know if there is an easy way to get this?
Again, thank you in advance.

Accepted Answer

Steve Eddins
Steve Eddins on 31 Mar 2011
I assume you meant your sample matrices to be 8-by-8 instead of 1-by-64? If that's true, then it looks like you want to change a pixel from a 0 to a 1 only if all of its 4-connected neighbors are 1. The following code uses bwhitmiss to identify such pixels:
se1 = [0 1 0; 1 0 1; 0 1 0];
se2 = [0 0 0; 0 1 0; 0 0 0];
pixels_to_change = bwhitmiss(BW1, se1, se2);
Now just elementwise-or with the original matrix:
BW3 = BW1 | pixels_to_change

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!