We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
filter.threshold_isodata fails on 16-bit int images
The problem is the following line in threshholding.py:threshold_isodata():

```
    binnums = np.arange(pmf.size, dtype=np.uint8)
```

Obviously the histogram bin numbers for images with more than 255 intensity levels don't get generated properly, leading to hilarity. Changing that to dtype=np.uint16 should do the trick for 8- and 16-bit images, and float images as long as the nbins parameter is < 2**16. (This wouldn't work for 32-bit integer images -- are these even supported though?)


--- 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/filter/thresholding.py`
Content:
```
1 __all__ = ['threshold_adaptive',
2            'threshold_otsu',
3            'threshold_yen',
4            'threshold_isodata']
5 
6 import numpy as np
7 import scipy.ndimage
8 from skimage.exposure import histogram
9 
10 
11 def threshold_adaptive(image, block_size, method='gaussian', offset=0,
12                        mode='reflect', param=None):
13     """Applies an adaptive threshold to an array.
14 
15     Also known as local or dynamic thresholding where the threshold value is
16     the weighted mean for the local neighborhood of a pixel subtracted by a
17     constant. Alternatively the threshold can be determined dynamically by a a
18     given function using the 'generic' method.
19 
20     Parameters
21     ----------
22     image : (N, M) ndarray
23         Input image.
24     block_size : int
25         Uneven size of pixel neighborhood which is used to calculate the
26         threshold value (e.g. 3, 5, 7, ..., 21, ...).
27     method : {'generic', 'gaussian', 'mean', 'median'}, optional
28         Method used to determine adaptive threshold for local neighbourhood in
29         weighted mean image.
30 
31         * 'generic': use custom function (see `param` parameter)
32         * 'gaussian': apply gaussian filter (see `param` parameter for custom\
33                       sigma value)
34         * 'mean': apply arithmetic mean filter
35         * 'median': apply median rank filter
36 
37         By default the 'gaussian' method is used.
38     offset : float, optional
39         Constant subtracted from weighted mean of neighborhood to calculate
40         the local threshold value. Default offset is 0.
41     mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
42         The mode parameter determines how the array borders are handled, where
43         cval is the value when mode is equal to 'constant'.
44         Default is 'reflect'.
45     param : {int, function}, optional
46         Either specify sigma for 'gaussian' method or function object for
47         'generic' method. This functions takes the flat array of local
48         neighbourhood as a single argument and returns the calculated
49         threshold for the centre pixel.
50 
51     Returns
52     -------
53     threshold : (N, M) ndarray
54         Thresholded binary image
55 
56     References
57     ----------
58     .. [1] http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold
59 
60     Examples
61     --------
62     >>> from skimage.data import camera
63     >>> image = camera()[:50, :50]
64     >>> binary_image1 = threshold_adaptive(image, 15, 'mean')
65     >>> func = lambda arr: arr.mean()
66     >>> binary_image2 = threshold_adaptive(image, 15, 'generic', param=func)
67     """
68     thresh_image = np.zeros(image.shape, 'double')
69     if method == 'generic':
70         scipy.ndimage.generic_filter(image, param, block_size,
71                                      output=thresh_image, mode=mode)
72     elif method == 'gaussian':
73         if param is None:
74             # automatically determine sigma which covers > 99% of distribution
75             sigma = (block_size - 1) / 6.0
76         else:
77             sigma = param
78         scipy.ndimage.gaussian_filter(image, sigma, output=thresh_image,
79                                       mode=mode)
80     elif method == 'mean':
81         mask = 1. / block_size * np.ones((block_size,))
82         # separation of filters to speedup convolution
83         scipy.ndimage.convolve1d(image, mask, axis=0, output=thresh_image,
84                                  mode=mode)
85         scipy.ndimage.convolve1d(thresh_image, mask, axis=1,
86                                  output=thresh_image, mode=mode)
87     elif method == 'median':
88         scipy.ndimage.median_filter(image, block_size, output=thresh_image,
89                                     mode=mode)
90 
91     return image > (thresh_image - offset)
92 
93 
94 def threshold_otsu(image, nbins=256):
95     """Return threshold value based on Otsu's method.
96 
97     Parameters
98     ----------
99     image : array
100         Input image.
101     nbins : int, optional
102         Number of bins used to calculate histogram. This value is ignored for
103         integer arrays.
104 
105     Returns
106     -------
107     threshold : float
108         Upper threshold value. All pixels intensities that less or equal of
109         this value assumed as foreground.
110 
111     References
112     ----------
113     .. [1] Wikipedia, http://en.wikipedia.org/wiki/Otsu's_Method
114 
115     Examples
116     --------
117     >>> from skimage.data import camera
118     >>> image = camera()
119     >>> thresh = threshold_otsu(image)
120     >>> binary = image <= thresh
121     """
122     hist, bin_centers = histogram(image, nbins)
123     hist = hist.astype(float)
124 
125     # class probabilities for all possible thresholds
126     weight1 = np.cumsum(hist)
127     weight2 = np.cumsum(hist[::-1])[::-1]
128     # class means for all possible thresholds
129     mean1 = np.cumsum(hist * bin_centers) / weight1
130     mean2 = (np.cumsum((hist * bin_centers)[::-1]) / weight2[::-1])[::-1]
131 
132     # Clip ends to align class 1 and class 2 variables:
133     # The last value of `weight1`/`mean1` should pair with zero values in
134     # `weight2`/`mean2`, which do not exist.
135     variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2
136 
137     idx = np.argmax(variance12)
138     threshold = bin_centers[:-1][idx]
139     return threshold
140 
141 
142 def threshold_yen(image, nbins=256):
143     """Return threshold value based on Yen's method.
144 
145     Parameters
146     ----------
147     image : array
148         Input image.
149     nbins : int, optional
150         Number of bins used to calculate histogram. This value is ignored for
151         integer arrays.
152 
153     Returns
154     -------
155     threshold : float
156         Upper threshold value. All pixels intensities that less or equal of
157         this value assumed as foreground.
158 
159     References
160     ----------
161     .. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
162            for Automatic Multilevel Thresholding" IEEE Trans. on Image
163            Processing, 4(3): 370-378
164     .. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
165            Techniques and Quantitative Performance Evaluation" Journal of
166            Electronic Imaging, 13(1): 146-165,
167            http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
168     .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
169 
170     Examples
171     --------
172     >>> from skimage.data import camera
173     >>> image = camera()
174     >>> thresh = threshold_yen(image)
175     >>> binary = image <= thresh
176     """
177     hist, bin_centers = histogram(image, nbins)
178     # On blank images (e.g. filled with 0) with int dtype, `histogram()`
179     # returns `bin_centers` containing only one value. Speed up with it.
180     if bin_centers.size == 1:
181         return bin_centers[0]
182 
183     # Calculate probability mass function
184     pmf = hist.astype(np.float32) / hist.sum()
185     P1 = np.cumsum(pmf)  # Cumulative normalized histogram
186     P1_sq = np.cumsum(pmf ** 2)
187     # Get cumsum calculated from end of squared array:
188     P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1]
189     # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid '-inf'
190     # in crit. ImageJ Yen implementation replaces those values by zero.
191     crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) *
192                   (P1[:-1] * (1.0 - P1[:-1])) ** 2)
193     return bin_centers[crit.argmax()]
194 
195 
196 def threshold_isodata(image, nbins=256):
197     """Return threshold value based on ISODATA method.
198 
199     Histogram-based threshold, known as Ridler-Calvard method or intermeans.
200 
201     Parameters
202     ----------
203     image : array
204         Input image.
205     nbins : int, optional
206         Number of bins used to calculate histogram. This value is ignored for
207         integer arrays.
208 
209     Returns
210     -------
211     threshold : float or int, corresponding input array dtype.
212         Upper threshold value. All pixels intensities that less or equal of
213         this value assumed as background.
214 
215     References
216     ----------
217     .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an
218            iterative selection method"
219     .. [2] IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,
220            http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4310039
221     .. [3] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
222            Techniques and Quantitative Performance Evaluation" Journal of
223            Electronic Imaging, 13(1): 146-165,
224            http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
225     .. [4] ImageJ AutoThresholder code,
226            http://fiji.sc/wiki/index.php/Auto_Threshold
227 
228     Examples
229     --------
230     >>> from skimage.data import coins
231     >>> image = coins()
232     >>> thresh = threshold_isodata(image)
233     >>> binary = image > thresh
234     """
235     hist, bin_centers = histogram(image, nbins)
236     # On blank images (e.g. filled with 0) with int dtype, `histogram()`
237     # returns `bin_centers` containing only one value. Speed up with it.
238     if bin_centers.size == 1:
239         return bin_centers[0]
240     # It is not necessary to calculate the probability mass function here,
241     # because the l and h fractions already include the normalization.
242     pmf = hist.astype(np.float32)  # / hist.sum()
243     cpmfl = np.cumsum(pmf, dtype=np.float32)
244     cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]
245 
246     binnums = np.arange(pmf.size, dtype=np.uint8)
247     # l and h contain average value of pixels in sum of bins, calculated
248     # from lower to higher and from higher to lower respectively.
249     l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)
250     h = np.ma.divide(
251         np.cumsum((pmf[::-1] * binnums[::-1]), dtype=np.float32)[::-1],
252         cpmfh)
253 
254     allmean = (l + h) / 2.0
255     threshold = bin_centers[np.nonzero(allmean.round() == binnums)[0][0]]
256     # This implementation returns threshold where
257     # `background <= threshold < foreground`.
258     return threshold
259
```
--- 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/filter/thresholding.py b/skimage/filter/thresholding.py
--- a/skimage/filter/thresholding.py
+++ b/skimage/filter/thresholding.py
@@ -243,7 +243,7 @@
     cpmfl = np.cumsum(pmf, dtype=np.float32)
     cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]
 
-    binnums = np.arange(pmf.size, dtype=np.uint8)
+    binnums = np.arange(pmf.size, dtype=np.min_scalar_type(nbins))
     # l and h contain average value of pixels in sum of bins, calculated
     # from lower to higher and from higher to lower respectively.
     l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)

{"golden_diff": "diff --git a/skimage/filter/thresholding.py b/skimage/filter/thresholding.py\n--- a/skimage/filter/thresholding.py\n+++ b/skimage/filter/thresholding.py\n@@ -243,7 +243,7 @@\n     cpmfl = np.cumsum(pmf, dtype=np.float32)\n     cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]\n \n-    binnums = np.arange(pmf.size, dtype=np.uint8)\n+    binnums = np.arange(pmf.size, dtype=np.min_scalar_type(nbins))\n     # l and h contain average value of pixels in sum of bins, calculated\n     # from lower to higher and from higher to lower respectively.\n     l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)\n", "issue": "filter.threshold_isodata fails on 16-bit int images\nThe problem is the following line in threshholding.py:threshold_isodata():\n\n```\n    binnums = np.arange(pmf.size, dtype=np.uint8)\n```\n\nObviously the histogram bin numbers for images with more than 255 intensity levels don't get generated properly, leading to hilarity. Changing that to dtype=np.uint16 should do the trick for 8- and 16-bit images, and float images as long as the nbins parameter is < 2**16. (This wouldn't work for 32-bit integer images -- are these even supported though?)\n\n", "before_files": [{"content": "__all__ = ['threshold_adaptive',\n           'threshold_otsu',\n           'threshold_yen',\n           'threshold_isodata']\n\nimport numpy as np\nimport scipy.ndimage\nfrom skimage.exposure import histogram\n\n\ndef threshold_adaptive(image, block_size, method='gaussian', offset=0,\n                       mode='reflect', param=None):\n    \"\"\"Applies an adaptive threshold to an array.\n\n    Also known as local or dynamic thresholding where the threshold value is\n    the weighted mean for the local neighborhood of a pixel subtracted by a\n    constant. Alternatively the threshold can be determined dynamically by a a\n    given function using the 'generic' method.\n\n    Parameters\n    ----------\n    image : (N, M) ndarray\n        Input image.\n    block_size : int\n        Uneven size of pixel neighborhood which is used to calculate the\n        threshold value (e.g. 3, 5, 7, ..., 21, ...).\n    method : {'generic', 'gaussian', 'mean', 'median'}, optional\n        Method used to determine adaptive threshold for local neighbourhood in\n        weighted mean image.\n\n        * 'generic': use custom function (see `param` parameter)\n        * 'gaussian': apply gaussian filter (see `param` parameter for custom\\\n                      sigma value)\n        * 'mean': apply arithmetic mean filter\n        * 'median': apply median rank filter\n\n        By default the 'gaussian' method is used.\n    offset : float, optional\n        Constant subtracted from weighted mean of neighborhood to calculate\n        the local threshold value. Default offset is 0.\n    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional\n        The mode parameter determines how the array borders are handled, where\n        cval is the value when mode is equal to 'constant'.\n        Default is 'reflect'.\n    param : {int, function}, optional\n        Either specify sigma for 'gaussian' method or function object for\n        'generic' method. This functions takes the flat array of local\n        neighbourhood as a single argument and returns the calculated\n        threshold for the centre pixel.\n\n    Returns\n    -------\n    threshold : (N, M) ndarray\n        Thresholded binary image\n\n    References\n    ----------\n    .. [1] http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()[:50, :50]\n    >>> binary_image1 = threshold_adaptive(image, 15, 'mean')\n    >>> func = lambda arr: arr.mean()\n    >>> binary_image2 = threshold_adaptive(image, 15, 'generic', param=func)\n    \"\"\"\n    thresh_image = np.zeros(image.shape, 'double')\n    if method == 'generic':\n        scipy.ndimage.generic_filter(image, param, block_size,\n                                     output=thresh_image, mode=mode)\n    elif method == 'gaussian':\n        if param is None:\n            # automatically determine sigma which covers > 99% of distribution\n            sigma = (block_size - 1) / 6.0\n        else:\n            sigma = param\n        scipy.ndimage.gaussian_filter(image, sigma, output=thresh_image,\n                                      mode=mode)\n    elif method == 'mean':\n        mask = 1. / block_size * np.ones((block_size,))\n        # separation of filters to speedup convolution\n        scipy.ndimage.convolve1d(image, mask, axis=0, output=thresh_image,\n                                 mode=mode)\n        scipy.ndimage.convolve1d(thresh_image, mask, axis=1,\n                                 output=thresh_image, mode=mode)\n    elif method == 'median':\n        scipy.ndimage.median_filter(image, block_size, output=thresh_image,\n                                    mode=mode)\n\n    return image > (thresh_image - offset)\n\n\ndef threshold_otsu(image, nbins=256):\n    \"\"\"Return threshold value based on Otsu's method.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as foreground.\n\n    References\n    ----------\n    .. [1] Wikipedia, http://en.wikipedia.org/wiki/Otsu's_Method\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()\n    >>> thresh = threshold_otsu(image)\n    >>> binary = image <= thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    hist = hist.astype(float)\n\n    # class probabilities for all possible thresholds\n    weight1 = np.cumsum(hist)\n    weight2 = np.cumsum(hist[::-1])[::-1]\n    # class means for all possible thresholds\n    mean1 = np.cumsum(hist * bin_centers) / weight1\n    mean2 = (np.cumsum((hist * bin_centers)[::-1]) / weight2[::-1])[::-1]\n\n    # Clip ends to align class 1 and class 2 variables:\n    # The last value of `weight1`/`mean1` should pair with zero values in\n    # `weight2`/`mean2`, which do not exist.\n    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2\n\n    idx = np.argmax(variance12)\n    threshold = bin_centers[:-1][idx]\n    return threshold\n\n\ndef threshold_yen(image, nbins=256):\n    \"\"\"Return threshold value based on Yen's method.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as foreground.\n\n    References\n    ----------\n    .. [1] Yen J.C., Chang F.J., and Chang S. (1995) \"A New Criterion\n           for Automatic Multilevel Thresholding\" IEEE Trans. on Image\n           Processing, 4(3): 370-378\n    .. [2] Sezgin M. and Sankur B. (2004) \"Survey over Image Thresholding\n           Techniques and Quantitative Performance Evaluation\" Journal of\n           Electronic Imaging, 13(1): 146-165,\n           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf\n    .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()\n    >>> thresh = threshold_yen(image)\n    >>> binary = image <= thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    # On blank images (e.g. filled with 0) with int dtype, `histogram()`\n    # returns `bin_centers` containing only one value. Speed up with it.\n    if bin_centers.size == 1:\n        return bin_centers[0]\n\n    # Calculate probability mass function\n    pmf = hist.astype(np.float32) / hist.sum()\n    P1 = np.cumsum(pmf)  # Cumulative normalized histogram\n    P1_sq = np.cumsum(pmf ** 2)\n    # Get cumsum calculated from end of squared array:\n    P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1]\n    # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid '-inf'\n    # in crit. ImageJ Yen implementation replaces those values by zero.\n    crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) *\n                  (P1[:-1] * (1.0 - P1[:-1])) ** 2)\n    return bin_centers[crit.argmax()]\n\n\ndef threshold_isodata(image, nbins=256):\n    \"\"\"Return threshold value based on ISODATA method.\n\n    Histogram-based threshold, known as Ridler-Calvard method or intermeans.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float or int, corresponding input array dtype.\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as background.\n\n    References\n    ----------\n    .. [1] Ridler, TW & Calvard, S (1978), \"Picture thresholding using an\n           iterative selection method\"\n    .. [2] IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,\n           http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4310039\n    .. [3] Sezgin M. and Sankur B. (2004) \"Survey over Image Thresholding\n           Techniques and Quantitative Performance Evaluation\" Journal of\n           Electronic Imaging, 13(1): 146-165,\n           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf\n    .. [4] ImageJ AutoThresholder code,\n           http://fiji.sc/wiki/index.php/Auto_Threshold\n\n    Examples\n    --------\n    >>> from skimage.data import coins\n    >>> image = coins()\n    >>> thresh = threshold_isodata(image)\n    >>> binary = image > thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    # On blank images (e.g. filled with 0) with int dtype, `histogram()`\n    # returns `bin_centers` containing only one value. Speed up with it.\n    if bin_centers.size == 1:\n        return bin_centers[0]\n    # It is not necessary to calculate the probability mass function here,\n    # because the l and h fractions already include the normalization.\n    pmf = hist.astype(np.float32)  # / hist.sum()\n    cpmfl = np.cumsum(pmf, dtype=np.float32)\n    cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]\n\n    binnums = np.arange(pmf.size, dtype=np.uint8)\n    # l and h contain average value of pixels in sum of bins, calculated\n    # from lower to higher and from higher to lower respectively.\n    l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)\n    h = np.ma.divide(\n        np.cumsum((pmf[::-1] * binnums[::-1]), dtype=np.float32)[::-1],\n        cpmfh)\n\n    allmean = (l + h) / 2.0\n    threshold = bin_centers[np.nonzero(allmean.round() == binnums)[0][0]]\n    # This implementation returns threshold where\n    # `background <= threshold < foreground`.\n    return threshold\n", "path": "skimage/filter/thresholding.py"}], "after_files": [{"content": "__all__ = ['threshold_adaptive',\n           'threshold_otsu',\n           'threshold_yen',\n           'threshold_isodata']\n\nimport numpy as np\nimport scipy.ndimage\nfrom skimage.exposure import histogram\n\n\ndef threshold_adaptive(image, block_size, method='gaussian', offset=0,\n                       mode='reflect', param=None):\n    \"\"\"Applies an adaptive threshold to an array.\n\n    Also known as local or dynamic thresholding where the threshold value is\n    the weighted mean for the local neighborhood of a pixel subtracted by a\n    constant. Alternatively the threshold can be determined dynamically by a a\n    given function using the 'generic' method.\n\n    Parameters\n    ----------\n    image : (N, M) ndarray\n        Input image.\n    block_size : int\n        Uneven size of pixel neighborhood which is used to calculate the\n        threshold value (e.g. 3, 5, 7, ..., 21, ...).\n    method : {'generic', 'gaussian', 'mean', 'median'}, optional\n        Method used to determine adaptive threshold for local neighbourhood in\n        weighted mean image.\n\n        * 'generic': use custom function (see `param` parameter)\n        * 'gaussian': apply gaussian filter (see `param` parameter for custom\\\n                      sigma value)\n        * 'mean': apply arithmetic mean filter\n        * 'median': apply median rank filter\n\n        By default the 'gaussian' method is used.\n    offset : float, optional\n        Constant subtracted from weighted mean of neighborhood to calculate\n        the local threshold value. Default offset is 0.\n    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional\n        The mode parameter determines how the array borders are handled, where\n        cval is the value when mode is equal to 'constant'.\n        Default is 'reflect'.\n    param : {int, function}, optional\n        Either specify sigma for 'gaussian' method or function object for\n        'generic' method. This functions takes the flat array of local\n        neighbourhood as a single argument and returns the calculated\n        threshold for the centre pixel.\n\n    Returns\n    -------\n    threshold : (N, M) ndarray\n        Thresholded binary image\n\n    References\n    ----------\n    .. [1] http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()[:50, :50]\n    >>> binary_image1 = threshold_adaptive(image, 15, 'mean')\n    >>> func = lambda arr: arr.mean()\n    >>> binary_image2 = threshold_adaptive(image, 15, 'generic', param=func)\n    \"\"\"\n    thresh_image = np.zeros(image.shape, 'double')\n    if method == 'generic':\n        scipy.ndimage.generic_filter(image, param, block_size,\n                                     output=thresh_image, mode=mode)\n    elif method == 'gaussian':\n        if param is None:\n            # automatically determine sigma which covers > 99% of distribution\n            sigma = (block_size - 1) / 6.0\n        else:\n            sigma = param\n        scipy.ndimage.gaussian_filter(image, sigma, output=thresh_image,\n                                      mode=mode)\n    elif method == 'mean':\n        mask = 1. / block_size * np.ones((block_size,))\n        # separation of filters to speedup convolution\n        scipy.ndimage.convolve1d(image, mask, axis=0, output=thresh_image,\n                                 mode=mode)\n        scipy.ndimage.convolve1d(thresh_image, mask, axis=1,\n                                 output=thresh_image, mode=mode)\n    elif method == 'median':\n        scipy.ndimage.median_filter(image, block_size, output=thresh_image,\n                                    mode=mode)\n\n    return image > (thresh_image - offset)\n\n\ndef threshold_otsu(image, nbins=256):\n    \"\"\"Return threshold value based on Otsu's method.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as foreground.\n\n    References\n    ----------\n    .. [1] Wikipedia, http://en.wikipedia.org/wiki/Otsu's_Method\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()\n    >>> thresh = threshold_otsu(image)\n    >>> binary = image <= thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    hist = hist.astype(float)\n\n    # class probabilities for all possible thresholds\n    weight1 = np.cumsum(hist)\n    weight2 = np.cumsum(hist[::-1])[::-1]\n    # class means for all possible thresholds\n    mean1 = np.cumsum(hist * bin_centers) / weight1\n    mean2 = (np.cumsum((hist * bin_centers)[::-1]) / weight2[::-1])[::-1]\n\n    # Clip ends to align class 1 and class 2 variables:\n    # The last value of `weight1`/`mean1` should pair with zero values in\n    # `weight2`/`mean2`, which do not exist.\n    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2\n\n    idx = np.argmax(variance12)\n    threshold = bin_centers[:-1][idx]\n    return threshold\n\n\ndef threshold_yen(image, nbins=256):\n    \"\"\"Return threshold value based on Yen's method.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as foreground.\n\n    References\n    ----------\n    .. [1] Yen J.C., Chang F.J., and Chang S. (1995) \"A New Criterion\n           for Automatic Multilevel Thresholding\" IEEE Trans. on Image\n           Processing, 4(3): 370-378\n    .. [2] Sezgin M. and Sankur B. (2004) \"Survey over Image Thresholding\n           Techniques and Quantitative Performance Evaluation\" Journal of\n           Electronic Imaging, 13(1): 146-165,\n           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf\n    .. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold\n\n    Examples\n    --------\n    >>> from skimage.data import camera\n    >>> image = camera()\n    >>> thresh = threshold_yen(image)\n    >>> binary = image <= thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    # On blank images (e.g. filled with 0) with int dtype, `histogram()`\n    # returns `bin_centers` containing only one value. Speed up with it.\n    if bin_centers.size == 1:\n        return bin_centers[0]\n\n    # Calculate probability mass function\n    pmf = hist.astype(np.float32) / hist.sum()\n    P1 = np.cumsum(pmf)  # Cumulative normalized histogram\n    P1_sq = np.cumsum(pmf ** 2)\n    # Get cumsum calculated from end of squared array:\n    P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1]\n    # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid '-inf'\n    # in crit. ImageJ Yen implementation replaces those values by zero.\n    crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) *\n                  (P1[:-1] * (1.0 - P1[:-1])) ** 2)\n    return bin_centers[crit.argmax()]\n\n\ndef threshold_isodata(image, nbins=256):\n    \"\"\"Return threshold value based on ISODATA method.\n\n    Histogram-based threshold, known as Ridler-Calvard method or intermeans.\n\n    Parameters\n    ----------\n    image : array\n        Input image.\n    nbins : int, optional\n        Number of bins used to calculate histogram. This value is ignored for\n        integer arrays.\n\n    Returns\n    -------\n    threshold : float or int, corresponding input array dtype.\n        Upper threshold value. All pixels intensities that less or equal of\n        this value assumed as background.\n\n    References\n    ----------\n    .. [1] Ridler, TW & Calvard, S (1978), \"Picture thresholding using an\n           iterative selection method\"\n    .. [2] IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,\n           http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4310039\n    .. [3] Sezgin M. and Sankur B. (2004) \"Survey over Image Thresholding\n           Techniques and Quantitative Performance Evaluation\" Journal of\n           Electronic Imaging, 13(1): 146-165,\n           http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf\n    .. [4] ImageJ AutoThresholder code,\n           http://fiji.sc/wiki/index.php/Auto_Threshold\n\n    Examples\n    --------\n    >>> from skimage.data import coins\n    >>> image = coins()\n    >>> thresh = threshold_isodata(image)\n    >>> binary = image > thresh\n    \"\"\"\n    hist, bin_centers = histogram(image, nbins)\n    # On blank images (e.g. filled with 0) with int dtype, `histogram()`\n    # returns `bin_centers` containing only one value. Speed up with it.\n    if bin_centers.size == 1:\n        return bin_centers[0]\n    # It is not necessary to calculate the probability mass function here,\n    # because the l and h fractions already include the normalization.\n    pmf = hist.astype(np.float32)  # / hist.sum()\n    cpmfl = np.cumsum(pmf, dtype=np.float32)\n    cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]\n\n    binnums = np.arange(pmf.size, dtype=np.min_scalar_type(nbins))\n    # l and h contain average value of pixels in sum of bins, calculated\n    # from lower to higher and from higher to lower respectively.\n    l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)\n    h = np.ma.divide(\n        np.cumsum((pmf[::-1] * binnums[::-1]), dtype=np.float32)[::-1],\n        cpmfh)\n\n    allmean = (l + h) / 2.0\n    threshold = bin_centers[np.nonzero(allmean.round() == binnums)[0][0]]\n    # This implementation returns threshold where\n    # `background <= threshold < foreground`.\n    return threshold\n", "path": "skimage/filter/thresholding.py"}]}