Reputation: 21
I use the new opencv function connectedComponentsWithStats
(version 3.0).
How do I get all pixels in connected components?
The result
Upvotes: 2
Views: 4449
Reputation: 51837
The third argument of connectedComponentsWithStats
, stats
, provides you information that will allow you to draw bounding boxes around the labeled regions.
The second argument, labels
should contain an image with zeros (black pixels) for non labeled pixels and coloured pixels for the labeled groups of pixels, one colour per label. Bare in mind, the non-zero values will be unique, but quite small (e.g for 7 labels, starting at 0 (background), the label values will go up to 6).
Here's an example 9x9 binary image:
[
[255,255, 0, 0, 0, 0, 0,255,255],
[255, 0, 0,255,255,255, 0, 0,255],
[ 0, 0,255, 0, 0, 0,255, 0, 0],
[ 0,255, 0, 0,255, 0, 0,255, 0],
[ 0,255, 0,255,255,255, 0,255, 0],
[ 0,255, 0, 0,255, 0, 0,255, 0],
[ 0, 0,255, 0, 0, 0,255, 0, 0],
[255, 0, 0,255,255,255, 0, 0,255],
[255,255, 0, 0, 0, 0, 0,255,255]
]
the connected components labels are:
[
[1 1 0 0 0 0 0 3 3]
[1 0 0 2 2 2 0 0 3]
[0 0 2 0 0 0 2 0 0]
[0 2 0 0 4 0 0 2 0]
[0 2 0 4 4 4 0 2 0]
[0 2 0 0 4 0 0 2 0]
[0 0 2 0 0 0 2 0 0]
[5 0 0 2 2 2 0 0 6]
[5 5 0 0 0 0 0 6 6]
]
to visualise them via imshow
you might want to scale those values up.
(could be a look-up table of colours you choose or computed colours as long as they are different enough to visually make sense).
Here's an example of scaling the labels above by 42 (255 max value / 6 foreground labels):
[
[ 42 42 0 0 0 0 0 126 126]
[ 42 0 0 84 84 84 0 0 126]
[ 0 0 84 0 0 0 84 0 0]
[ 0 84 0 0 168 0 0 84 0]
[ 0 84 0 168 168 168 0 84 0]
[ 0 84 0 0 168 0 0 84 0]
[ 0 0 84 0 0 0 84 0 0]
[210 0 0 84 84 84 0 0 252]
[210 210 0 0 0 0 0 252 252]
]
Upvotes: 6