Ask Your Question

Revision history [back]

How to get stats from image segmented with watershed?

It appears that connectedComponents does not separate components that are divided by a single pixel dividing line.

This is an issue when trying to obtain region stats from an image segmented with the watershed method (ultimately I want to use connectedComponentsWithStats). Since connectedComponents does not handle already labeled images, I binarize the image by setting the background and dividing lines as 0 and the labeled regions as 255. The resulting binary image (segmented_bin) has regions separated by a single-pixel-wide line.

CoinsSegmented

Running connectedComponents on this image returns only 2 regions: the background and an aggregate of the foreground regions.

Steps to reproduce

Here is a sample code to reproduce the issue

```python import cv2

[...] # Prepare markers as in https://docs.opencv.org/3.4/d3/db4/tutorial_py_watershed.html

segmented = cv2.watershed(img,markers)

segmented_bin = segmented.copy() segmented_bin[segmented < 2] = 0 # -1 is dividing regions, no 0s, 1 is background segmented_bin[segmented > 1] = 255 # all above 1 are distinct regions num_labels, label_image = cv2.connectedComponents(segmented_bin.astype('uint8'), 8, cv2.CV_16U, cv2.CCL_GRANA) ```

Executing this code returns num_labels = 2 instead of 27.

click to hide/show revision 2
None

updated 2019-05-16 09:50:01 -0600

berak gravatar image

How to get stats from image segmented with watershed?

It appears that connectedComponents does not separate components that are divided by a single pixel dividing line.

This is an issue when trying to obtain region stats from an image segmented with the watershed method (ultimately I want to use connectedComponentsWithStats). Since connectedComponents does not handle already labeled images, I binarize the image by setting the background and dividing lines as 0 and the labeled regions as 255. The resulting binary image (segmented_bin) has regions separated by a single-pixel-wide line.

CoinsSegmented

Running connectedComponents on this image returns only 2 regions: the background and an aggregate of the foreground regions.

Steps to reproduce

Here is a sample code to reproduce the issue

```python

import cv2

cv2 [...] # Prepare markers as in https://docs.opencv.org/3.4/d3/db4/tutorial_py_watershed.html

https://docs.opencv.org/3.4/d3/db4/tutorial_py_watershed.html segmented = cv2.watershed(img,markers)

cv2.watershed(img,markers) segmented_bin = segmented.copy() segmented_bin[segmented < 2] = 0 # -1 is dividing regions, no 0s, 1 is background segmented_bin[segmented > 1] = 255 # all above 1 are distinct regions num_labels, label_image = cv2.connectedComponents(segmented_bin.astype('uint8'), 8, cv2.CV_16U, cv2.CCL_GRANA) ```

Executing this code returns num_labels = 2 instead of 27.