We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Question: Why is default structuring element of 1-connectivity used by ndimage.label for getting the default markers(labeled local minima) for watershed segmentation?
## Description

In the implemented watershed.py segmentation, one can pass a connectivity argument, when `local_minima` is called by watershed (when `markers=none`) it passes the same connectivity value onto the local minima function, this generates the `markers_bool`, which then is used by `ndimage.label()` to generate the labeled markers. `ndimage.label` can take a structure argument and it defaults to 1-connectivity structure if none are given. IMO it is more intuitive to have `ndimage.label` also use the same connectivity which is passed by the user to the watershed function instead of always using the default 1-connectivity.
Below is the line in the source I am referring to:
https://github.com/scikit-image/scikit-image/blob/663e9e4b0f2ba88249bfef45bc65700555a3f24b/skimage/segmentation/_watershed.py#L76

Instead of the above would it not be better to have?
```python
if connectivity==2:
   markers = ndi.label(markers_bool,
                       structure = [[1,1,1],
                                   [1,1,1],
                                   [1,1,1]])[0]
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `skimage/segmentation/_watershed.py`
Content:
```
1 """watershed.py - watershed algorithm
2 
3 This module implements a watershed algorithm that apportions pixels into
4 marked basins. The algorithm uses a priority queue to hold the pixels
5 with the metric for the priority queue being pixel value, then the time
6 of entry into the queue - this settles ties in favor of the closest marker.
7 
8 Some ideas taken from
9 Soille, "Automated Basin Delineation from Digital Elevation Models Using
10 Mathematical Morphology", Signal Processing 20 (1990) 171-182.
11 
12 The most important insight in the paper is that entry time onto the queue
13 solves two problems: a pixel should be assigned to the neighbor with the
14 largest gradient or, if there is no gradient, pixels on a plateau should
15 be split between markers on opposite sides.
16 
17 Originally part of CellProfiler, code licensed under both GPL and BSD licenses.
18 Website: http://www.cellprofiler.org
19 
20 Copyright (c) 2003-2009 Massachusetts Institute of Technology
21 Copyright (c) 2009-2011 Broad Institute
22 All rights reserved.
23 
24 Original author: Lee Kamentsky
25 """
26 
27 import numpy as np
28 from scipy import ndimage as ndi
29 
30 from . import _watershed_cy
31 from ..morphology.extrema import local_minima
32 from ..morphology._util import (_validate_connectivity,
33                                 _offsets_to_raveled_neighbors)
34 from ..util import crop, regular_seeds
35 
36 
37 def _validate_inputs(image, markers, mask, connectivity):
38     """Ensure that all inputs to watershed have matching shapes and types.
39 
40     Parameters
41     ----------
42     image : array
43         The input image.
44     markers : int or array of int
45         The marker image.
46     mask : array, or None
47         A boolean mask, True where we want to compute the watershed.
48     connectivity : int in {1, ..., image.ndim}
49         The connectivity of the neighborhood of a pixel.
50 
51     Returns
52     -------
53     image, markers, mask : arrays
54         The validated and formatted arrays. Image will have dtype float64,
55         markers int32, and mask int8. If ``None`` was given for the mask,
56         it is a volume of all 1s.
57 
58     Raises
59     ------
60     ValueError
61         If the shapes of the given arrays don't match.
62     """
63     n_pixels = image.size
64     if mask is None:
65         # Use a complete `True` mask if none is provided
66         mask = np.ones(image.shape, bool)
67     else:
68         mask = np.asanyarray(mask, dtype=bool)
69         n_pixels = np.sum(mask)
70         if mask.shape != image.shape:
71             message = ("`mask` (shape {}) must have same shape as "
72                        "`image` (shape {})".format(mask.shape, image.shape))
73             raise ValueError(message)
74     if markers is None:
75         markers_bool = local_minima(image, connectivity=connectivity) * mask
76         markers = ndi.label(markers_bool)[0]
77     elif not isinstance(markers, (np.ndarray, list, tuple)):
78         # not array-like, assume int
79         # given int, assume that number of markers *within mask*.
80         markers = regular_seeds(image.shape,
81                                 int(markers / (n_pixels / image.size)))
82         markers *= mask
83     else:
84         markers = np.asanyarray(markers) * mask
85         if markers.shape != image.shape:
86             message = ("`markers` (shape {}) must have same shape as "
87                        "`image` (shape {})".format(markers.shape, image.shape))
88             raise ValueError(message)
89     return (image.astype(np.float64),
90             markers.astype(np.int32),
91             mask.astype(np.int8))
92 
93 
94 def watershed(image, markers=None, connectivity=1, offset=None, mask=None,
95               compactness=0, watershed_line=False):
96     """Find watershed basins in `image` flooded from given `markers`.
97 
98     Parameters
99     ----------
100     image : ndarray (2-D, 3-D, ...) of integers
101         Data array where the lowest value points are labeled first.
102     markers : int, or ndarray of int, same shape as `image`, optional
103         The desired number of markers, or an array marking the basins with the
104         values to be assigned in the label matrix. Zero means not a marker. If
105         ``None`` (no markers given), the local minima of the image are used as
106         markers.
107     connectivity : ndarray, optional
108         An array with the same number of dimensions as `image` whose
109         non-zero elements indicate neighbors for connection.
110         Following the scipy convention, default is a one-connected array of
111         the dimension of the image.
112     offset : array_like of shape image.ndim, optional
113         offset of the connectivity (one offset per dimension)
114     mask : ndarray of bools or 0s and 1s, optional
115         Array of same shape as `image`. Only points at which mask == True
116         will be labeled.
117     compactness : float, optional
118         Use compact watershed [3]_ with given compactness parameter.
119         Higher values result in more regularly-shaped watershed basins.
120     watershed_line : bool, optional
121         If watershed_line is True, a one-pixel wide line separates the regions
122         obtained by the watershed algorithm. The line has the label 0.
123 
124     Returns
125     -------
126     out : ndarray
127         A labeled matrix of the same type and shape as markers
128 
129     See Also
130     --------
131     skimage.segmentation.random_walker : random walker segmentation
132         A segmentation algorithm based on anisotropic diffusion, usually
133         slower than the watershed but with good results on noisy data and
134         boundaries with holes.
135 
136     Notes
137     -----
138     This function implements a watershed algorithm [1]_ [2]_ that apportions
139     pixels into marked basins. The algorithm uses a priority queue to hold
140     the pixels with the metric for the priority queue being pixel value, then
141     the time of entry into the queue - this settles ties in favor of the
142     closest marker.
143 
144     Some ideas taken from
145     Soille, "Automated Basin Delineation from Digital Elevation Models Using
146     Mathematical Morphology", Signal Processing 20 (1990) 171-182
147 
148     The most important insight in the paper is that entry time onto the queue
149     solves two problems: a pixel should be assigned to the neighbor with the
150     largest gradient or, if there is no gradient, pixels on a plateau should
151     be split between markers on opposite sides.
152 
153     This implementation converts all arguments to specific, lowest common
154     denominator types, then passes these to a C algorithm.
155 
156     Markers can be determined manually, or automatically using for example
157     the local minima of the gradient of the image, or the local maxima of the
158     distance function to the background for separating overlapping objects
159     (see example).
160 
161     References
162     ----------
163     .. [1] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29
164 
165     .. [2] http://cmm.ensmp.fr/~beucher/wtshed.html
166 
167     .. [3] Peer Neubert & Peter Protzel (2014). Compact Watershed and
168            Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation
169            Algorithms. ICPR 2014, pp 996-1001. :DOI:`10.1109/ICPR.2014.181`
170            https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf
171 
172     Examples
173     --------
174     The watershed algorithm is useful to separate overlapping objects.
175 
176     We first generate an initial image with two overlapping circles:
177 
178     >>> x, y = np.indices((80, 80))
179     >>> x1, y1, x2, y2 = 28, 28, 44, 52
180     >>> r1, r2 = 16, 20
181     >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2
182     >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2
183     >>> image = np.logical_or(mask_circle1, mask_circle2)
184 
185     Next, we want to separate the two circles. We generate markers at the
186     maxima of the distance to the background:
187 
188     >>> from scipy import ndimage as ndi
189     >>> distance = ndi.distance_transform_edt(image)
190     >>> from skimage.feature import peak_local_max
191     >>> local_maxi = peak_local_max(distance, labels=image,
192     ...                             footprint=np.ones((3, 3)),
193     ...                             indices=False)
194     >>> markers = ndi.label(local_maxi)[0]
195 
196     Finally, we run the watershed on the image and markers:
197 
198     >>> labels = watershed(-distance, markers, mask=image)
199 
200     The algorithm works also for 3-D images, and can be used for example to
201     separate overlapping spheres.
202     """
203     image, markers, mask = _validate_inputs(image, markers, mask, connectivity)
204     connectivity, offset = _validate_connectivity(image.ndim, connectivity,
205                                                   offset)
206 
207     # pad the image, markers, and mask so that we can use the mask to
208     # keep from running off the edges
209     pad_width = [(p, p) for p in offset]
210     image = np.pad(image, pad_width, mode='constant')
211     mask = np.pad(mask, pad_width, mode='constant').ravel()
212     output = np.pad(markers, pad_width, mode='constant')
213 
214     flat_neighborhood = _offsets_to_raveled_neighbors(
215         image.shape, connectivity, center=offset)
216     marker_locations = np.flatnonzero(output)
217     image_strides = np.array(image.strides, dtype=np.intp) // image.itemsize
218 
219     _watershed_cy.watershed_raveled(image.ravel(),
220                                     marker_locations, flat_neighborhood,
221                                     mask, image_strides, compactness,
222                                     output.ravel(),
223                                     watershed_line)
224 
225     output = crop(output, pad_width, copy=True)
226 
227     return output
228
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/skimage/segmentation/_watershed.py b/skimage/segmentation/_watershed.py
--- a/skimage/segmentation/_watershed.py
+++ b/skimage/segmentation/_watershed.py
@@ -73,7 +73,8 @@
             raise ValueError(message)
     if markers is None:
         markers_bool = local_minima(image, connectivity=connectivity) * mask
-        markers = ndi.label(markers_bool)[0]
+        footprint = ndi.generate_binary_structure(markers_bool.ndim, connectivity)
+        markers = ndi.label(markers_bool, structure=footprint)[0]
     elif not isinstance(markers, (np.ndarray, list, tuple)):
         # not array-like, assume int
         # given int, assume that number of markers *within mask*.

{"golden_diff": "diff --git a/skimage/segmentation/_watershed.py b/skimage/segmentation/_watershed.py\n--- a/skimage/segmentation/_watershed.py\n+++ b/skimage/segmentation/_watershed.py\n@@ -73,7 +73,8 @@\n             raise ValueError(message)\n     if markers is None:\n         markers_bool = local_minima(image, connectivity=connectivity) * mask\n-        markers = ndi.label(markers_bool)[0]\n+        footprint = ndi.generate_binary_structure(markers_bool.ndim, connectivity)\n+        markers = ndi.label(markers_bool, structure=footprint)[0]\n     elif not isinstance(markers, (np.ndarray, list, tuple)):\n         # not array-like, assume int\n         # given int, assume that number of markers *within mask*.\n", "issue": "Question: Why is default structuring element of 1-connectivity used by ndimage.label for getting the default markers(labeled local minima) for watershed segmentation?\n## Description\r\n\r\nIn the implemented watershed.py segmentation, one can pass a connectivity argument, when `local_minima` is called by watershed (when `markers=none`) it passes the same connectivity value onto the local minima function, this generates the `markers_bool`, which then is used by `ndimage.label()` to generate the labeled markers. `ndimage.label` can take a structure argument and it defaults to 1-connectivity structure if none are given. IMO it is more intuitive to have `ndimage.label` also use the same connectivity which is passed by the user to the watershed function instead of always using the default 1-connectivity.\r\nBelow is the line in the source I am referring to:\r\nhttps://github.com/scikit-image/scikit-image/blob/663e9e4b0f2ba88249bfef45bc65700555a3f24b/skimage/segmentation/_watershed.py#L76\r\n\r\nInstead of the above would it not be better to have?\r\n```python\r\nif connectivity==2:\r\n   markers = ndi.label(markers_bool,\r\n                       structure = [[1,1,1],\r\n                                   [1,1,1],\r\n                                   [1,1,1]])[0]\r\n```\r\n\n", "before_files": [{"content": "\"\"\"watershed.py - watershed algorithm\n\nThis module implements a watershed algorithm that apportions pixels into\nmarked basins. The algorithm uses a priority queue to hold the pixels\nwith the metric for the priority queue being pixel value, then the time\nof entry into the queue - this settles ties in favor of the closest marker.\n\nSome ideas taken from\nSoille, \"Automated Basin Delineation from Digital Elevation Models Using\nMathematical Morphology\", Signal Processing 20 (1990) 171-182.\n\nThe most important insight in the paper is that entry time onto the queue\nsolves two problems: a pixel should be assigned to the neighbor with the\nlargest gradient or, if there is no gradient, pixels on a plateau should\nbe split between markers on opposite sides.\n\nOriginally part of CellProfiler, code licensed under both GPL and BSD licenses.\nWebsite: http://www.cellprofiler.org\n\nCopyright (c) 2003-2009 Massachusetts Institute of Technology\nCopyright (c) 2009-2011 Broad Institute\nAll rights reserved.\n\nOriginal author: Lee Kamentsky\n\"\"\"\n\nimport numpy as np\nfrom scipy import ndimage as ndi\n\nfrom . import _watershed_cy\nfrom ..morphology.extrema import local_minima\nfrom ..morphology._util import (_validate_connectivity,\n                                _offsets_to_raveled_neighbors)\nfrom ..util import crop, regular_seeds\n\n\ndef _validate_inputs(image, markers, mask, connectivity):\n    \"\"\"Ensure that all inputs to watershed have matching shapes and types.\n\n    Parameters\n    ----------\n    image : array\n        The input image.\n    markers : int or array of int\n        The marker image.\n    mask : array, or None\n        A boolean mask, True where we want to compute the watershed.\n    connectivity : int in {1, ..., image.ndim}\n        The connectivity of the neighborhood of a pixel.\n\n    Returns\n    -------\n    image, markers, mask : arrays\n        The validated and formatted arrays. Image will have dtype float64,\n        markers int32, and mask int8. If ``None`` was given for the mask,\n        it is a volume of all 1s.\n\n    Raises\n    ------\n    ValueError\n        If the shapes of the given arrays don't match.\n    \"\"\"\n    n_pixels = image.size\n    if mask is None:\n        # Use a complete `True` mask if none is provided\n        mask = np.ones(image.shape, bool)\n    else:\n        mask = np.asanyarray(mask, dtype=bool)\n        n_pixels = np.sum(mask)\n        if mask.shape != image.shape:\n            message = (\"`mask` (shape {}) must have same shape as \"\n                       \"`image` (shape {})\".format(mask.shape, image.shape))\n            raise ValueError(message)\n    if markers is None:\n        markers_bool = local_minima(image, connectivity=connectivity) * mask\n        markers = ndi.label(markers_bool)[0]\n    elif not isinstance(markers, (np.ndarray, list, tuple)):\n        # not array-like, assume int\n        # given int, assume that number of markers *within mask*.\n        markers = regular_seeds(image.shape,\n                                int(markers / (n_pixels / image.size)))\n        markers *= mask\n    else:\n        markers = np.asanyarray(markers) * mask\n        if markers.shape != image.shape:\n            message = (\"`markers` (shape {}) must have same shape as \"\n                       \"`image` (shape {})\".format(markers.shape, image.shape))\n            raise ValueError(message)\n    return (image.astype(np.float64),\n            markers.astype(np.int32),\n            mask.astype(np.int8))\n\n\ndef watershed(image, markers=None, connectivity=1, offset=None, mask=None,\n              compactness=0, watershed_line=False):\n    \"\"\"Find watershed basins in `image` flooded from given `markers`.\n\n    Parameters\n    ----------\n    image : ndarray (2-D, 3-D, ...) of integers\n        Data array where the lowest value points are labeled first.\n    markers : int, or ndarray of int, same shape as `image`, optional\n        The desired number of markers, or an array marking the basins with the\n        values to be assigned in the label matrix. Zero means not a marker. If\n        ``None`` (no markers given), the local minima of the image are used as\n        markers.\n    connectivity : ndarray, optional\n        An array with the same number of dimensions as `image` whose\n        non-zero elements indicate neighbors for connection.\n        Following the scipy convention, default is a one-connected array of\n        the dimension of the image.\n    offset : array_like of shape image.ndim, optional\n        offset of the connectivity (one offset per dimension)\n    mask : ndarray of bools or 0s and 1s, optional\n        Array of same shape as `image`. Only points at which mask == True\n        will be labeled.\n    compactness : float, optional\n        Use compact watershed [3]_ with given compactness parameter.\n        Higher values result in more regularly-shaped watershed basins.\n    watershed_line : bool, optional\n        If watershed_line is True, a one-pixel wide line separates the regions\n        obtained by the watershed algorithm. The line has the label 0.\n\n    Returns\n    -------\n    out : ndarray\n        A labeled matrix of the same type and shape as markers\n\n    See Also\n    --------\n    skimage.segmentation.random_walker : random walker segmentation\n        A segmentation algorithm based on anisotropic diffusion, usually\n        slower than the watershed but with good results on noisy data and\n        boundaries with holes.\n\n    Notes\n    -----\n    This function implements a watershed algorithm [1]_ [2]_ that apportions\n    pixels into marked basins. The algorithm uses a priority queue to hold\n    the pixels with the metric for the priority queue being pixel value, then\n    the time of entry into the queue - this settles ties in favor of the\n    closest marker.\n\n    Some ideas taken from\n    Soille, \"Automated Basin Delineation from Digital Elevation Models Using\n    Mathematical Morphology\", Signal Processing 20 (1990) 171-182\n\n    The most important insight in the paper is that entry time onto the queue\n    solves two problems: a pixel should be assigned to the neighbor with the\n    largest gradient or, if there is no gradient, pixels on a plateau should\n    be split between markers on opposite sides.\n\n    This implementation converts all arguments to specific, lowest common\n    denominator types, then passes these to a C algorithm.\n\n    Markers can be determined manually, or automatically using for example\n    the local minima of the gradient of the image, or the local maxima of the\n    distance function to the background for separating overlapping objects\n    (see example).\n\n    References\n    ----------\n    .. [1] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29\n\n    .. [2] http://cmm.ensmp.fr/~beucher/wtshed.html\n\n    .. [3] Peer Neubert & Peter Protzel (2014). Compact Watershed and\n           Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation\n           Algorithms. ICPR 2014, pp 996-1001. :DOI:`10.1109/ICPR.2014.181`\n           https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf\n\n    Examples\n    --------\n    The watershed algorithm is useful to separate overlapping objects.\n\n    We first generate an initial image with two overlapping circles:\n\n    >>> x, y = np.indices((80, 80))\n    >>> x1, y1, x2, y2 = 28, 28, 44, 52\n    >>> r1, r2 = 16, 20\n    >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2\n    >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2\n    >>> image = np.logical_or(mask_circle1, mask_circle2)\n\n    Next, we want to separate the two circles. We generate markers at the\n    maxima of the distance to the background:\n\n    >>> from scipy import ndimage as ndi\n    >>> distance = ndi.distance_transform_edt(image)\n    >>> from skimage.feature import peak_local_max\n    >>> local_maxi = peak_local_max(distance, labels=image,\n    ...                             footprint=np.ones((3, 3)),\n    ...                             indices=False)\n    >>> markers = ndi.label(local_maxi)[0]\n\n    Finally, we run the watershed on the image and markers:\n\n    >>> labels = watershed(-distance, markers, mask=image)\n\n    The algorithm works also for 3-D images, and can be used for example to\n    separate overlapping spheres.\n    \"\"\"\n    image, markers, mask = _validate_inputs(image, markers, mask, connectivity)\n    connectivity, offset = _validate_connectivity(image.ndim, connectivity,\n                                                  offset)\n\n    # pad the image, markers, and mask so that we can use the mask to\n    # keep from running off the edges\n    pad_width = [(p, p) for p in offset]\n    image = np.pad(image, pad_width, mode='constant')\n    mask = np.pad(mask, pad_width, mode='constant').ravel()\n    output = np.pad(markers, pad_width, mode='constant')\n\n    flat_neighborhood = _offsets_to_raveled_neighbors(\n        image.shape, connectivity, center=offset)\n    marker_locations = np.flatnonzero(output)\n    image_strides = np.array(image.strides, dtype=np.intp) // image.itemsize\n\n    _watershed_cy.watershed_raveled(image.ravel(),\n                                    marker_locations, flat_neighborhood,\n                                    mask, image_strides, compactness,\n                                    output.ravel(),\n                                    watershed_line)\n\n    output = crop(output, pad_width, copy=True)\n\n    return output\n", "path": "skimage/segmentation/_watershed.py"}], "after_files": [{"content": "\"\"\"watershed.py - watershed algorithm\n\nThis module implements a watershed algorithm that apportions pixels into\nmarked basins. The algorithm uses a priority queue to hold the pixels\nwith the metric for the priority queue being pixel value, then the time\nof entry into the queue - this settles ties in favor of the closest marker.\n\nSome ideas taken from\nSoille, \"Automated Basin Delineation from Digital Elevation Models Using\nMathematical Morphology\", Signal Processing 20 (1990) 171-182.\n\nThe most important insight in the paper is that entry time onto the queue\nsolves two problems: a pixel should be assigned to the neighbor with the\nlargest gradient or, if there is no gradient, pixels on a plateau should\nbe split between markers on opposite sides.\n\nOriginally part of CellProfiler, code licensed under both GPL and BSD licenses.\nWebsite: http://www.cellprofiler.org\n\nCopyright (c) 2003-2009 Massachusetts Institute of Technology\nCopyright (c) 2009-2011 Broad Institute\nAll rights reserved.\n\nOriginal author: Lee Kamentsky\n\"\"\"\n\nimport numpy as np\nfrom scipy import ndimage as ndi\n\nfrom . import _watershed_cy\nfrom ..morphology.extrema import local_minima\nfrom ..morphology._util import (_validate_connectivity,\n                                _offsets_to_raveled_neighbors)\nfrom ..util import crop, regular_seeds\n\n\ndef _validate_inputs(image, markers, mask, connectivity):\n    \"\"\"Ensure that all inputs to watershed have matching shapes and types.\n\n    Parameters\n    ----------\n    image : array\n        The input image.\n    markers : int or array of int\n        The marker image.\n    mask : array, or None\n        A boolean mask, True where we want to compute the watershed.\n    connectivity : int in {1, ..., image.ndim}\n        The connectivity of the neighborhood of a pixel.\n\n    Returns\n    -------\n    image, markers, mask : arrays\n        The validated and formatted arrays. Image will have dtype float64,\n        markers int32, and mask int8. If ``None`` was given for the mask,\n        it is a volume of all 1s.\n\n    Raises\n    ------\n    ValueError\n        If the shapes of the given arrays don't match.\n    \"\"\"\n    n_pixels = image.size\n    if mask is None:\n        # Use a complete `True` mask if none is provided\n        mask = np.ones(image.shape, bool)\n    else:\n        mask = np.asanyarray(mask, dtype=bool)\n        n_pixels = np.sum(mask)\n        if mask.shape != image.shape:\n            message = (\"`mask` (shape {}) must have same shape as \"\n                       \"`image` (shape {})\".format(mask.shape, image.shape))\n            raise ValueError(message)\n    if markers is None:\n        markers_bool = local_minima(image, connectivity=connectivity) * mask\n        footprint = ndi.generate_binary_structure(markers_bool.ndim, connectivity)\n        markers = ndi.label(markers_bool, structure=footprint)[0]\n    elif not isinstance(markers, (np.ndarray, list, tuple)):\n        # not array-like, assume int\n        # given int, assume that number of markers *within mask*.\n        markers = regular_seeds(image.shape,\n                                int(markers / (n_pixels / image.size)))\n        markers *= mask\n    else:\n        markers = np.asanyarray(markers) * mask\n        if markers.shape != image.shape:\n            message = (\"`markers` (shape {}) must have same shape as \"\n                       \"`image` (shape {})\".format(markers.shape, image.shape))\n            raise ValueError(message)\n    return (image.astype(np.float64),\n            markers.astype(np.int32),\n            mask.astype(np.int8))\n\n\ndef watershed(image, markers=None, connectivity=1, offset=None, mask=None,\n              compactness=0, watershed_line=False):\n    \"\"\"Find watershed basins in `image` flooded from given `markers`.\n\n    Parameters\n    ----------\n    image : ndarray (2-D, 3-D, ...) of integers\n        Data array where the lowest value points are labeled first.\n    markers : int, or ndarray of int, same shape as `image`, optional\n        The desired number of markers, or an array marking the basins with the\n        values to be assigned in the label matrix. Zero means not a marker. If\n        ``None`` (no markers given), the local minima of the image are used as\n        markers.\n    connectivity : ndarray, optional\n        An array with the same number of dimensions as `image` whose\n        non-zero elements indicate neighbors for connection.\n        Following the scipy convention, default is a one-connected array of\n        the dimension of the image.\n    offset : array_like of shape image.ndim, optional\n        offset of the connectivity (one offset per dimension)\n    mask : ndarray of bools or 0s and 1s, optional\n        Array of same shape as `image`. Only points at which mask == True\n        will be labeled.\n    compactness : float, optional\n        Use compact watershed [3]_ with given compactness parameter.\n        Higher values result in more regularly-shaped watershed basins.\n    watershed_line : bool, optional\n        If watershed_line is True, a one-pixel wide line separates the regions\n        obtained by the watershed algorithm. The line has the label 0.\n\n    Returns\n    -------\n    out : ndarray\n        A labeled matrix of the same type and shape as markers\n\n    See Also\n    --------\n    skimage.segmentation.random_walker : random walker segmentation\n        A segmentation algorithm based on anisotropic diffusion, usually\n        slower than the watershed but with good results on noisy data and\n        boundaries with holes.\n\n    Notes\n    -----\n    This function implements a watershed algorithm [1]_ [2]_ that apportions\n    pixels into marked basins. The algorithm uses a priority queue to hold\n    the pixels with the metric for the priority queue being pixel value, then\n    the time of entry into the queue - this settles ties in favor of the\n    closest marker.\n\n    Some ideas taken from\n    Soille, \"Automated Basin Delineation from Digital Elevation Models Using\n    Mathematical Morphology\", Signal Processing 20 (1990) 171-182\n\n    The most important insight in the paper is that entry time onto the queue\n    solves two problems: a pixel should be assigned to the neighbor with the\n    largest gradient or, if there is no gradient, pixels on a plateau should\n    be split between markers on opposite sides.\n\n    This implementation converts all arguments to specific, lowest common\n    denominator types, then passes these to a C algorithm.\n\n    Markers can be determined manually, or automatically using for example\n    the local minima of the gradient of the image, or the local maxima of the\n    distance function to the background for separating overlapping objects\n    (see example).\n\n    References\n    ----------\n    .. [1] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29\n\n    .. [2] http://cmm.ensmp.fr/~beucher/wtshed.html\n\n    .. [3] Peer Neubert & Peter Protzel (2014). Compact Watershed and\n           Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation\n           Algorithms. ICPR 2014, pp 996-1001. :DOI:`10.1109/ICPR.2014.181`\n           https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf\n\n    Examples\n    --------\n    The watershed algorithm is useful to separate overlapping objects.\n\n    We first generate an initial image with two overlapping circles:\n\n    >>> x, y = np.indices((80, 80))\n    >>> x1, y1, x2, y2 = 28, 28, 44, 52\n    >>> r1, r2 = 16, 20\n    >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2\n    >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2\n    >>> image = np.logical_or(mask_circle1, mask_circle2)\n\n    Next, we want to separate the two circles. We generate markers at the\n    maxima of the distance to the background:\n\n    >>> from scipy import ndimage as ndi\n    >>> distance = ndi.distance_transform_edt(image)\n    >>> from skimage.feature import peak_local_max\n    >>> local_maxi = peak_local_max(distance, labels=image,\n    ...                             footprint=np.ones((3, 3)),\n    ...                             indices=False)\n    >>> markers = ndi.label(local_maxi)[0]\n\n    Finally, we run the watershed on the image and markers:\n\n    >>> labels = watershed(-distance, markers, mask=image)\n\n    The algorithm works also for 3-D images, and can be used for example to\n    separate overlapping spheres.\n    \"\"\"\n    image, markers, mask = _validate_inputs(image, markers, mask, connectivity)\n    connectivity, offset = _validate_connectivity(image.ndim, connectivity,\n                                                  offset)\n\n    # pad the image, markers, and mask so that we can use the mask to\n    # keep from running off the edges\n    pad_width = [(p, p) for p in offset]\n    image = np.pad(image, pad_width, mode='constant')\n    mask = np.pad(mask, pad_width, mode='constant').ravel()\n    output = np.pad(markers, pad_width, mode='constant')\n\n    flat_neighborhood = _offsets_to_raveled_neighbors(\n        image.shape, connectivity, center=offset)\n    marker_locations = np.flatnonzero(output)\n    image_strides = np.array(image.strides, dtype=np.intp) // image.itemsize\n\n    _watershed_cy.watershed_raveled(image.ravel(),\n                                    marker_locations, flat_neighborhood,\n                                    mask, image_strides, compactness,\n                                    output.ravel(),\n                                    watershed_line)\n\n    output = crop(output, pad_width, copy=True)\n\n    return output\n", "path": "skimage/segmentation/_watershed.py"}]}