0

I used SuperpixelSLIC from OpenCV to compute superpixels and get the labels of each one, now I need to compute the neighborhood for each label. For example, considering 8-connected case in the array below, the neighborhood for label 1 es {2, 5}, for label 2 is {1, 3, 4, 5}, for 3 is {2, 4} and for 4 is {2, 3}

111223333
112222334
122233344
555244444

How can I implement this efficiently using opencv?

1 Answers1

1

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,
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Yes, I did a similar thing. OpenCV give 2 Mat variables: Labels and Contours (for each label). I iterated over the contours (instead of labels to check only contours) and checked 8-connected neighborhood. I used an auxiliary Mat variable to check if the current pixel and neighbors were visited to avoid computacion too. Anyway, thanks for your suggestion – Pavel Angel Mendoza Villafane May 07 '18 at 14:10