Is there a way to sort the masks returned by OpenCV's ConnectedComponentsWithStats method in a left-to-right, top-to-bottom way?

I am using the ConnectedComponentsWithStats() method and using the masks to parse a grid-like structure. The components returned by the method are well defined and separate but not sorted in the order of appearance (left-to-right, top-to-bottom).

This method returns the centroid values of the components as well as the left-most x coordinate, top-most y coordinate, height, and width.

I am looking for a way to sort these components’ masks.

related: