This operation can be performed by first sorting all pixels by gray value and then incrementally adding pixels to each connected component as the threshold is changed.
The area is monitored.
Regions such that their variation wrt the threshold is minimal are defined maximally stable: