Sort Connected Components from Right to Left

206 views Asked by At

How can I sort connected components from right to left and bottom to top in MATLAB? For example, I have this in the resulting label matrix L:

L = [0 0 0 1 1 1 0 0 0 0 0 3 3 0 4 4 0 0 0; ...
     0 0 1 1 1 0 0 0 0 0 0 3 3 0 4 4 4 0 0; ...
     0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 5 5; ...
     0 0 0 0 0 0 2 2 2 2 0 0 0 0 0 0 0 5 5];

I want the connected components in an image to be read from right to left and get this in L instead:

L = [0 0 0 5 5 5 0 0 0 0 0 3 3 0 2 2 0 0 0; ...
     0 0 5 5 5 0 0 0 0 0 0 3 3 0 2 2 2 0 0; ...
     0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 1 1; ...
     0 0 0 0 0 0 4 4 4 4 0 0 0 0 0 0 0 1 1];

I have used the regionprops function in MATLAB but it seems to work from left to right.

2

There are 2 answers

1
gnovice On

Labeling (such as that done by bwlabel) appears to follow a linear ordering, meaning it goes down each column from left to right, labeling regions in the order it first finds them.

If you want to instead label each region from right to left, but still down each column, you can flip your matrix from left to right first, do the labeling, then flip the result back again. For example:

L = flip(bwlabel(flip(bw, 2), 4), 2);

If you want to label each region from right to left, but instead go up each column, you can use 180 degree rotations of your matrix instead of flipping it:

L = rot90(bwlabel(rot90(bw, 2), 4), 2);

Another option that will simply reverse the labels in L is as follows:

L(L > 0) = max(L(:))+1-L(L > 0);
0
Jose Marques Junior On

Have you tried rotate the binary image?

%bin_img is the binary image
bin_img = rot90(rot90(bin_img));

%use regionprops like you want
%after this, you can retunr the image to the original

bin_img = rot90(rot90(bin_img));