I don't know if OpenCV has a specific function for this.
If you want to build it yourself, you can use a data structure like this:
std::unordered_map<int,std::set<int>> neighbors;
This is a hash map that associates a label (I use int
, replace with whatever type you use in your labeled image) to a set of labels (the neighbors).
You would then iterate through each pixel, and examine its 8-connected neighborhood:
int label = image[ii,jj];
int other = image[ii+1,jj]; // this inside a loop over the neighborhood
if (label != other) {
neighbors[label].insert(other);
}
The insert
operation will have no effect if other
was already in the set, so there is no need to explicitly check for that.
At the end of this process, neighbors
will contain an entry for each label in the image, and iterating over this entry will give a sorted list of neighbors:
label = 2;
std::cout << "Neighbors for label " << label << " are: ";
for(auto n : neighbors[label]) {
std::cout << n << ", ";
}
std::cout << '\n';
In your example should output:
Neighbors for label 2 are: 1, 3, 4, 5,