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.
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:
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:
Another option that will simply reverse the labels in
L
is as follows: