If, given a pixel, you want to determine the largest connected monochrome region of the image containing that pixel, then this is just a graph traversal in an undirected graph, and a simple depth-first search suffices. In particular, there is no need to merge several regions.
If, however, you have a clever way to delimit regions in an image and later want to merge some of them, then this looks to me like the perfect application for a union-find data structure.
An union-find data structure maintains an equivalence relation on a set. It supports two operations:
- find(x): returns a canonical representative of x's equivalence class;
- union(x, y): merge x's and y's equivalence classes.
In other words, the equivalence relation represented by the union-find is the smallest equivalence relation containing the pair (x, y) for all calls to union(x, y) since the beginning.
A union-find can be represented efficiently by associating a "last computed representative" to each non-isolated element in the set. A plain C array can do if the set is small, or a QHash if it is larger. union(x, y) makes x's representative be represented by y's representative (or the opposite), but lazily leaves all other representatives untouched. find(x) follows the chains of "last computed representatives" from x until it finds the current representative c, and takes the opportunity to compress the data structure by remapping all the visited elements to c, thus speeding up subsequent lookups.
You can probably find the details online.
Again, this is just a shot in the dark as you still haven't explained in details what you are trying to achieve.
Bookmarks