2

I should be able to input a pixel position and get all the same coloured(in my case it should be black) pixels which are connected to it. How to do this in opencv with c++. Simply the output pixels should be connected to each other with color black. FindContours() method does not work as it cannot be feeded with a pixel.

Samitha Chathuranga
  • 1,689
  • 5
  • 30
  • 57

2 Answers2

4

OpenCV has no such function, so you will have to implement it yourself. An easy way would be to implement a search algorithm like a BFS or DFS in trees.

som pseudo-code:

list<pixels> pixels_in_component;
stack<pixels> neighbours;
neighbours.add(starting_point)

while not neightbours.empty:
   p = neighbours.pop();
   pixels_in_component.append(p) 
   for each adjacent pixel n of p:
     if color(n) == color(starting_point):
         neighbours.append(n)

If you use a stack or a queue is not relevant and pixels_in_component will later contain all you connected pixels.

Or (if you are restricted to black components) you can use cv::Threshold to invert your image. Just use the inverted binary threshold where all pixels above a certain value are mapped to zero, while the pixels below the threshold are mapped to a given value.

If you have a CV_8UC1 image, you could just call threshold( input,output, 1,255, THRESH_BINARY_INV);

to map black pixels to 255 and the rest to zero. Then you can just run the normal findContours.

FooTheBar
  • 818
  • 1
  • 9
  • 20
3

You should simply use floodFill.

Here you can find a detailed explanation on how to obtain a binary image with all the pixels connected to your seed point.

Community
  • 1
  • 1
Antonio
  • 19,451
  • 13
  • 99
  • 197
  • Thanks. Via The simple floodfill method (1st variation) we can only change the color of connected components. That doesn't return which pixels are connected. So I still think this is not a direct answer but a workaround. I guess u suggest to use the floodFill method's second variation which include mask parameter. But does this mask too have information which pixels are connected? (or do I have to manually find which pixels are filled with a certain color) – Samitha Chathuranga Apr 09 '15 at 14:52
  • @SamithaChathuranga Check also this http://stackoverflow.com/q/28364678/2436175. How do you want your output? A vector of vector of points? A vector of binary images, where each binary image represents one label? – Antonio Apr 09 '15 at 15:21