We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Make level parameter optional in measure.find_contours
## Description


I think that we could put a default value to level in find_contours. I would suggest (image.max() - image.min())/2. This would make this function able to be used with an image and I think this default value is meaningful.

I'm open to discussion.

--- 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/measure/_find_contours.py`
Content:
```
1 import numpy as np
2 from skimage._shared.utils import deprecate_kwarg
3 
4 from ._find_contours_cy import _get_contour_segments
5 
6 from collections import deque
7 
8 _param_options = ('high', 'low')
9 
10 
11 @deprecate_kwarg({'array': 'image'}, removed_version="0.20")
12 def find_contours(image, level,
13                   fully_connected='low', positive_orientation='low',
14                   *,
15                   mask=None):
16     """Find iso-valued contours in a 2D array for a given level value.
17 
18     Uses the "marching squares" method to compute a the iso-valued contours of
19     the input 2D array for a particular level value. Array values are linearly
20     interpolated to provide better precision for the output contours.
21 
22     Parameters
23     ----------
24     image : 2D ndarray of double
25         Input image in which to find contours.
26     level : float
27         Value along which to find contours in the array.
28     fully_connected : str, {'low', 'high'}
29          Indicates whether array elements below the given level value are to be
30          considered fully-connected (and hence elements above the value will
31          only be face connected), or vice-versa. (See notes below for details.)
32     positive_orientation : str, {'low', 'high'}
33          Indicates whether the output contours will produce positively-oriented
34          polygons around islands of low- or high-valued elements. If 'low' then
35          contours will wind counter- clockwise around elements below the
36          iso-value. Alternately, this means that low-valued elements are always
37          on the left of the contour. (See below for details.)
38     mask : 2D ndarray of bool, or None
39         A boolean mask, True where we want to draw contours.
40         Note that NaN values are always excluded from the considered region
41         (``mask`` is set to ``False`` wherever ``array`` is ``NaN``).
42 
43     Returns
44     -------
45     contours : list of (n,2)-ndarrays
46         Each contour is an ndarray of shape ``(n, 2)``,
47         consisting of n ``(row, column)`` coordinates along the contour.
48 
49     See Also
50     --------
51     skimage.measure.marching_cubes
52 
53     Notes
54     -----
55     The marching squares algorithm is a special case of the marching cubes
56     algorithm [1]_.  A simple explanation is available here:
57 
58     http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html
59 
60     There is a single ambiguous case in the marching squares algorithm: when
61     a given ``2 x 2``-element square has two high-valued and two low-valued
62     elements, each pair diagonally adjacent. (Where high- and low-valued is
63     with respect to the contour value sought.) In this case, either the
64     high-valued elements can be 'connected together' via a thin isthmus that
65     separates the low-valued elements, or vice-versa. When elements are
66     connected together across a diagonal, they are considered 'fully
67     connected' (also known as 'face+vertex-connected' or '8-connected'). Only
68     high-valued or low-valued elements can be fully-connected, the other set
69     will be considered as 'face-connected' or '4-connected'. By default,
70     low-valued elements are considered fully-connected; this can be altered
71     with the 'fully_connected' parameter.
72 
73     Output contours are not guaranteed to be closed: contours which intersect
74     the array edge or a masked-off region (either where mask is False or where
75     array is NaN) will be left open. All other contours will be closed. (The
76     closed-ness of a contours can be tested by checking whether the beginning
77     point is the same as the end point.)
78 
79     Contours are oriented. By default, array values lower than the contour
80     value are to the left of the contour and values greater than the contour
81     value are to the right. This means that contours will wind
82     counter-clockwise (i.e. in 'positive orientation') around islands of
83     low-valued pixels. This behavior can be altered with the
84     'positive_orientation' parameter.
85 
86     The order of the contours in the output list is determined by the position
87     of the smallest ``x,y`` (in lexicographical order) coordinate in the
88     contour.  This is a side-effect of how the input array is traversed, but
89     can be relied upon.
90 
91     .. warning::
92 
93        Array coordinates/values are assumed to refer to the *center* of the
94        array element. Take a simple example input: ``[0, 1]``. The interpolated
95        position of 0.5 in this array is midway between the 0-element (at
96        ``x=0``) and the 1-element (at ``x=1``), and thus would fall at
97        ``x=0.5``.
98 
99     This means that to find reasonable contours, it is best to find contours
100     midway between the expected "light" and "dark" values. In particular,
101     given a binarized array, *do not* choose to find contours at the low or
102     high value of the array. This will often yield degenerate contours,
103     especially around structures that are a single array element wide. Instead
104     choose a middle value, as above.
105 
106     References
107     ----------
108     .. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High
109            Resolution 3D Surface Construction Algorithm. Computer Graphics
110            (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170).
111            :DOI:`10.1145/37401.37422`
112 
113     Examples
114     --------
115     >>> a = np.zeros((3, 3))
116     >>> a[0, 0] = 1
117     >>> a
118     array([[1., 0., 0.],
119            [0., 0., 0.],
120            [0., 0., 0.]])
121     >>> find_contours(a, 0.5)
122     [array([[0. , 0.5],
123            [0.5, 0. ]])]
124     """
125     if fully_connected not in _param_options:
126         raise ValueError('Parameters "fully_connected" must be either '
127                          '"high" or "low".')
128     if positive_orientation not in _param_options:
129         raise ValueError('Parameters "positive_orientation" must be either '
130                          '"high" or "low".')
131     if image.shape[0] < 2 or image.shape[1] < 2:
132         raise ValueError("Input array must be at least 2x2.")
133     if image.ndim != 2:
134         raise ValueError('Only 2D arrays are supported.')
135     if mask is not None:
136         if mask.shape != image.shape:
137             raise ValueError('Parameters "array" and "mask"'
138                              ' must have same shape.')
139         if not np.can_cast(mask.dtype, bool, casting='safe'):
140             raise TypeError('Parameter "mask" must be a binary array.')
141         mask = mask.astype(np.uint8, copy=False)
142 
143     segments = _get_contour_segments(image.astype(np.double), float(level),
144                                      fully_connected == 'high', mask=mask)
145     contours = _assemble_contours(segments)
146     if positive_orientation == 'high':
147         contours = [c[::-1] for c in contours]
148     return contours
149 
150 
151 def _assemble_contours(segments):
152     current_index = 0
153     contours = {}
154     starts = {}
155     ends = {}
156     for from_point, to_point in segments:
157         # Ignore degenerate segments.
158         # This happens when (and only when) one vertex of the square is
159         # exactly the contour level, and the rest are above or below.
160         # This degenerate vertex will be picked up later by neighboring
161         # squares.
162         if from_point == to_point:
163             continue
164 
165         tail, tail_num = starts.pop(to_point, (None, None))
166         head, head_num = ends.pop(from_point, (None, None))
167 
168         if tail is not None and head is not None:
169             # We need to connect these two contours.
170             if tail is head:
171                 # We need to closed a contour.
172                 # Add the end point
173                 head.append(to_point)
174             else:  # tail is not head
175                 # We need to join two distinct contours.
176                 # We want to keep the first contour segment created, so that
177                 # the final contours are ordered left->right, top->bottom.
178                 if tail_num > head_num:
179                     # tail was created second. Append tail to head.
180                     head.extend(tail)
181                     # remove all traces of tail:
182                     ends.pop(tail[-1])
183                     contours.pop(tail_num, None)
184                     # Update contour starts end ends
185                     starts[head[0]] = (head, head_num)
186                     ends[head[-1]] = (head, head_num)
187                 else:  # tail_num <= head_num
188                     # head was created second. Prepend head to tail.
189                     tail.extendleft(reversed(head))
190                     # remove all traces of head:
191                     starts.pop(head[0])
192                     contours.pop(head_num, None)
193                     # Update contour starts end ends
194                     starts[tail[0]] = (tail, tail_num)
195                     ends[tail[-1]] = (tail, tail_num)
196         elif tail is None and head is None:
197             # we need to add a new contour
198             new_contour = deque((from_point, to_point))
199             contours[current_index] = new_contour
200             starts[from_point] = (new_contour, current_index)
201             ends[to_point] = (new_contour, current_index)
202             current_index += 1
203         elif head is None:  # tail is not None
204             # We've found a single contour to which the new segment should be
205             # prepended.
206             tail.appendleft(from_point)
207             starts[from_point] = (tail, tail_num)
208         else:  # tail is None and head is not None:
209             # We've found a single contour to which the new segment should be
210             # appended
211             head.append(to_point)
212             ends[to_point] = (head, head_num)
213 
214     return [np.array(contour) for _, contour in sorted(contours.items())]
215
```
--- 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/measure/_find_contours.py b/skimage/measure/_find_contours.py
--- a/skimage/measure/_find_contours.py
+++ b/skimage/measure/_find_contours.py
@@ -9,7 +9,7 @@
 
 
 @deprecate_kwarg({'array': 'image'}, removed_version="0.20")
-def find_contours(image, level,
+def find_contours(image, level=None,
                   fully_connected='low', positive_orientation='low',
                   *,
                   mask=None):
@@ -23,8 +23,9 @@
     ----------
     image : 2D ndarray of double
         Input image in which to find contours.
-    level : float
-        Value along which to find contours in the array.
+    level : float, optional
+        Value along which to find contours in the array. By default, the level
+        is set to (max(image) - min(image)) / 2
     fully_connected : str, {'low', 'high'}
          Indicates whether array elements below the given level value are to be
          considered fully-connected (and hence elements above the value will
@@ -139,6 +140,8 @@
         if not np.can_cast(mask.dtype, bool, casting='safe'):
             raise TypeError('Parameter "mask" must be a binary array.')
         mask = mask.astype(np.uint8, copy=False)
+    if level is None:
+        level = (np.nanmax(image) - np.nanmin(image)) / 2.0
 
     segments = _get_contour_segments(image.astype(np.double), float(level),
                                      fully_connected == 'high', mask=mask)

{"golden_diff": "diff --git a/skimage/measure/_find_contours.py b/skimage/measure/_find_contours.py\n--- a/skimage/measure/_find_contours.py\n+++ b/skimage/measure/_find_contours.py\n@@ -9,7 +9,7 @@\n \n \n @deprecate_kwarg({'array': 'image'}, removed_version=\"0.20\")\n-def find_contours(image, level,\n+def find_contours(image, level=None,\n                   fully_connected='low', positive_orientation='low',\n                   *,\n                   mask=None):\n@@ -23,8 +23,9 @@\n     ----------\n     image : 2D ndarray of double\n         Input image in which to find contours.\n-    level : float\n-        Value along which to find contours in the array.\n+    level : float, optional\n+        Value along which to find contours in the array. By default, the level\n+        is set to (max(image) - min(image)) / 2\n     fully_connected : str, {'low', 'high'}\n          Indicates whether array elements below the given level value are to be\n          considered fully-connected (and hence elements above the value will\n@@ -139,6 +140,8 @@\n         if not np.can_cast(mask.dtype, bool, casting='safe'):\n             raise TypeError('Parameter \"mask\" must be a binary array.')\n         mask = mask.astype(np.uint8, copy=False)\n+    if level is None:\n+        level = (np.nanmax(image) - np.nanmin(image)) / 2.0\n \n     segments = _get_contour_segments(image.astype(np.double), float(level),\n                                      fully_connected == 'high', mask=mask)\n", "issue": "Make level parameter optional in measure.find_contours\n## Description\r\n\r\n\r\nI think that we could put a default value to level in find_contours. I would suggest (image.max() - image.min())/2. This would make this function able to be used with an image and I think this default value is meaningful.\r\n\r\nI'm open to discussion.\n", "before_files": [{"content": "import numpy as np\nfrom skimage._shared.utils import deprecate_kwarg\n\nfrom ._find_contours_cy import _get_contour_segments\n\nfrom collections import deque\n\n_param_options = ('high', 'low')\n\n\n@deprecate_kwarg({'array': 'image'}, removed_version=\"0.20\")\ndef find_contours(image, level,\n                  fully_connected='low', positive_orientation='low',\n                  *,\n                  mask=None):\n    \"\"\"Find iso-valued contours in a 2D array for a given level value.\n\n    Uses the \"marching squares\" method to compute a the iso-valued contours of\n    the input 2D array for a particular level value. Array values are linearly\n    interpolated to provide better precision for the output contours.\n\n    Parameters\n    ----------\n    image : 2D ndarray of double\n        Input image in which to find contours.\n    level : float\n        Value along which to find contours in the array.\n    fully_connected : str, {'low', 'high'}\n         Indicates whether array elements below the given level value are to be\n         considered fully-connected (and hence elements above the value will\n         only be face connected), or vice-versa. (See notes below for details.)\n    positive_orientation : str, {'low', 'high'}\n         Indicates whether the output contours will produce positively-oriented\n         polygons around islands of low- or high-valued elements. If 'low' then\n         contours will wind counter- clockwise around elements below the\n         iso-value. Alternately, this means that low-valued elements are always\n         on the left of the contour. (See below for details.)\n    mask : 2D ndarray of bool, or None\n        A boolean mask, True where we want to draw contours.\n        Note that NaN values are always excluded from the considered region\n        (``mask`` is set to ``False`` wherever ``array`` is ``NaN``).\n\n    Returns\n    -------\n    contours : list of (n,2)-ndarrays\n        Each contour is an ndarray of shape ``(n, 2)``,\n        consisting of n ``(row, column)`` coordinates along the contour.\n\n    See Also\n    --------\n    skimage.measure.marching_cubes\n\n    Notes\n    -----\n    The marching squares algorithm is a special case of the marching cubes\n    algorithm [1]_.  A simple explanation is available here:\n\n    http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html\n\n    There is a single ambiguous case in the marching squares algorithm: when\n    a given ``2 x 2``-element square has two high-valued and two low-valued\n    elements, each pair diagonally adjacent. (Where high- and low-valued is\n    with respect to the contour value sought.) In this case, either the\n    high-valued elements can be 'connected together' via a thin isthmus that\n    separates the low-valued elements, or vice-versa. When elements are\n    connected together across a diagonal, they are considered 'fully\n    connected' (also known as 'face+vertex-connected' or '8-connected'). Only\n    high-valued or low-valued elements can be fully-connected, the other set\n    will be considered as 'face-connected' or '4-connected'. By default,\n    low-valued elements are considered fully-connected; this can be altered\n    with the 'fully_connected' parameter.\n\n    Output contours are not guaranteed to be closed: contours which intersect\n    the array edge or a masked-off region (either where mask is False or where\n    array is NaN) will be left open. All other contours will be closed. (The\n    closed-ness of a contours can be tested by checking whether the beginning\n    point is the same as the end point.)\n\n    Contours are oriented. By default, array values lower than the contour\n    value are to the left of the contour and values greater than the contour\n    value are to the right. This means that contours will wind\n    counter-clockwise (i.e. in 'positive orientation') around islands of\n    low-valued pixels. This behavior can be altered with the\n    'positive_orientation' parameter.\n\n    The order of the contours in the output list is determined by the position\n    of the smallest ``x,y`` (in lexicographical order) coordinate in the\n    contour.  This is a side-effect of how the input array is traversed, but\n    can be relied upon.\n\n    .. warning::\n\n       Array coordinates/values are assumed to refer to the *center* of the\n       array element. Take a simple example input: ``[0, 1]``. The interpolated\n       position of 0.5 in this array is midway between the 0-element (at\n       ``x=0``) and the 1-element (at ``x=1``), and thus would fall at\n       ``x=0.5``.\n\n    This means that to find reasonable contours, it is best to find contours\n    midway between the expected \"light\" and \"dark\" values. In particular,\n    given a binarized array, *do not* choose to find contours at the low or\n    high value of the array. This will often yield degenerate contours,\n    especially around structures that are a single array element wide. Instead\n    choose a middle value, as above.\n\n    References\n    ----------\n    .. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High\n           Resolution 3D Surface Construction Algorithm. Computer Graphics\n           (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170).\n           :DOI:`10.1145/37401.37422`\n\n    Examples\n    --------\n    >>> a = np.zeros((3, 3))\n    >>> a[0, 0] = 1\n    >>> a\n    array([[1., 0., 0.],\n           [0., 0., 0.],\n           [0., 0., 0.]])\n    >>> find_contours(a, 0.5)\n    [array([[0. , 0.5],\n           [0.5, 0. ]])]\n    \"\"\"\n    if fully_connected not in _param_options:\n        raise ValueError('Parameters \"fully_connected\" must be either '\n                         '\"high\" or \"low\".')\n    if positive_orientation not in _param_options:\n        raise ValueError('Parameters \"positive_orientation\" must be either '\n                         '\"high\" or \"low\".')\n    if image.shape[0] < 2 or image.shape[1] < 2:\n        raise ValueError(\"Input array must be at least 2x2.\")\n    if image.ndim != 2:\n        raise ValueError('Only 2D arrays are supported.')\n    if mask is not None:\n        if mask.shape != image.shape:\n            raise ValueError('Parameters \"array\" and \"mask\"'\n                             ' must have same shape.')\n        if not np.can_cast(mask.dtype, bool, casting='safe'):\n            raise TypeError('Parameter \"mask\" must be a binary array.')\n        mask = mask.astype(np.uint8, copy=False)\n\n    segments = _get_contour_segments(image.astype(np.double), float(level),\n                                     fully_connected == 'high', mask=mask)\n    contours = _assemble_contours(segments)\n    if positive_orientation == 'high':\n        contours = [c[::-1] for c in contours]\n    return contours\n\n\ndef _assemble_contours(segments):\n    current_index = 0\n    contours = {}\n    starts = {}\n    ends = {}\n    for from_point, to_point in segments:\n        # Ignore degenerate segments.\n        # This happens when (and only when) one vertex of the square is\n        # exactly the contour level, and the rest are above or below.\n        # This degenerate vertex will be picked up later by neighboring\n        # squares.\n        if from_point == to_point:\n            continue\n\n        tail, tail_num = starts.pop(to_point, (None, None))\n        head, head_num = ends.pop(from_point, (None, None))\n\n        if tail is not None and head is not None:\n            # We need to connect these two contours.\n            if tail is head:\n                # We need to closed a contour.\n                # Add the end point\n                head.append(to_point)\n            else:  # tail is not head\n                # We need to join two distinct contours.\n                # We want to keep the first contour segment created, so that\n                # the final contours are ordered left->right, top->bottom.\n                if tail_num > head_num:\n                    # tail was created second. Append tail to head.\n                    head.extend(tail)\n                    # remove all traces of tail:\n                    ends.pop(tail[-1])\n                    contours.pop(tail_num, None)\n                    # Update contour starts end ends\n                    starts[head[0]] = (head, head_num)\n                    ends[head[-1]] = (head, head_num)\n                else:  # tail_num <= head_num\n                    # head was created second. Prepend head to tail.\n                    tail.extendleft(reversed(head))\n                    # remove all traces of head:\n                    starts.pop(head[0])\n                    contours.pop(head_num, None)\n                    # Update contour starts end ends\n                    starts[tail[0]] = (tail, tail_num)\n                    ends[tail[-1]] = (tail, tail_num)\n        elif tail is None and head is None:\n            # we need to add a new contour\n            new_contour = deque((from_point, to_point))\n            contours[current_index] = new_contour\n            starts[from_point] = (new_contour, current_index)\n            ends[to_point] = (new_contour, current_index)\n            current_index += 1\n        elif head is None:  # tail is not None\n            # We've found a single contour to which the new segment should be\n            # prepended.\n            tail.appendleft(from_point)\n            starts[from_point] = (tail, tail_num)\n        else:  # tail is None and head is not None:\n            # We've found a single contour to which the new segment should be\n            # appended\n            head.append(to_point)\n            ends[to_point] = (head, head_num)\n\n    return [np.array(contour) for _, contour in sorted(contours.items())]\n", "path": "skimage/measure/_find_contours.py"}], "after_files": [{"content": "import numpy as np\nfrom skimage._shared.utils import deprecate_kwarg\n\nfrom ._find_contours_cy import _get_contour_segments\n\nfrom collections import deque\n\n_param_options = ('high', 'low')\n\n\n@deprecate_kwarg({'array': 'image'}, removed_version=\"0.20\")\ndef find_contours(image, level=None,\n                  fully_connected='low', positive_orientation='low',\n                  *,\n                  mask=None):\n    \"\"\"Find iso-valued contours in a 2D array for a given level value.\n\n    Uses the \"marching squares\" method to compute a the iso-valued contours of\n    the input 2D array for a particular level value. Array values are linearly\n    interpolated to provide better precision for the output contours.\n\n    Parameters\n    ----------\n    image : 2D ndarray of double\n        Input image in which to find contours.\n    level : float, optional\n        Value along which to find contours in the array. By default, the level\n        is set to (max(image) - min(image)) / 2\n    fully_connected : str, {'low', 'high'}\n         Indicates whether array elements below the given level value are to be\n         considered fully-connected (and hence elements above the value will\n         only be face connected), or vice-versa. (See notes below for details.)\n    positive_orientation : str, {'low', 'high'}\n         Indicates whether the output contours will produce positively-oriented\n         polygons around islands of low- or high-valued elements. If 'low' then\n         contours will wind counter- clockwise around elements below the\n         iso-value. Alternately, this means that low-valued elements are always\n         on the left of the contour. (See below for details.)\n    mask : 2D ndarray of bool, or None\n        A boolean mask, True where we want to draw contours.\n        Note that NaN values are always excluded from the considered region\n        (``mask`` is set to ``False`` wherever ``array`` is ``NaN``).\n\n    Returns\n    -------\n    contours : list of (n,2)-ndarrays\n        Each contour is an ndarray of shape ``(n, 2)``,\n        consisting of n ``(row, column)`` coordinates along the contour.\n\n    See Also\n    --------\n    skimage.measure.marching_cubes\n\n    Notes\n    -----\n    The marching squares algorithm is a special case of the marching cubes\n    algorithm [1]_.  A simple explanation is available here:\n\n    http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html\n\n    There is a single ambiguous case in the marching squares algorithm: when\n    a given ``2 x 2``-element square has two high-valued and two low-valued\n    elements, each pair diagonally adjacent. (Where high- and low-valued is\n    with respect to the contour value sought.) In this case, either the\n    high-valued elements can be 'connected together' via a thin isthmus that\n    separates the low-valued elements, or vice-versa. When elements are\n    connected together across a diagonal, they are considered 'fully\n    connected' (also known as 'face+vertex-connected' or '8-connected'). Only\n    high-valued or low-valued elements can be fully-connected, the other set\n    will be considered as 'face-connected' or '4-connected'. By default,\n    low-valued elements are considered fully-connected; this can be altered\n    with the 'fully_connected' parameter.\n\n    Output contours are not guaranteed to be closed: contours which intersect\n    the array edge or a masked-off region (either where mask is False or where\n    array is NaN) will be left open. All other contours will be closed. (The\n    closed-ness of a contours can be tested by checking whether the beginning\n    point is the same as the end point.)\n\n    Contours are oriented. By default, array values lower than the contour\n    value are to the left of the contour and values greater than the contour\n    value are to the right. This means that contours will wind\n    counter-clockwise (i.e. in 'positive orientation') around islands of\n    low-valued pixels. This behavior can be altered with the\n    'positive_orientation' parameter.\n\n    The order of the contours in the output list is determined by the position\n    of the smallest ``x,y`` (in lexicographical order) coordinate in the\n    contour.  This is a side-effect of how the input array is traversed, but\n    can be relied upon.\n\n    .. warning::\n\n       Array coordinates/values are assumed to refer to the *center* of the\n       array element. Take a simple example input: ``[0, 1]``. The interpolated\n       position of 0.5 in this array is midway between the 0-element (at\n       ``x=0``) and the 1-element (at ``x=1``), and thus would fall at\n       ``x=0.5``.\n\n    This means that to find reasonable contours, it is best to find contours\n    midway between the expected \"light\" and \"dark\" values. In particular,\n    given a binarized array, *do not* choose to find contours at the low or\n    high value of the array. This will often yield degenerate contours,\n    especially around structures that are a single array element wide. Instead\n    choose a middle value, as above.\n\n    References\n    ----------\n    .. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High\n           Resolution 3D Surface Construction Algorithm. Computer Graphics\n           (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170).\n           :DOI:`10.1145/37401.37422`\n\n    Examples\n    --------\n    >>> a = np.zeros((3, 3))\n    >>> a[0, 0] = 1\n    >>> a\n    array([[1., 0., 0.],\n           [0., 0., 0.],\n           [0., 0., 0.]])\n    >>> find_contours(a, 0.5)\n    [array([[0. , 0.5],\n           [0.5, 0. ]])]\n    \"\"\"\n    if fully_connected not in _param_options:\n        raise ValueError('Parameters \"fully_connected\" must be either '\n                         '\"high\" or \"low\".')\n    if positive_orientation not in _param_options:\n        raise ValueError('Parameters \"positive_orientation\" must be either '\n                         '\"high\" or \"low\".')\n    if image.shape[0] < 2 or image.shape[1] < 2:\n        raise ValueError(\"Input array must be at least 2x2.\")\n    if image.ndim != 2:\n        raise ValueError('Only 2D arrays are supported.')\n    if mask is not None:\n        if mask.shape != image.shape:\n            raise ValueError('Parameters \"array\" and \"mask\"'\n                             ' must have same shape.')\n        if not np.can_cast(mask.dtype, bool, casting='safe'):\n            raise TypeError('Parameter \"mask\" must be a binary array.')\n        mask = mask.astype(np.uint8, copy=False)\n    if level is None:\n        level = (np.nanmax(image) - np.nanmin(image)) / 2.0\n\n    segments = _get_contour_segments(image.astype(np.double), float(level),\n                                     fully_connected == 'high', mask=mask)\n    contours = _assemble_contours(segments)\n    if positive_orientation == 'high':\n        contours = [c[::-1] for c in contours]\n    return contours\n\n\ndef _assemble_contours(segments):\n    current_index = 0\n    contours = {}\n    starts = {}\n    ends = {}\n    for from_point, to_point in segments:\n        # Ignore degenerate segments.\n        # This happens when (and only when) one vertex of the square is\n        # exactly the contour level, and the rest are above or below.\n        # This degenerate vertex will be picked up later by neighboring\n        # squares.\n        if from_point == to_point:\n            continue\n\n        tail, tail_num = starts.pop(to_point, (None, None))\n        head, head_num = ends.pop(from_point, (None, None))\n\n        if tail is not None and head is not None:\n            # We need to connect these two contours.\n            if tail is head:\n                # We need to closed a contour.\n                # Add the end point\n                head.append(to_point)\n            else:  # tail is not head\n                # We need to join two distinct contours.\n                # We want to keep the first contour segment created, so that\n                # the final contours are ordered left->right, top->bottom.\n                if tail_num > head_num:\n                    # tail was created second. Append tail to head.\n                    head.extend(tail)\n                    # remove all traces of tail:\n                    ends.pop(tail[-1])\n                    contours.pop(tail_num, None)\n                    # Update contour starts end ends\n                    starts[head[0]] = (head, head_num)\n                    ends[head[-1]] = (head, head_num)\n                else:  # tail_num <= head_num\n                    # head was created second. Prepend head to tail.\n                    tail.extendleft(reversed(head))\n                    # remove all traces of head:\n                    starts.pop(head[0])\n                    contours.pop(head_num, None)\n                    # Update contour starts end ends\n                    starts[tail[0]] = (tail, tail_num)\n                    ends[tail[-1]] = (tail, tail_num)\n        elif tail is None and head is None:\n            # we need to add a new contour\n            new_contour = deque((from_point, to_point))\n            contours[current_index] = new_contour\n            starts[from_point] = (new_contour, current_index)\n            ends[to_point] = (new_contour, current_index)\n            current_index += 1\n        elif head is None:  # tail is not None\n            # We've found a single contour to which the new segment should be\n            # prepended.\n            tail.appendleft(from_point)\n            starts[from_point] = (tail, tail_num)\n        else:  # tail is None and head is not None:\n            # We've found a single contour to which the new segment should be\n            # appended\n            head.append(to_point)\n            ends[to_point] = (head, head_num)\n\n    return [np.array(contour) for _, contour in sorted(contours.items())]\n", "path": "skimage/measure/_find_contours.py"}]}