Datasets:

Modalities:
Image
Text
Formats:
text
Size:
< 1K
Libraries:
Datasets
License:
ZijunCui commited on
Commit
a65c2f8
·
verified ·
1 Parent(s): 33d1d58

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. envs/kitoverlay/skimage/_shared/__pycache__/__init__.cpython-311.pyc +0 -0
  2. envs/kitoverlay/skimage/_shared/__pycache__/_dependency_checks.cpython-311.pyc +0 -0
  3. envs/kitoverlay/skimage/_shared/__pycache__/_geometry.cpython-311.pyc +0 -0
  4. envs/kitoverlay/skimage/_shared/__pycache__/_tempfile.cpython-311.pyc +0 -0
  5. envs/kitoverlay/skimage/_shared/__pycache__/_warnings.cpython-311.pyc +0 -0
  6. envs/kitoverlay/skimage/_shared/__pycache__/compat.cpython-311.pyc +0 -0
  7. envs/kitoverlay/skimage/_shared/__pycache__/coord.cpython-311.pyc +0 -0
  8. envs/kitoverlay/skimage/_shared/__pycache__/dtype.cpython-311.pyc +0 -0
  9. envs/kitoverlay/skimage/_shared/__pycache__/filters.cpython-311.pyc +0 -0
  10. envs/kitoverlay/skimage/_shared/__pycache__/tester.cpython-311.pyc +0 -0
  11. envs/kitoverlay/skimage/_shared/__pycache__/testing.cpython-311.pyc +0 -0
  12. envs/kitoverlay/skimage/_shared/__pycache__/utils.cpython-311.pyc +0 -0
  13. envs/kitoverlay/skimage/_shared/__pycache__/version_requirements.cpython-311.pyc +0 -0
  14. envs/kitoverlay/skimage/_shared/_dependency_checks.py +7 -0
  15. envs/kitoverlay/skimage/_shared/_warnings.py +149 -0
  16. envs/kitoverlay/skimage/_shared/compat.py +32 -0
  17. envs/kitoverlay/skimage/_shared/dtype.py +73 -0
  18. envs/kitoverlay/skimage/_shared/fast_exp.h +47 -0
  19. envs/kitoverlay/skimage/_shared/filters.py +136 -0
  20. envs/kitoverlay/skimage/_shared/testing.py +327 -0
  21. envs/kitoverlay/skimage/_shared/utils.py +1099 -0
  22. envs/kitoverlay/skimage/feature/__pycache__/_daisy.cpython-311.pyc +0 -0
  23. envs/kitoverlay/skimage/feature/__pycache__/brief.cpython-311.pyc +0 -0
  24. envs/kitoverlay/skimage/feature/__pycache__/template.cpython-311.pyc +0 -0
  25. envs/kitoverlay/skimage/graph/__init__.py +12 -0
  26. envs/kitoverlay/skimage/graph/__init__.pyi +27 -0
  27. envs/kitoverlay/skimage/graph/__pycache__/__init__.cpython-311.pyc +0 -0
  28. envs/kitoverlay/skimage/graph/__pycache__/_graph.cpython-311.pyc +0 -0
  29. envs/kitoverlay/skimage/graph/__pycache__/_graph_cut.cpython-311.pyc +0 -0
  30. envs/kitoverlay/skimage/graph/__pycache__/_graph_merge.cpython-311.pyc +0 -0
  31. envs/kitoverlay/skimage/graph/__pycache__/_ncut.cpython-311.pyc +0 -0
  32. envs/kitoverlay/skimage/graph/__pycache__/_rag.cpython-311.pyc +0 -0
  33. envs/kitoverlay/skimage/graph/__pycache__/mcp.cpython-311.pyc +0 -0
  34. envs/kitoverlay/skimage/graph/__pycache__/spath.cpython-311.pyc +0 -0
  35. envs/kitoverlay/skimage/graph/_graph.py +220 -0
  36. envs/kitoverlay/skimage/graph/_graph_cut.py +319 -0
  37. envs/kitoverlay/skimage/graph/_graph_merge.py +138 -0
  38. envs/kitoverlay/skimage/graph/_ncut.py +64 -0
  39. envs/kitoverlay/skimage/graph/_rag.py +581 -0
  40. envs/kitoverlay/skimage/graph/mcp.py +88 -0
  41. envs/kitoverlay/skimage/graph/spath.py +83 -0
  42. envs/kitoverlay/skimage/registration/__init__.py +5 -0
  43. envs/kitoverlay/skimage/registration/__init__.pyi +8 -0
  44. envs/kitoverlay/skimage/registration/__pycache__/__init__.cpython-311.pyc +0 -0
  45. envs/kitoverlay/skimage/registration/__pycache__/_masked_phase_cross_correlation.cpython-311.pyc +0 -0
  46. envs/kitoverlay/skimage/registration/__pycache__/_optical_flow.cpython-311.pyc +0 -0
  47. envs/kitoverlay/skimage/registration/__pycache__/_optical_flow_utils.cpython-311.pyc +0 -0
  48. envs/kitoverlay/skimage/registration/__pycache__/_phase_cross_correlation.cpython-311.pyc +0 -0
  49. envs/kitoverlay/skimage/registration/_masked_phase_cross_correlation.py +306 -0
  50. envs/kitoverlay/skimage/registration/_optical_flow.py +429 -0
envs/kitoverlay/skimage/_shared/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (172 Bytes). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/_dependency_checks.cpython-311.pyc ADDED
Binary file (513 Bytes). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/_geometry.cpython-311.pyc ADDED
Binary file (2.4 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/_tempfile.cpython-311.pyc ADDED
Binary file (1.32 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/_warnings.cpython-311.pyc ADDED
Binary file (6.15 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/compat.cpython-311.pyc ADDED
Binary file (879 Bytes). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/coord.cpython-311.pyc ADDED
Binary file (5.2 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/dtype.cpython-311.pyc ADDED
Binary file (3.08 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/filters.cpython-311.pyc ADDED
Binary file (5.72 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/tester.cpython-311.pyc ADDED
Binary file (4.39 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/testing.cpython-311.pyc ADDED
Binary file (14 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/utils.cpython-311.pyc ADDED
Binary file (44.6 kB). View file
 
envs/kitoverlay/skimage/_shared/__pycache__/version_requirements.cpython-311.pyc ADDED
Binary file (5.9 kB). View file
 
envs/kitoverlay/skimage/_shared/_dependency_checks.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .version_requirements import is_installed
2
+ import sys
3
+ import platform
4
+
5
+ has_mpl = is_installed("matplotlib", ">=3.3")
6
+
7
+ is_wasm = (sys.platform == "emscripten") or (platform.machine() in ["wasm32", "wasm64"])
envs/kitoverlay/skimage/_shared/_warnings.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ import sys
3
+ import warnings
4
+ import re
5
+ import functools
6
+ import os
7
+
8
+ __all__ = ['all_warnings', 'expected_warnings', 'warn']
9
+
10
+
11
+ # A version of `warnings.warn` with a default stacklevel of 2.
12
+ # functool is used so as not to increase the call stack accidentally
13
+ warn = functools.partial(warnings.warn, stacklevel=2)
14
+
15
+
16
+ @contextmanager
17
+ def all_warnings():
18
+ """
19
+ Context for use in testing to ensure that all warnings are raised.
20
+
21
+ Examples
22
+ --------
23
+ >>> import warnings
24
+ >>> def foo():
25
+ ... warnings.warn(RuntimeWarning("bar"), stacklevel=2)
26
+
27
+ We raise the warning once, while the warning filter is set to "once".
28
+ Hereafter, the warning is invisible, even with custom filters:
29
+
30
+ >>> with warnings.catch_warnings():
31
+ ... warnings.simplefilter('once')
32
+ ... foo() # doctest: +SKIP
33
+
34
+ We can now run ``foo()`` without a warning being raised:
35
+
36
+ >>> from numpy.testing import assert_warns
37
+ >>> foo() # doctest: +SKIP
38
+
39
+ To catch the warning, we call in the help of ``all_warnings``:
40
+
41
+ >>> with all_warnings():
42
+ ... assert_warns(RuntimeWarning, foo)
43
+ """
44
+ # _warnings.py is on the critical import path.
45
+ # Since this is a testing only function, we lazy import inspect.
46
+ import inspect
47
+
48
+ # Whenever a warning is triggered, Python adds a __warningregistry__
49
+ # member to the *calling* module. The exercise here is to find
50
+ # and eradicate all those breadcrumbs that were left lying around.
51
+ #
52
+ # We proceed by first searching all parent calling frames and explicitly
53
+ # clearing their warning registries (necessary for the doctests above to
54
+ # pass). Then, we search for all submodules of skimage and clear theirs
55
+ # as well (necessary for the skimage test suite to pass).
56
+
57
+ frame = inspect.currentframe()
58
+ if frame:
59
+ for f in inspect.getouterframes(frame):
60
+ f[0].f_locals['__warningregistry__'] = {}
61
+ del frame
62
+
63
+ for mod_name, mod in list(sys.modules.items()):
64
+ try:
65
+ mod.__warningregistry__.clear()
66
+ except AttributeError:
67
+ pass
68
+
69
+ with warnings.catch_warnings(record=True) as w:
70
+ warnings.simplefilter("always")
71
+ yield w
72
+
73
+
74
+ @contextmanager
75
+ def expected_warnings(matching):
76
+ r"""Context for use in testing to catch known warnings matching regexes
77
+
78
+ Parameters
79
+ ----------
80
+ matching : None or a list of strings or compiled regexes
81
+ Regexes for the desired warning to catch
82
+ If matching is None, this behaves as a no-op.
83
+
84
+ Examples
85
+ --------
86
+ >>> import numpy as np
87
+ >>> rng = np.random.default_rng()
88
+ >>> image = rng.integers(0, 2**16, size=(100, 100), dtype=np.uint16)
89
+ >>> # rank filters are slow when bit-depth exceeds 10 bits
90
+ >>> from skimage import filters
91
+ >>> with expected_warnings(['Bad rank filter performance']):
92
+ ... median_filtered = filters.rank.median(image)
93
+
94
+ Notes
95
+ -----
96
+ Uses `all_warnings` to ensure all warnings are raised.
97
+ Upon exiting, it checks the recorded warnings for the desired matching
98
+ pattern(s).
99
+ Raises a ValueError if any match was not found or an unexpected
100
+ warning was raised.
101
+ Allows for three types of behaviors: `and`, `or`, and `optional` matches.
102
+ This is done to accommodate different build environments or loop conditions
103
+ that may produce different warnings. The behaviors can be combined.
104
+ If you pass multiple patterns, you get an orderless `and`, where all of the
105
+ warnings must be raised.
106
+ If you use the `|` operator in a pattern, you can catch one of several
107
+ warnings.
108
+ Finally, you can use `|\A\Z` in a pattern to signify it as optional.
109
+
110
+ """
111
+ if isinstance(matching, str):
112
+ raise ValueError(
113
+ '``matching`` should be a list of strings and not a string itself.'
114
+ )
115
+
116
+ # Special case for disabling the context manager
117
+ if matching is None:
118
+ yield None
119
+ return
120
+
121
+ strict_warnings = os.environ.get('SKIMAGE_TEST_STRICT_WARNINGS', '1')
122
+ if strict_warnings.lower() == 'true':
123
+ strict_warnings = True
124
+ elif strict_warnings.lower() == 'false':
125
+ strict_warnings = False
126
+ else:
127
+ strict_warnings = bool(int(strict_warnings))
128
+
129
+ with all_warnings() as w:
130
+ # enter context
131
+ yield w
132
+ # exited user context, check the recorded warnings
133
+ # Allow users to provide None
134
+ while None in matching:
135
+ matching.remove(None)
136
+ remaining = [m for m in matching if r'\A\Z' not in m.split('|')]
137
+ for warn in w:
138
+ found = False
139
+ for match in matching:
140
+ if re.search(match, str(warn.message)) is not None:
141
+ found = True
142
+ if match in remaining:
143
+ remaining.remove(match)
144
+ if strict_warnings and not found:
145
+ raise ValueError(f'Unexpected warning: {str(warn.message)}')
146
+ if strict_warnings and (len(remaining) > 0):
147
+ newline = "\n"
148
+ msg = f"No warning raised matching:{newline}{newline.join(remaining)}"
149
+ raise ValueError(msg)
envs/kitoverlay/skimage/_shared/compat.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility helpers for dependencies."""
2
+
3
+ from packaging.version import parse
4
+
5
+ import numpy as np
6
+ import scipy as sp
7
+
8
+
9
+ __all__ = [
10
+ "NP_COPY_IF_NEEDED",
11
+ "SCIPY_CG_TOL_PARAM_NAME",
12
+ ]
13
+
14
+
15
+ NUMPY_LT_2_0_0 = parse(np.__version__) < parse('2.0.0.dev0')
16
+
17
+ # With NumPy 2.0.0, `copy=False` now raises a ValueError if the copy cannot be
18
+ # made. The previous behavior to only copy if needed is provided with `copy=None`.
19
+ # During the transition period, use this symbol instead.
20
+ # Remove once NumPy 2.0.0 is the minimal required version.
21
+ # https://numpy.org/devdocs/release/2.0.0-notes.html#new-copy-keyword-meaning-for-array-and-asarray-constructors
22
+ # https://github.com/numpy/numpy/pull/25168
23
+ NP_COPY_IF_NEEDED = False if NUMPY_LT_2_0_0 else None
24
+
25
+
26
+ SCIPY_LT_1_12 = parse(sp.__version__) < parse('1.12')
27
+
28
+ # Starting in SciPy v1.12, 'scipy.sparse.linalg.cg' keyword argument `tol` is
29
+ # deprecated in favor of `rtol`.
30
+ SCIPY_CG_TOL_PARAM_NAME = "tol" if SCIPY_LT_1_12 else "rtol"
31
+
32
+ SCIPY_GE_1_17_0_DEV0 = parse('1.17.0.dev0') <= parse(sp.__version__)
envs/kitoverlay/skimage/_shared/dtype.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ # Define classes of supported dtypes and Python scalar types
4
+ # Variables ending in `_dtypes` only contain numpy.dtypes of the respective
5
+ # class; variables ending in `_types` additionally include Python scalar types.
6
+ signed_integer_dtypes = {np.int8, np.int16, np.int32, np.int64}
7
+ signed_integer_types = signed_integer_dtypes | {int}
8
+
9
+ unsigned_integer_dtypes = {np.uint8, np.uint16, np.uint32, np.uint64}
10
+
11
+ integer_dtypes = signed_integer_dtypes | unsigned_integer_dtypes
12
+ integer_types = signed_integer_types | unsigned_integer_dtypes
13
+
14
+ floating_dtypes = {np.float16, np.float32, np.float64}
15
+ floating_types = floating_dtypes | {float}
16
+
17
+ complex_dtypes = {np.complex64, np.complex128}
18
+ complex_types = complex_dtypes | {complex}
19
+
20
+ inexact_dtypes = floating_dtypes | complex_dtypes
21
+ inexact_types = floating_types | complex_types
22
+
23
+ bool_types = {np.dtype(bool), bool}
24
+
25
+ numeric_dtypes = integer_dtypes | inexact_dtypes | {np.bool_}
26
+ numeric_types = integer_types | inexact_types | bool_types
27
+
28
+
29
+ def numeric_dtype_min_max(dtype):
30
+ """Return minimum and maximum representable value for a given dtype.
31
+
32
+ A convenient wrapper around `numpy.finfo` and `numpy.iinfo` that
33
+ additionally supports numpy.bool as well.
34
+
35
+ Parameters
36
+ ----------
37
+ dtype : numpy.dtype
38
+ The dtype. Tries to convert Python "types" such as int or float, to
39
+ the corresponding NumPy dtype.
40
+
41
+ Returns
42
+ -------
43
+ min, max : number
44
+ Minimum and maximum of the given `dtype`. These scalars are themselves
45
+ of the given `dtype`.
46
+
47
+ Examples
48
+ --------
49
+ >>> import numpy as np
50
+ >>> numeric_dtype_min_max(np.uint8)
51
+ (0, 255)
52
+ >>> numeric_dtype_min_max(bool)
53
+ (False, True)
54
+ >>> numeric_dtype_min_max(np.float64)
55
+ (-1.7976931348623157e+308, 1.7976931348623157e+308)
56
+ >>> numeric_dtype_min_max(int)
57
+ (-9223372036854775808, 9223372036854775807)
58
+ """
59
+ dtype = np.dtype(dtype)
60
+ if np.issubdtype(dtype, np.integer):
61
+ info = np.iinfo(dtype)
62
+ min_ = dtype.type(info.min)
63
+ max_ = dtype.type(info.max)
64
+ elif np.issubdtype(dtype, np.inexact):
65
+ info = np.finfo(dtype)
66
+ min_ = info.min
67
+ max_ = info.max
68
+ elif np.issubdtype(dtype, np.dtype(bool)):
69
+ min_ = dtype.type(False)
70
+ max_ = dtype.type(True)
71
+ else:
72
+ raise ValueError(f"unsupported dtype {dtype!r}")
73
+ return min_, max_
envs/kitoverlay/skimage/_shared/fast_exp.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* A fast approximation of the exponential function.
2
+ * Reference [1]: https://schraudolph.org/pubs/Schraudolph99.pdf
3
+ * Reference [2]: https://doi.org/10.1162/089976600300015033
4
+ * Additional improvements by Leonid Bloch. */
5
+
6
+ #include <stdint.h>
7
+
8
+ /* use just EXP_A = 1512775 for integer version, to avoid FP calculations */
9
+ #define EXP_A (1512775.3951951856938) /* 2^20/ln2 */
10
+ /* For min. RMS error */
11
+ #define EXP_BC 1072632447 /* 1023*2^20 - 60801 */
12
+ /* For min. max. relative error */
13
+ /* #define EXP_BC 1072647449 */ /* 1023*2^20 - 45799 */
14
+ /* For min. mean relative error */
15
+ /* #define EXP_BC 1072625005 */ /* 1023*2^20 - 68243 */
16
+
17
+ __inline double _fast_exp (double y)
18
+ {
19
+ union
20
+ {
21
+ double d;
22
+ struct { int32_t i, j; } n;
23
+ char t[8];
24
+ } _eco;
25
+
26
+ _eco.n.i = 1;
27
+
28
+ switch(_eco.t[0]) {
29
+ case 1:
30
+ /* Little endian */
31
+ _eco.n.j = (int32_t)(EXP_A*(y)) + EXP_BC;
32
+ _eco.n.i = 0;
33
+ break;
34
+ case 0:
35
+ /* Big endian */
36
+ _eco.n.i = (int32_t)(EXP_A*(y)) + EXP_BC;
37
+ _eco.n.j = 0;
38
+ break;
39
+ }
40
+
41
+ return _eco.d;
42
+ }
43
+
44
+ __inline float _fast_expf (float y)
45
+ {
46
+ return (float)_fast_exp((double)y);
47
+ }
envs/kitoverlay/skimage/_shared/filters.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filters used across multiple skimage submodules.
2
+
3
+ These are defined here to avoid circular imports.
4
+
5
+ The unit tests remain under skimage/filters/tests/
6
+ """
7
+
8
+ from collections.abc import Iterable
9
+
10
+ import numpy as np
11
+ from scipy import ndimage as ndi
12
+
13
+ from .._shared.utils import (
14
+ _supported_float_type,
15
+ convert_to_float,
16
+ )
17
+
18
+
19
+ def gaussian(
20
+ image,
21
+ sigma=1.0,
22
+ *,
23
+ mode='nearest',
24
+ cval=0,
25
+ preserve_range=False,
26
+ truncate=4.0,
27
+ channel_axis=None,
28
+ out=None,
29
+ ):
30
+ """Multi-dimensional Gaussian filter.
31
+
32
+ Parameters
33
+ ----------
34
+ image : ndarray
35
+ Input image (grayscale or color) to filter.
36
+ sigma : scalar or sequence of scalars, optional
37
+ Standard deviation for Gaussian kernel. The standard
38
+ deviations of the Gaussian filter are given for each axis as a
39
+ sequence, or as a single number, in which case it is equal for
40
+ all axes.
41
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
42
+ The ``mode`` parameter determines how the array borders are
43
+ handled, where ``cval`` is the value when mode is equal to
44
+ 'constant'. Default is 'nearest'.
45
+ cval : scalar, optional
46
+ Value to fill past edges of input if ``mode`` is 'constant'. Default
47
+ is 0.0
48
+ preserve_range : bool, optional
49
+ If True, keep the original range of values. Otherwise, the input
50
+ ``image`` is converted according to the conventions of ``img_as_float``
51
+ (Normalized first to values [-1.0 ; 1.0] or [0 ; 1.0] depending on
52
+ dtype of input)
53
+
54
+ For more information, see:
55
+ https://scikit-image.org/docs/dev/user_guide/data_types.html
56
+ truncate : float, optional
57
+ Truncate the filter at this many standard deviations.
58
+ channel_axis : int or None, optional
59
+ If None, the image is assumed to be a grayscale (single channel) image.
60
+ Otherwise, this parameter indicates which axis of the array corresponds
61
+ to channels.
62
+
63
+ .. versionadded:: 0.19
64
+ `channel_axis` was added in 0.19.
65
+ out : ndarray, optional
66
+ If given, the filtered image will be stored in this array.
67
+
68
+ .. versionadded:: 0.23
69
+ `out` was added in 0.23.
70
+
71
+ Returns
72
+ -------
73
+ filtered_image : ndarray
74
+ the filtered array
75
+
76
+ Notes
77
+ -----
78
+ This function is a wrapper around :func:`scipy.ndimage.gaussian_filter`.
79
+
80
+ Integer arrays are converted to float.
81
+
82
+ `out` should be of floating-point data type since `gaussian` converts the
83
+ input `image` to float. If `out` is not provided, another array
84
+ will be allocated and returned as the result.
85
+
86
+ The multi-dimensional filter is implemented as a sequence of
87
+ one-dimensional convolution filters. The intermediate arrays are
88
+ stored in the same data type as the output. Therefore, for output
89
+ types with a limited precision, the results may be imprecise
90
+ because intermediate results may be stored with insufficient
91
+ precision.
92
+
93
+ Examples
94
+ --------
95
+ >>> import skimage as ski
96
+ >>> a = np.zeros((3, 3))
97
+ >>> a[1, 1] = 1
98
+ >>> a
99
+ array([[0., 0., 0.],
100
+ [0., 1., 0.],
101
+ [0., 0., 0.]])
102
+ >>> ski.filters.gaussian(a, sigma=0.4) # mild smoothing
103
+ array([[0.00163116, 0.03712502, 0.00163116],
104
+ [0.03712502, 0.84496158, 0.03712502],
105
+ [0.00163116, 0.03712502, 0.00163116]])
106
+ >>> ski.filters.gaussian(a, sigma=1) # more smoothing
107
+ array([[0.05855018, 0.09653293, 0.05855018],
108
+ [0.09653293, 0.15915589, 0.09653293],
109
+ [0.05855018, 0.09653293, 0.05855018]])
110
+ >>> # Several modes are possible for handling boundaries
111
+ >>> ski.filters.gaussian(a, sigma=1, mode='reflect')
112
+ array([[0.08767308, 0.12075024, 0.08767308],
113
+ [0.12075024, 0.16630671, 0.12075024],
114
+ [0.08767308, 0.12075024, 0.08767308]])
115
+ >>> # For RGB images, each is filtered separately
116
+ >>> image = ski.data.astronaut()
117
+ >>> filtered_img = ski.filters.gaussian(image, sigma=1, channel_axis=-1)
118
+
119
+ """
120
+ if np.any(np.asarray(sigma) < 0.0):
121
+ raise ValueError("Sigma values less than zero are not valid")
122
+ if channel_axis is not None:
123
+ # do not filter across channels
124
+ if not isinstance(sigma, Iterable):
125
+ sigma = [sigma] * (image.ndim - 1)
126
+ if len(sigma) == image.ndim - 1:
127
+ sigma = list(sigma)
128
+ sigma.insert(channel_axis % image.ndim, 0)
129
+ image = convert_to_float(image, preserve_range)
130
+ float_dtype = _supported_float_type(image.dtype)
131
+ image = image.astype(float_dtype, copy=False)
132
+ if (out is not None) and (not np.issubdtype(out.dtype, np.floating)):
133
+ raise ValueError(f"dtype of `out` must be float; got {out.dtype!r}.")
134
+ return ndi.gaussian_filter(
135
+ image, sigma, output=out, mode=mode, cval=cval, truncate=truncate
136
+ )
envs/kitoverlay/skimage/_shared/testing.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing utilities.
3
+ """
4
+
5
+ import os
6
+ import platform
7
+ import re
8
+ import struct
9
+ import sys
10
+ import functools
11
+ import inspect
12
+ from tempfile import NamedTemporaryFile
13
+
14
+ import numpy as np
15
+ from numpy import testing
16
+ from numpy.testing import (
17
+ TestCase,
18
+ assert_,
19
+ assert_warns,
20
+ assert_no_warnings,
21
+ assert_equal,
22
+ assert_almost_equal,
23
+ assert_array_equal,
24
+ assert_allclose,
25
+ assert_array_almost_equal,
26
+ assert_array_almost_equal_nulp,
27
+ assert_array_less,
28
+ )
29
+
30
+ from .. import data, io
31
+ from ..data._fetchers import _fetch
32
+ from ..util import img_as_uint, img_as_float, img_as_int, img_as_ubyte
33
+ from ._warnings import expected_warnings
34
+ from ._dependency_checks import is_wasm
35
+
36
+ import pytest
37
+
38
+
39
+ skipif = pytest.mark.skipif
40
+ xfail = pytest.mark.xfail
41
+ parametrize = pytest.mark.parametrize
42
+ raises = pytest.raises
43
+ fixture = pytest.fixture
44
+
45
+ SKIP_RE = re.compile(r"(\s*>>>.*?)(\s*)#\s*skip\s+if\s+(.*)$")
46
+
47
+ # true if python is running in 32bit mode
48
+ # Calculate the size of a void * pointer in bits
49
+ # https://docs.python.org/3/library/struct.html
50
+ arch32 = struct.calcsize("P") * 8 == 32
51
+
52
+
53
+ def assert_less(a, b, msg=None):
54
+ message = f"{a!r} is not lower than {b!r}"
55
+ if msg is not None:
56
+ message += ": " + msg
57
+ assert a < b, message
58
+
59
+
60
+ def assert_greater(a, b, msg=None):
61
+ message = f"{a!r} is not greater than {b!r}"
62
+ if msg is not None:
63
+ message += ": " + msg
64
+ assert a > b, message
65
+
66
+
67
+ def doctest_skip_parser(func):
68
+ """Decorator replaces custom skip test markup in doctests
69
+
70
+ Say a function has a docstring::
71
+
72
+ >>> something, HAVE_AMODULE, HAVE_BMODULE = 0, False, False
73
+ >>> something # skip if not HAVE_AMODULE
74
+ 0
75
+ >>> something # skip if HAVE_BMODULE
76
+ 0
77
+
78
+ This decorator will evaluate the expression after ``skip if``. If this
79
+ evaluates to True, then the comment is replaced by ``# doctest: +SKIP``. If
80
+ False, then the comment is just removed. The expression is evaluated in the
81
+ ``globals`` scope of `func`.
82
+
83
+ For example, if the module global ``HAVE_AMODULE`` is False, and module
84
+ global ``HAVE_BMODULE`` is False, the returned function will have docstring::
85
+
86
+ >>> something # doctest: +SKIP
87
+ >>> something + else # doctest: +SKIP
88
+ >>> something # doctest: +SKIP
89
+
90
+ """
91
+ lines = func.__doc__.split('\n')
92
+ new_lines = []
93
+ for line in lines:
94
+ match = SKIP_RE.match(line)
95
+ if match is None:
96
+ new_lines.append(line)
97
+ continue
98
+ code, space, expr = match.groups()
99
+
100
+ try:
101
+ # Works as a function decorator
102
+ if eval(expr, func.__globals__):
103
+ code = code + space + "# doctest: +SKIP"
104
+ except AttributeError:
105
+ # Works as a class decorator
106
+ if eval(expr, func.__init__.__globals__):
107
+ code = code + space + "# doctest: +SKIP"
108
+
109
+ new_lines.append(code)
110
+ func.__doc__ = "\n".join(new_lines)
111
+ return func
112
+
113
+
114
+ def roundtrip(image, plugin, suffix):
115
+ """Save and read an image using a specified plugin"""
116
+ if '.' not in suffix:
117
+ suffix = '.' + suffix
118
+ with NamedTemporaryFile(suffix=suffix, delete=False) as temp_file:
119
+ fname = temp_file.name
120
+ io.imsave(fname, image, plugin=plugin)
121
+ new = io.imread(fname, plugin=plugin)
122
+ try:
123
+ os.remove(fname)
124
+ except Exception:
125
+ pass
126
+ return new
127
+
128
+
129
+ def color_check(plugin, fmt='png'):
130
+ """Check roundtrip behavior for color images.
131
+
132
+ All major input types should be handled as ubytes and read
133
+ back correctly.
134
+ """
135
+ img = img_as_ubyte(data.chelsea())
136
+ r1 = roundtrip(img, plugin, fmt)
137
+ testing.assert_allclose(img, r1)
138
+
139
+ img2 = img > 128
140
+ r2 = roundtrip(img2, plugin, fmt)
141
+ testing.assert_allclose(img2, r2.astype(bool))
142
+
143
+ img3 = img_as_float(img)
144
+ r3 = roundtrip(img3, plugin, fmt)
145
+ testing.assert_allclose(r3, img)
146
+
147
+ img4 = img_as_int(img)
148
+ if fmt.lower() in (('tif', 'tiff')):
149
+ img4 -= 100
150
+ r4 = roundtrip(img4, plugin, fmt)
151
+ testing.assert_allclose(r4, img4)
152
+ else:
153
+ r4 = roundtrip(img4, plugin, fmt)
154
+ testing.assert_allclose(r4, img_as_ubyte(img4))
155
+
156
+ img5 = img_as_uint(img)
157
+ r5 = roundtrip(img5, plugin, fmt)
158
+ testing.assert_allclose(r5, img)
159
+
160
+
161
+ def mono_check(plugin, fmt='png'):
162
+ """Check the roundtrip behavior for images that support most types.
163
+
164
+ All major input types should be handled.
165
+ """
166
+
167
+ img = img_as_ubyte(data.moon())
168
+ r1 = roundtrip(img, plugin, fmt)
169
+ testing.assert_allclose(img, r1)
170
+
171
+ img2 = img > 128
172
+ r2 = roundtrip(img2, plugin, fmt)
173
+ testing.assert_allclose(img2, r2.astype(bool))
174
+
175
+ img3 = img_as_float(img)
176
+ r3 = roundtrip(img3, plugin, fmt)
177
+ if r3.dtype.kind == 'f':
178
+ testing.assert_allclose(img3, r3)
179
+ else:
180
+ testing.assert_allclose(r3, img_as_uint(img))
181
+
182
+ img4 = img_as_int(img)
183
+ if fmt.lower() in (('tif', 'tiff')):
184
+ img4 -= 100
185
+ r4 = roundtrip(img4, plugin, fmt)
186
+ testing.assert_allclose(r4, img4)
187
+ else:
188
+ r4 = roundtrip(img4, plugin, fmt)
189
+ testing.assert_allclose(r4, img_as_uint(img4))
190
+
191
+ img5 = img_as_uint(img)
192
+ r5 = roundtrip(img5, plugin, fmt)
193
+ testing.assert_allclose(r5, img5)
194
+
195
+
196
+ def fetch(data_filename, prefix=None):
197
+ """Attempt to fetch data, but if unavailable, skip the tests.
198
+
199
+ Parameters
200
+ ----------
201
+ data_filename : str
202
+ File path in the scikit-image repo tree, e.g.,
203
+ 'restoration/camera_rl.npy', possibly pointing to a remote location.
204
+
205
+ prefix : str, optional
206
+ If None, `data_filename` is prefixed by 'src/skimage'
207
+ If 'tests', `data_filename` is prefixed by 'tests/skimage'.
208
+
209
+ Returns
210
+ -------
211
+ file_path : str
212
+ Path of the local file, possibly pointing to a remote location.
213
+
214
+ """
215
+ try:
216
+ return _fetch(data_filename, prefix=prefix)
217
+ except (ConnectionError, ModuleNotFoundError):
218
+ pytest.skip(f'Unable to download {data_filename}', allow_module_level=True)
219
+
220
+
221
+ # Ref: about the lack of threading support in WASM, please see
222
+ # https://github.com/pyodide/pyodide/issues/237
223
+ def run_in_parallel(workers=2, warnings_matching=None):
224
+ """Decorator to run the same function multiple times in parallel.
225
+
226
+ This decorator is useful to ensure that separate threads execute
227
+ concurrently and correctly while releasing the GIL.
228
+
229
+ It is currently skipped when running on WASM-based platforms, as
230
+ the threading module is not supported.
231
+
232
+ Parameters
233
+ ----------
234
+ workers : int, optional
235
+ The number of times the function is run in parallel.
236
+ warnings_matching : list or None
237
+ This parameter is passed on to `expected_warnings` so as not to have
238
+ race conditions with the warnings filters. A single
239
+ `expected_warnings` context manager is used for all threads.
240
+ If None, then no warnings are checked.
241
+
242
+ """
243
+
244
+ assert workers > 0
245
+
246
+ def wrapper(func):
247
+ if is_wasm:
248
+ # Threading isn't supported on WASM, return early
249
+ return func
250
+
251
+ import threading
252
+
253
+ @functools.wraps(func)
254
+ def inner(*args, **kwargs):
255
+ with expected_warnings(warnings_matching):
256
+ threads = []
257
+ for i in range(workers - 1):
258
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs)
259
+ threads.append(thread)
260
+ for thread in threads:
261
+ thread.start()
262
+
263
+ func(*args, **kwargs)
264
+
265
+ for thread in threads:
266
+ thread.join()
267
+
268
+ return inner
269
+
270
+ return wrapper
271
+
272
+
273
+ def assert_stacklevel(warnings, *, offset=-1):
274
+ """Assert correct stacklevel of captured warnings.
275
+
276
+ When scikit-image raises warnings, the stacklevel should ideally be set
277
+ so that the origin of the warnings will point to the public function
278
+ that was called by the user and not necessarily the very place where the
279
+ warnings were emitted (which may be inside some internal function).
280
+ This utility function helps with checking that
281
+ the stacklevel was set correctly on warnings captured by `pytest.warns`.
282
+
283
+ Parameters
284
+ ----------
285
+ warnings : collections.abc.Iterable[warning.WarningMessage]
286
+ Warnings that were captured by `pytest.warns`.
287
+ offset : int, optional
288
+ Offset from the line this function is called to the line were the
289
+ warning is supposed to originate from. For multiline calls, the
290
+ first line is relevant. Defaults to -1 which corresponds to the line
291
+ right above the one where this function is called.
292
+
293
+ Raises
294
+ ------
295
+ AssertionError
296
+ If a warning in `warnings` does not match the expected line number or
297
+ file name.
298
+
299
+ Examples
300
+ --------
301
+ >>> def test_something():
302
+ ... with pytest.warns(UserWarning, match="some message") as record:
303
+ ... something_raising_a_warning()
304
+ ... assert_stacklevel(record)
305
+ ...
306
+ >>> def test_another_thing():
307
+ ... with pytest.warns(UserWarning, match="some message") as record:
308
+ ... iam_raising_many_warnings(
309
+ ... "A long argument that forces the call to wrap."
310
+ ... )
311
+ ... assert_stacklevel(record, offset=-3)
312
+ """
313
+ __tracebackhide__ = True # Hide traceback for py.test
314
+
315
+ frame = inspect.stack()[1].frame # 0 is current frame, 1 is outer frame
316
+ line_number = frame.f_lineno + offset
317
+ filename = frame.f_code.co_filename
318
+ expected = f"{filename}:{line_number}"
319
+ for warning in warnings:
320
+ actual = f"{warning.filename}:{warning.lineno}"
321
+ msg = (
322
+ "Warning with wrong stacklevel:\n"
323
+ f" Expected: {expected}\n"
324
+ f" Actual: {actual}\n"
325
+ f" {warning.category.__name__}: {warning.message}"
326
+ )
327
+ assert actual == expected, msg
envs/kitoverlay/skimage/_shared/utils.py ADDED
@@ -0,0 +1,1099 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import sys
4
+ import warnings
5
+ from contextlib import contextmanager
6
+
7
+ import numpy as np
8
+
9
+ from ._warnings import all_warnings, warn
10
+
11
+ __all__ = [
12
+ 'deprecate_func',
13
+ 'get_bound_method_class',
14
+ 'all_warnings',
15
+ 'safe_as_int',
16
+ 'check_shape_equality',
17
+ 'check_nD',
18
+ 'warn',
19
+ 'reshape_nd',
20
+ 'identity',
21
+ 'slice_at_axis',
22
+ "deprecate_parameter",
23
+ "DEPRECATED",
24
+ ]
25
+
26
+
27
+ def count_inner_wrappers(func):
28
+ """Count the number of inner wrappers by unpacking ``__wrapped__``.
29
+
30
+ If a wrapped function wraps another wrapped function, then we refer to the
31
+ wrapping of the second function as an *inner wrapper*.
32
+
33
+ For example, consider this code fragment:
34
+
35
+ .. code-block:: python
36
+ @wrap_outer
37
+ @wrap_inner
38
+ def foo():
39
+ pass
40
+
41
+ Here ``@wrap_inner`` applies a wrapper to ``foo``, and ``@wrap_outer``
42
+ applies a wrapper to the result.
43
+
44
+ Parameters
45
+ ----------
46
+ func : callable
47
+ The callable of which to determine the number of inner wrappers.
48
+
49
+ Returns
50
+ -------
51
+ count : int
52
+ The number of times `func` has been wrapped.
53
+
54
+ See Also
55
+ --------
56
+ count_global_wrappers
57
+ """
58
+ unwrapped = func
59
+ count = 0
60
+ while hasattr(unwrapped, "__wrapped__"):
61
+ unwrapped = unwrapped.__wrapped__
62
+ count += 1
63
+ return count
64
+
65
+
66
+ def _warning_stacklevel(func):
67
+ """Find stacklevel of `func` relative to its global representation.
68
+
69
+ Determine automatically with which stacklevel a warning should be raised.
70
+
71
+ Parameters
72
+ ----------
73
+ func : Callable
74
+ Tries to find the global version of `func` and counts the number of
75
+ additional wrappers around `func`.
76
+
77
+ Returns
78
+ -------
79
+ stacklevel : int
80
+ The stacklevel. Minimum of 2.
81
+ """
82
+ # Count number of wrappers around `func`
83
+ inner_wrapped_count = count_inner_wrappers(func)
84
+ global_wrapped_count = count_global_wrappers(func)
85
+
86
+ stacklevel = global_wrapped_count - inner_wrapped_count + 1
87
+ return max(stacklevel, 2)
88
+
89
+
90
+ def count_global_wrappers(func):
91
+ """Count the total number of times a function as been wrapped globally.
92
+
93
+ Similar to :func:`count_inner_wrappers`, this counts the number of times
94
+ `func` has been wrapped. However, this function doesn't start counting
95
+ from `func` but instead tries to access the "global representation" of
96
+ `func`. This means that you could use this function from inside a wrapper
97
+ that was applied first, and still count wrappers that were applied on
98
+ top of it afterwards.
99
+
100
+ E.g., `func` might be wrapped by multiple decorators that emit
101
+ warnings. In that case, calling this function in the inner-most decorator
102
+ will still return the total count of wrappers.
103
+
104
+ Parameters
105
+ ----------
106
+ func : callable
107
+ The callable of which to determine the number of wrappers. Can be a
108
+ function or method of a class.
109
+
110
+ Returns
111
+ -------
112
+ count : int
113
+ The number of times `func` has been wrapped.
114
+
115
+ See Also
116
+ --------
117
+ count_inner_wrappers
118
+ """
119
+ if "<locals>" in func.__qualname__:
120
+ msg = (
121
+ "Cannot determine stacklevel of a function defined in another "
122
+ "function's local namespace. Set the stacklevel manually."
123
+ )
124
+ raise ValueError(msg)
125
+
126
+ first_name, *other = func.__qualname__.split(".")
127
+ global_func = func.__globals__.get(first_name, func)
128
+
129
+ # Account for `func` being a method, in which case it's an attribute of
130
+ # what we got from `func.__globals__`
131
+ for part in other:
132
+ global_func = getattr(global_func, part, global_func)
133
+
134
+ count = count_inner_wrappers(global_func)
135
+ assert count >= 0
136
+ return count
137
+
138
+
139
+ class change_default_value:
140
+ """Decorator for changing the default value of an argument.
141
+
142
+ Parameters
143
+ ----------
144
+ arg_name : str
145
+ The name of the argument to be updated.
146
+ new_value : any
147
+ The argument new value.
148
+ changed_version : str
149
+ The package version in which the change will be introduced.
150
+ warning_msg : str
151
+ Optional warning message. If None, a generic warning message
152
+ is used.
153
+ stacklevel : {None, int}, optional
154
+ If None, the decorator attempts to detect the appropriate stacklevel for the
155
+ deprecation warning automatically. This can fail, e.g., due to
156
+ decorating a closure, in which case you can set the stacklevel manually
157
+ here. The outermost decorator should have stacklevel 2, the next inner
158
+ one stacklevel 3, etc.
159
+ """
160
+
161
+ def __init__(
162
+ self, arg_name, *, new_value, changed_version, warning_msg=None, stacklevel=None
163
+ ):
164
+ self.arg_name = arg_name
165
+ self.new_value = new_value
166
+ self.warning_msg = warning_msg
167
+ self.changed_version = changed_version
168
+ self.stacklevel = stacklevel
169
+
170
+ def __call__(self, func):
171
+ parameters = inspect.signature(func).parameters
172
+ arg_idx = list(parameters.keys()).index(self.arg_name)
173
+ old_value = parameters[self.arg_name].default
174
+
175
+ if self.warning_msg is None:
176
+ self.warning_msg = (
177
+ f'The new recommended value for {self.arg_name} is '
178
+ f'{self.new_value}. Until version {self.changed_version}, '
179
+ f'the default {self.arg_name} value is {old_value}. '
180
+ f'From version {self.changed_version}, the {self.arg_name} '
181
+ f'default value will be {self.new_value}. To avoid '
182
+ f'this warning, please explicitly set {self.arg_name} value.'
183
+ )
184
+
185
+ @functools.wraps(func)
186
+ def fixed_func(*args, **kwargs):
187
+ if len(args) < arg_idx + 1 and self.arg_name not in kwargs.keys():
188
+ stacklevel = (
189
+ self.stacklevel
190
+ if self.stacklevel is not None
191
+ else _warning_stacklevel(func)
192
+ )
193
+ # warn that arg_name default value changed:
194
+ warnings.warn(self.warning_msg, FutureWarning, stacklevel=stacklevel)
195
+ return func(*args, **kwargs)
196
+
197
+ return fixed_func
198
+
199
+
200
+ class PatchClassRepr(type):
201
+ """Control class representations in rendered signatures."""
202
+
203
+ def __repr__(cls):
204
+ return f"<{cls.__name__}>"
205
+
206
+
207
+ class DEPRECATED(metaclass=PatchClassRepr):
208
+ """Signal value to help with deprecating parameters that use None.
209
+
210
+ This is a proxy object, used to signal that a parameter has not been set.
211
+ This is useful if ``None`` is already used for a different purpose or just
212
+ to highlight a deprecated parameter in the signature.
213
+ """
214
+
215
+
216
+ class deprecate_parameter:
217
+ """Deprecate a parameter of a function.
218
+
219
+ Parameters
220
+ ----------
221
+ deprecated_name : str
222
+ The name of the deprecated parameter.
223
+ start_version : str
224
+ The package version in which the warning was introduced.
225
+ stop_version : str
226
+ The package version in which the warning will be replaced by
227
+ an error / the deprecation is completed.
228
+ template : str, optional
229
+ If given, this message template is used instead of the default one.
230
+ new_name : str, optional
231
+ If given, the default message will recommend the new parameter name and an
232
+ error will be raised if the user uses both old and new names for the
233
+ same parameter.
234
+ modify_docstring : bool, optional
235
+ If the wrapped function has a docstring, add the deprecated parameters
236
+ to the "Other Parameters" section.
237
+ stacklevel : {None, int}, optional
238
+ If None, the decorator attempts to detect the appropriate stacklevel for the
239
+ deprecation warning automatically. This can fail, e.g., due to
240
+ decorating a closure, in which case you can set the stacklevel manually
241
+ here. The outermost decorator should have stacklevel 2, the next inner
242
+ one stacklevel 3, etc.
243
+
244
+ Notes
245
+ -----
246
+ Assign `DEPRECATED` as the new default value for the deprecated parameter.
247
+ This marks the status of the parameter also in the signature and rendered
248
+ HTML docs.
249
+
250
+ This decorator can be stacked to deprecate more than one parameter.
251
+
252
+ Examples
253
+ --------
254
+ >>> from skimage._shared.utils import deprecate_parameter, DEPRECATED
255
+ >>> @deprecate_parameter(
256
+ ... "b", new_name="c", start_version="0.1", stop_version="0.3"
257
+ ... )
258
+ ... def foo(a, b=DEPRECATED, *, c=None):
259
+ ... return a, c
260
+
261
+ Calling ``foo(1, b=2)`` will warn with::
262
+
263
+ FutureWarning: Parameter `b` is deprecated since version 0.1 and will
264
+ be removed in 0.3 (or later). To avoid this warning, please use the
265
+ parameter `c` instead. For more details, see the documentation of
266
+ `foo`.
267
+ """
268
+
269
+ DEPRECATED = DEPRECATED # Make signal value accessible for convenience
270
+
271
+ remove_parameter_template = (
272
+ "Parameter `{deprecated_name}` is deprecated since version "
273
+ "{deprecated_version} and will be removed in {changed_version} (or "
274
+ "later). To avoid this warning, please do not use the parameter "
275
+ "`{deprecated_name}`. For more details, see the documentation of "
276
+ "`{func_name}`."
277
+ )
278
+
279
+ replace_parameter_template = (
280
+ "Parameter `{deprecated_name}` is deprecated since version "
281
+ "{deprecated_version} and will be removed in {changed_version} (or "
282
+ "later). To avoid this warning, please use the parameter `{new_name}` "
283
+ "instead. For more details, see the documentation of `{func_name}`."
284
+ )
285
+
286
+ def __init__(
287
+ self,
288
+ deprecated_name,
289
+ *,
290
+ start_version,
291
+ stop_version,
292
+ template=None,
293
+ new_name=None,
294
+ modify_docstring=True,
295
+ stacklevel=None,
296
+ ):
297
+ self.deprecated_name = deprecated_name
298
+ self.new_name = new_name
299
+ self.template = template
300
+ self.start_version = start_version
301
+ self.stop_version = stop_version
302
+ self.modify_docstring = modify_docstring
303
+ self.stacklevel = stacklevel
304
+
305
+ def __call__(self, func):
306
+ parameters = inspect.signature(func).parameters
307
+ try:
308
+ deprecated_idx = list(parameters.keys()).index(self.deprecated_name)
309
+ except ValueError as e:
310
+ raise ValueError(f"{self.deprecated_name!r} not in parameters") from e
311
+
312
+ new_idx = False
313
+ if self.new_name:
314
+ try:
315
+ new_idx = list(parameters.keys()).index(self.new_name)
316
+ except ValueError as e:
317
+ raise ValueError(f"{self.new_name!r} not in parameters") from e
318
+
319
+ if parameters[self.deprecated_name].default is not DEPRECATED:
320
+ raise RuntimeError(
321
+ f"Expected `{self.deprecated_name}` to have the value {DEPRECATED!r} "
322
+ f"to indicate its status in the rendered signature."
323
+ )
324
+
325
+ if self.template is not None:
326
+ template = self.template
327
+ elif self.new_name is not None:
328
+ template = self.replace_parameter_template
329
+ else:
330
+ template = self.remove_parameter_template
331
+ warning_message = template.format(
332
+ deprecated_name=self.deprecated_name,
333
+ deprecated_version=self.start_version,
334
+ changed_version=self.stop_version,
335
+ func_name=func.__qualname__,
336
+ new_name=self.new_name,
337
+ )
338
+
339
+ @functools.wraps(func)
340
+ def fixed_func(*args, **kwargs):
341
+ deprecated_value = DEPRECATED
342
+ new_value = DEPRECATED
343
+
344
+ # Extract value of deprecated parameter
345
+ if len(args) > deprecated_idx:
346
+ deprecated_value = args[deprecated_idx]
347
+ # Overwrite old with DEPRECATED if replacement exists
348
+ if self.new_name is not None:
349
+ args = (
350
+ args[:deprecated_idx]
351
+ + (DEPRECATED,)
352
+ + args[deprecated_idx + 1 :]
353
+ )
354
+ if self.deprecated_name in kwargs.keys():
355
+ deprecated_value = kwargs[self.deprecated_name]
356
+ # Overwrite old with DEPRECATED if replacement exists
357
+ if self.new_name is not None:
358
+ kwargs[self.deprecated_name] = DEPRECATED
359
+
360
+ # Extract value of new parameter (if present)
361
+ if new_idx is not False and len(args) > new_idx:
362
+ new_value = args[new_idx]
363
+ if self.new_name and self.new_name in kwargs.keys():
364
+ new_value = kwargs[self.new_name]
365
+
366
+ if deprecated_value is not DEPRECATED:
367
+ stacklevel = (
368
+ self.stacklevel
369
+ if self.stacklevel is not None
370
+ else _warning_stacklevel(func)
371
+ )
372
+ warnings.warn(
373
+ warning_message, category=FutureWarning, stacklevel=stacklevel
374
+ )
375
+
376
+ if new_value is not DEPRECATED:
377
+ raise ValueError(
378
+ f"Both deprecated parameter `{self.deprecated_name}` "
379
+ f"and new parameter `{self.new_name}` are used. Use "
380
+ f"only the latter to avoid conflicting values."
381
+ )
382
+ elif self.new_name is not None:
383
+ # Assign old value to new one
384
+ kwargs[self.new_name] = deprecated_value
385
+
386
+ return func(*args, **kwargs)
387
+
388
+ if self.modify_docstring and func.__doc__ is not None:
389
+ newdoc = _docstring_add_deprecated(
390
+ func, {self.deprecated_name: self.new_name}, self.start_version
391
+ )
392
+ fixed_func.__doc__ = newdoc
393
+
394
+ return fixed_func
395
+
396
+
397
+ def _docstring_add_deprecated(func, kwarg_mapping, deprecated_version):
398
+ """Add deprecated kwarg(s) to the "Other Params" section of a docstring.
399
+
400
+ Parameters
401
+ ----------
402
+ func : function
403
+ The function whose docstring we wish to update.
404
+ kwarg_mapping : dict
405
+ A dict containing {old_arg: new_arg} key/value pairs, see
406
+ `deprecate_parameter`.
407
+ deprecated_version : str
408
+ A major.minor version string specifying when old_arg was
409
+ deprecated.
410
+
411
+ Returns
412
+ -------
413
+ new_doc : str
414
+ The updated docstring. Returns the original docstring if numpydoc is
415
+ not available.
416
+ """
417
+ if func.__doc__ is None:
418
+ return None
419
+ try:
420
+ from numpydoc.docscrape import FunctionDoc, Parameter
421
+ except ImportError:
422
+ # Return an unmodified docstring if numpydoc is not available.
423
+ return func.__doc__
424
+
425
+ Doc = FunctionDoc(func)
426
+ for old_arg, new_arg in kwarg_mapping.items():
427
+ desc = []
428
+ if new_arg is None:
429
+ desc.append(f'`{old_arg}` is deprecated.')
430
+ else:
431
+ desc.append(f'Deprecated in favor of `{new_arg}`.')
432
+
433
+ desc += ['', f'.. deprecated:: {deprecated_version}']
434
+ Doc['Other Parameters'].append(
435
+ Parameter(name=old_arg, type='DEPRECATED', desc=desc)
436
+ )
437
+ new_docstring = str(Doc)
438
+
439
+ # new_docstring will have a header starting with:
440
+ #
441
+ # .. function:: func.__name__
442
+ #
443
+ # and some additional blank lines. We strip these off below.
444
+ split = new_docstring.split('\n')
445
+ no_header = split[1:]
446
+ while not no_header[0].strip():
447
+ no_header.pop(0)
448
+
449
+ # Store the initial description before any of the Parameters fields.
450
+ # Usually this is a single line, but the while loop covers any case
451
+ # where it is not.
452
+ descr = no_header.pop(0)
453
+ while no_header[0].strip():
454
+ descr += '\n ' + no_header.pop(0)
455
+ descr += '\n\n'
456
+ # '\n ' rather than '\n' here to restore the original indentation.
457
+ final_docstring = descr + '\n '.join(no_header)
458
+ # strip any extra spaces from ends of lines
459
+ final_docstring = '\n'.join([line.rstrip() for line in final_docstring.split('\n')])
460
+ return final_docstring
461
+
462
+
463
+ class FailedEstimationAccessError(AttributeError):
464
+ """Error from use of failed estimation instance
465
+
466
+ This error arises from attempts to use an instance of
467
+ :class:`FailedEstimation`.
468
+ """
469
+
470
+
471
+ class FailedEstimation:
472
+ """Class to indicate a failed transform estimation.
473
+
474
+ The ``from_estimate`` class method of each transform type may return an
475
+ instance of this class to indicate some failure in the estimation process.
476
+
477
+ Parameters
478
+ ----------
479
+ message : str
480
+ Message indicating reason for failed estimation.
481
+
482
+ Attributes
483
+ ----------
484
+ message : str
485
+ Message above.
486
+
487
+ Raises
488
+ ------
489
+ FailedEstimationAccessError
490
+ Exception raised for missing attributes or if the instance is used as a
491
+ callable.
492
+ """
493
+
494
+ error_cls = FailedEstimationAccessError
495
+
496
+ hint = (
497
+ "You can check for a failed estimation by truth testing the returned "
498
+ "object. For failed estimations, `bool(estimation_result)` will be `False`. "
499
+ "E.g.\n\n"
500
+ " if not estimation_result:\n"
501
+ " raise RuntimeError(f'Failed estimation: {estimation_result}')"
502
+ )
503
+
504
+ def __init__(self, message):
505
+ self.message = message
506
+
507
+ def __bool__(self):
508
+ return False
509
+
510
+ def __repr__(self):
511
+ return f"{type(self).__name__}({self.message!r})"
512
+
513
+ def __str__(self):
514
+ return self.message
515
+
516
+ def __call__(self, *args, **kwargs):
517
+ msg = (
518
+ f'{type(self).__name__} is not callable. {self.message}\n\n'
519
+ f'Hint: {self.hint}'
520
+ )
521
+ raise self.error_cls(msg)
522
+
523
+ def __getattr__(self, name):
524
+ msg = (
525
+ f'{type(self).__name__} has no attribute {name!r}. {self.message}\n\n'
526
+ f'Hint: {self.hint}'
527
+ )
528
+ raise self.error_cls(msg)
529
+
530
+
531
+ @contextmanager
532
+ def _ignore_deprecated_estimate_warning():
533
+ """Filter warnings about the deprecated `estimate` method.
534
+
535
+ Use either as decorator or context manager.
536
+ """
537
+ with warnings.catch_warnings():
538
+ warnings.filterwarnings(
539
+ action="ignore",
540
+ category=FutureWarning,
541
+ message="`estimate` is deprecated",
542
+ module="skimage",
543
+ )
544
+ yield
545
+
546
+
547
+ class channel_as_last_axis:
548
+ """Decorator for automatically making channels axis last for all arrays.
549
+
550
+ This decorator reorders axes for compatibility with functions that only
551
+ support channels along the last axis. After the function call is complete
552
+ the channels axis is restored back to its original position.
553
+
554
+ Parameters
555
+ ----------
556
+ channel_arg_positions : tuple of int, optional
557
+ Positional arguments at the positions specified in this tuple are
558
+ assumed to be multichannel arrays. The default is to assume only the
559
+ first argument to the function is a multichannel array.
560
+ channel_kwarg_names : tuple of str, optional
561
+ A tuple containing the names of any keyword arguments corresponding to
562
+ multichannel arrays.
563
+ multichannel_output : bool, optional
564
+ A boolean that should be True if the output of the function is not a
565
+ multichannel array and False otherwise. This decorator does not
566
+ currently support the general case of functions with multiple outputs
567
+ where some or all are multichannel.
568
+
569
+ """
570
+
571
+ def __init__(
572
+ self,
573
+ channel_arg_positions=(0,),
574
+ channel_kwarg_names=(),
575
+ multichannel_output=True,
576
+ ):
577
+ self.arg_positions = set(channel_arg_positions)
578
+ self.kwarg_names = set(channel_kwarg_names)
579
+ self.multichannel_output = multichannel_output
580
+
581
+ def __call__(self, func):
582
+ @functools.wraps(func)
583
+ def fixed_func(*args, **kwargs):
584
+ channel_axis = kwargs.get('channel_axis', None)
585
+
586
+ if channel_axis is None:
587
+ return func(*args, **kwargs)
588
+
589
+ # TODO: convert scalars to a tuple in anticipation of eventually
590
+ # supporting a tuple of channel axes. Right now, only an
591
+ # integer or a single-element tuple is supported, though.
592
+ if np.isscalar(channel_axis):
593
+ channel_axis = (channel_axis,)
594
+ if len(channel_axis) > 1:
595
+ raise ValueError("only a single channel axis is currently supported")
596
+
597
+ if channel_axis == (-1,) or channel_axis == -1:
598
+ return func(*args, **kwargs)
599
+
600
+ if self.arg_positions:
601
+ new_args = []
602
+ for pos, arg in enumerate(args):
603
+ if pos in self.arg_positions:
604
+ new_args.append(np.moveaxis(arg, channel_axis[0], -1))
605
+ else:
606
+ new_args.append(arg)
607
+ new_args = tuple(new_args)
608
+ else:
609
+ new_args = args
610
+
611
+ for name in self.kwarg_names:
612
+ kwargs[name] = np.moveaxis(kwargs[name], channel_axis[0], -1)
613
+
614
+ # now that we have moved the channels axis to the last position,
615
+ # change the channel_axis argument to -1
616
+ kwargs["channel_axis"] = -1
617
+
618
+ # Call the function with the fixed arguments
619
+ out = func(*new_args, **kwargs)
620
+ if self.multichannel_output:
621
+ out = np.moveaxis(out, -1, channel_axis[0])
622
+ return out
623
+
624
+ return fixed_func
625
+
626
+
627
+ class deprecate_func:
628
+ """Decorate a deprecated function and warn when it is called.
629
+
630
+ Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
631
+
632
+ Parameters
633
+ ----------
634
+ deprecated_version : str
635
+ The package version when the deprecation was introduced.
636
+ removed_version : str
637
+ The package version in which the deprecated function will be removed.
638
+ hint : str, optional
639
+ A hint on how to address this deprecation,
640
+ e.g., "Use `skimage.submodule.alternative_func` instead."
641
+ stacklevel : {None, int}, optional
642
+ If None, the decorator attempts to detect the appropriate stacklevel for the
643
+ deprecation warning automatically. This can fail, e.g., due to
644
+ decorating a closure, in which case you can set the stacklevel manually
645
+ here. The outermost decorator should have stacklevel 2, the next inner
646
+ one stacklevel 3, etc.
647
+
648
+ Examples
649
+ --------
650
+ >>> @deprecate_func(
651
+ ... deprecated_version="1.0.0",
652
+ ... removed_version="1.2.0",
653
+ ... hint="Use `bar` instead."
654
+ ... )
655
+ ... def foo():
656
+ ... pass
657
+
658
+ Calling ``foo`` will warn with::
659
+
660
+ FutureWarning: `foo` is deprecated since version 1.0.0
661
+ and will be removed in version 1.2.0. Use `bar` instead.
662
+ """
663
+
664
+ def __init__(
665
+ self, *, deprecated_version, removed_version=None, hint=None, stacklevel=None
666
+ ):
667
+ self.deprecated_version = deprecated_version
668
+ self.removed_version = removed_version
669
+ self.hint = hint
670
+ self.stacklevel = stacklevel
671
+
672
+ def __call__(self, func):
673
+ message = (
674
+ f"`{func.__name__}` is deprecated since version {self.deprecated_version}"
675
+ )
676
+ if self.removed_version:
677
+ message += f" and will be removed in version {self.removed_version}."
678
+ if self.hint:
679
+ # Prepend space and make sure it closes with "."
680
+ message += f" {self.hint.rstrip('.')}."
681
+
682
+ @functools.wraps(func)
683
+ def wrapped(*args, **kwargs):
684
+ stacklevel = (
685
+ self.stacklevel
686
+ if self.stacklevel is not None
687
+ else _warning_stacklevel(func)
688
+ )
689
+ warnings.warn(message, category=FutureWarning, stacklevel=stacklevel)
690
+ return func(*args, **kwargs)
691
+
692
+ # modify docstring to display deprecation warning
693
+ doc = f'**Deprecated:** {message}'
694
+ if wrapped.__doc__ is None:
695
+ wrapped.__doc__ = doc
696
+ else:
697
+ wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__
698
+
699
+ return wrapped
700
+
701
+
702
+ def _deprecate_estimate(func, class_name=None):
703
+ """Deprecate ``estimate`` method."""
704
+ class_name = func.__qualname__.split('.')[0] if class_name is None else class_name
705
+ return deprecate_func(
706
+ deprecated_version="0.26",
707
+ removed_version="2.2",
708
+ hint=f"Please use `{class_name}.from_estimate` class constructor instead.",
709
+ stacklevel=2,
710
+ )(func)
711
+
712
+
713
+ def _deprecate_inherited_estimate(cls):
714
+ """Deprecate inherited ``estimate`` instance method.
715
+
716
+ This needs a class decorator so we can correctly specify the class of the
717
+ `from_estimate` class method in the deprecation message.
718
+ """
719
+
720
+ def estimate(self, *args, **kwargs):
721
+ return self._estimate(*args, **kwargs) is None
722
+
723
+ # The inherited method will always be wrapped by deprecator.
724
+ inherited_meth = getattr(cls, 'estimate').__wrapped__
725
+ estimate.__doc__ = inherited_meth.__doc__
726
+ estimate.__signature__ = inspect.signature(inherited_meth)
727
+
728
+ cls.estimate = _deprecate_estimate(estimate, cls.__name__)
729
+ return cls
730
+
731
+
732
+ def _update_from_estimate_docstring(cls):
733
+ """Fix docstring for inherited ``from_estimate`` class method.
734
+
735
+ Even for classes that inherit the `from_estimate` method, and do not
736
+ override it, we nevertheless need to change the *docstring* of the
737
+ `from_estimate` method to point the user to the current (inheriting) class,
738
+ rather than the class in which the method is defined (the inherited class).
739
+
740
+ This needs a class decorator so we can modify the docstring of the new
741
+ class method. CPython currently does not allow us to modify class method
742
+ docstrings by updating ``__doc__``.
743
+ """
744
+
745
+ inherited_cmeth = getattr(cls, 'from_estimate')
746
+
747
+ def from_estimate(cls, *args, **kwargs):
748
+ return inherited_cmeth(*args, **kwargs)
749
+
750
+ inherited_class_name = inherited_cmeth.__qualname__.split('.')[-2]
751
+
752
+ from_estimate.__doc__ = inherited_cmeth.__doc__.replace(
753
+ inherited_class_name, cls.__name__
754
+ )
755
+ from_estimate.__signature__ = inspect.signature(inherited_cmeth)
756
+
757
+ cls.from_estimate = classmethod(from_estimate)
758
+ return cls
759
+
760
+
761
+ def get_bound_method_class(m):
762
+ """Return the class for a bound method."""
763
+ return m.im_class if sys.version < '3' else m.__self__.__class__
764
+
765
+
766
+ def safe_as_int(val, atol=1e-3):
767
+ """
768
+ Attempt to safely cast values to integer format.
769
+
770
+ Parameters
771
+ ----------
772
+ val : scalar or iterable of scalars
773
+ Number or container of numbers which are intended to be interpreted as
774
+ integers, e.g., for indexing purposes, but which may not carry integer
775
+ type.
776
+ atol : float
777
+ Absolute tolerance away from nearest integer to consider values in
778
+ ``val`` functionally integers.
779
+
780
+ Returns
781
+ -------
782
+ val_int : NumPy scalar or ndarray of dtype `np.int64`
783
+ Returns the input value(s) coerced to dtype `np.int64` assuming all
784
+ were within ``atol`` of the nearest integer.
785
+
786
+ Notes
787
+ -----
788
+ This operation calculates ``val`` modulo 1, which returns the mantissa of
789
+ all values. Then all mantissas greater than 0.5 are subtracted from one.
790
+ Finally, the absolute tolerance from zero is calculated. If it is less
791
+ than ``atol`` for all value(s) in ``val``, they are rounded and returned
792
+ in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is
793
+ returned.
794
+
795
+ If any value(s) are outside the specified tolerance, an informative error
796
+ is raised.
797
+
798
+ Examples
799
+ --------
800
+ >>> safe_as_int(7.0)
801
+ 7
802
+
803
+ >>> safe_as_int([9, 4, 2.9999999999])
804
+ array([9, 4, 3])
805
+
806
+ >>> safe_as_int(53.1)
807
+ Traceback (most recent call last):
808
+ ...
809
+ ValueError: Integer argument required but received 53.1, check inputs.
810
+
811
+ >>> safe_as_int(53.01, atol=0.01)
812
+ 53
813
+
814
+ """
815
+ mod = np.asarray(val) % 1 # Extract mantissa
816
+
817
+ # Check for and subtract any mod values > 0.5 from 1
818
+ if mod.ndim == 0: # Scalar input, cannot be indexed
819
+ if mod > 0.5:
820
+ mod = 1 - mod
821
+ else: # Iterable input, now ndarray
822
+ mod[mod > 0.5] = 1 - mod[mod > 0.5] # Test on each side of nearest int
823
+
824
+ if not np.allclose(mod, 0, atol=atol):
825
+ raise ValueError(f'Integer argument required but received {val}, check inputs.')
826
+
827
+ return np.round(val).astype(np.int64)
828
+
829
+
830
+ def check_shape_equality(*images):
831
+ """Check that all images have the same shape"""
832
+ image0 = images[0]
833
+ if not all(image0.shape == image.shape for image in images[1:]):
834
+ raise ValueError('Input images must have the same dimensions.')
835
+ return
836
+
837
+
838
+ def slice_at_axis(sl, axis):
839
+ """
840
+ Construct tuple of slices to slice an array in the given dimension.
841
+
842
+ Parameters
843
+ ----------
844
+ sl : slice
845
+ The slice for the given dimension.
846
+ axis : int
847
+ The axis to which `sl` is applied. All other dimensions are left
848
+ "unsliced".
849
+
850
+ Returns
851
+ -------
852
+ sl : tuple of slices
853
+ A tuple with slices matching `shape` in length.
854
+
855
+ Examples
856
+ --------
857
+ >>> slice_at_axis(slice(None, 3, -1), 1)
858
+ (slice(None, None, None), slice(None, 3, -1), Ellipsis)
859
+ """
860
+ return (slice(None),) * axis + (sl,) + (...,)
861
+
862
+
863
+ def reshape_nd(arr, ndim, dim):
864
+ """Reshape a 1D array to have n dimensions, all singletons but one.
865
+
866
+ Parameters
867
+ ----------
868
+ arr : array, shape (N,)
869
+ Input array
870
+ ndim : int
871
+ Number of desired dimensions of reshaped array.
872
+ dim : int
873
+ Which dimension/axis will not be singleton-sized.
874
+
875
+ Returns
876
+ -------
877
+ arr_reshaped : array, shape ([1, ...], N, [1,...])
878
+ View of `arr` reshaped to the desired shape.
879
+
880
+ Examples
881
+ --------
882
+ >>> rng = np.random.default_rng()
883
+ >>> arr = rng.random(7)
884
+ >>> reshape_nd(arr, 2, 0).shape
885
+ (7, 1)
886
+ >>> reshape_nd(arr, 3, 1).shape
887
+ (1, 7, 1)
888
+ >>> reshape_nd(arr, 4, -1).shape
889
+ (1, 1, 1, 7)
890
+ """
891
+ if arr.ndim != 1:
892
+ raise ValueError("arr must be a 1D array")
893
+ new_shape = [1] * ndim
894
+ new_shape[dim] = -1
895
+ return np.reshape(arr, new_shape)
896
+
897
+
898
+ def check_nD(array, ndim, arg_name='image'):
899
+ """
900
+ Verify an array meets the desired ndims and array isn't empty.
901
+
902
+ Parameters
903
+ ----------
904
+ array : array-like
905
+ Input array to be validated
906
+ ndim : int or iterable of ints
907
+ Allowable ndim or ndims for the array.
908
+ arg_name : str, optional
909
+ The name of the array in the original function.
910
+
911
+ """
912
+ array = np.asanyarray(array)
913
+ msg_incorrect_dim = "The parameter `%s` must be a %s-dimensional array"
914
+ msg_empty_array = "The parameter `%s` cannot be an empty array"
915
+ if isinstance(ndim, int):
916
+ ndim = [ndim]
917
+ if array.size == 0:
918
+ raise ValueError(msg_empty_array % (arg_name))
919
+ if array.ndim not in ndim:
920
+ raise ValueError(
921
+ msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim]))
922
+ )
923
+
924
+
925
+ def convert_to_float(image, preserve_range):
926
+ """Convert input image to float image with the appropriate range.
927
+
928
+ Parameters
929
+ ----------
930
+ image : ndarray
931
+ Input image.
932
+ preserve_range : bool
933
+ Determines if the range of the image should be kept or transformed
934
+ using img_as_float. Also see
935
+ https://scikit-image.org/docs/dev/user_guide/data_types.html
936
+
937
+ Notes
938
+ -----
939
+ * Input images with `float32` data type are not upcast.
940
+
941
+ Returns
942
+ -------
943
+ image : ndarray
944
+ Transformed version of the input.
945
+
946
+ """
947
+ if image.dtype == np.float16:
948
+ return image.astype(np.float32)
949
+ if preserve_range:
950
+ # Convert image to double only if it is not single or double
951
+ # precision float
952
+ if image.dtype.char not in 'df':
953
+ image = image.astype(float)
954
+ else:
955
+ from ..util.dtype import img_as_float
956
+
957
+ image = img_as_float(image)
958
+ return image
959
+
960
+
961
+ def _validate_interpolation_order(image_dtype, order):
962
+ """Validate and return spline interpolation's order.
963
+
964
+ Parameters
965
+ ----------
966
+ image_dtype : dtype
967
+ Image dtype.
968
+ order : {None, int}, optional
969
+ The order of the spline interpolation. The order has to be in the range
970
+ 0-5. If ``None`` assume order 0 for Boolean images, otherwise 1. See
971
+ `skimage.transform.warp` for detail.
972
+
973
+ Returns
974
+ -------
975
+ order : int
976
+ if input order is None, returns 0 if image_dtype is bool and 1
977
+ otherwise. Otherwise, image_dtype is checked and input order
978
+ is validated accordingly (order > 0 is not supported for bool
979
+ image dtype)
980
+
981
+ """
982
+
983
+ if order is None:
984
+ return 0 if image_dtype == bool else 1
985
+
986
+ if order < 0 or order > 5:
987
+ raise ValueError("Spline interpolation order has to be in the range 0-5.")
988
+
989
+ if image_dtype == bool and order != 0:
990
+ raise ValueError(
991
+ "Input image dtype is bool. Interpolation is not defined "
992
+ "with bool data type. Please set order to 0 or explicitly "
993
+ "cast input image to another data type."
994
+ )
995
+
996
+ return order
997
+
998
+
999
+ def _to_np_mode(mode):
1000
+ """Convert padding modes from `ndi.correlate` to `np.pad`."""
1001
+ mode_translation_dict = dict(nearest='edge', reflect='symmetric', mirror='reflect')
1002
+ if mode in mode_translation_dict:
1003
+ mode = mode_translation_dict[mode]
1004
+ return mode
1005
+
1006
+
1007
+ def _to_ndimage_mode(mode):
1008
+ """Convert from `numpy.pad` mode name to the corresponding ndimage mode."""
1009
+ mode_translation_dict = dict(
1010
+ constant='constant',
1011
+ edge='nearest',
1012
+ symmetric='reflect',
1013
+ reflect='mirror',
1014
+ wrap='wrap',
1015
+ )
1016
+ if mode not in mode_translation_dict:
1017
+ raise ValueError(
1018
+ f"Unknown mode: '{mode}', or cannot translate mode. The "
1019
+ f"mode should be one of 'constant', 'edge', 'symmetric', "
1020
+ f"'reflect', or 'wrap'. See the documentation of numpy.pad for "
1021
+ f"more info."
1022
+ )
1023
+ return _fix_ndimage_mode(mode_translation_dict[mode])
1024
+
1025
+
1026
+ def _fix_ndimage_mode(mode):
1027
+ # SciPy 1.6.0 introduced grid variants of constant and wrap which
1028
+ # have less surprising behavior for images. Use these when available
1029
+ grid_modes = {'constant': 'grid-constant', 'wrap': 'grid-wrap'}
1030
+ return grid_modes.get(mode, mode)
1031
+
1032
+
1033
+ new_float_type = {
1034
+ # preserved types
1035
+ np.float32().dtype.char: np.float32,
1036
+ np.float64().dtype.char: np.float64,
1037
+ np.complex64().dtype.char: np.complex64,
1038
+ np.complex128().dtype.char: np.complex128,
1039
+ # altered types
1040
+ np.float16().dtype.char: np.float32,
1041
+ 'g': np.float64, # np.float128 ; doesn't exist on windows
1042
+ 'G': np.complex128, # np.complex256 ; doesn't exist on windows
1043
+ }
1044
+
1045
+
1046
+ def _supported_float_type(input_dtype, allow_complex=False):
1047
+ """Return an appropriate floating-point dtype for a given dtype.
1048
+
1049
+ float32, float64, complex64, complex128 are preserved.
1050
+ float16 is promoted to float32.
1051
+ complex256 is demoted to complex128.
1052
+ Other types are cast to float64.
1053
+
1054
+ Parameters
1055
+ ----------
1056
+ input_dtype : np.dtype or tuple of np.dtype
1057
+ The input dtype. If a tuple of multiple dtypes is provided, each
1058
+ dtype is first converted to a supported floating point type and the
1059
+ final dtype is then determined by applying `np.result_type` on the
1060
+ sequence of supported floating point types.
1061
+ allow_complex : bool, optional
1062
+ If False, raise a ValueError on complex-valued inputs.
1063
+
1064
+ Returns
1065
+ -------
1066
+ float_type : dtype
1067
+ Floating-point dtype for the image.
1068
+ """
1069
+ if isinstance(input_dtype, tuple):
1070
+ return np.result_type(*(_supported_float_type(d) for d in input_dtype))
1071
+ input_dtype = np.dtype(input_dtype)
1072
+ if not allow_complex and input_dtype.kind == 'c':
1073
+ raise ValueError("complex valued input is not supported")
1074
+ return new_float_type.get(input_dtype.char, np.float64)
1075
+
1076
+
1077
+ def identity(image, *args, **kwargs):
1078
+ """Returns the first argument unmodified."""
1079
+ return image
1080
+
1081
+
1082
+ def as_binary_ndarray(array, *, variable_name):
1083
+ """Return `array` as a numpy.ndarray of dtype bool.
1084
+
1085
+ Raises
1086
+ ------
1087
+ ValueError:
1088
+ An error including the given `variable_name` if `array` can not be
1089
+ safely cast to a boolean array.
1090
+ """
1091
+ array = np.asarray(array)
1092
+ if array.dtype != bool:
1093
+ if np.any((array != 1) & (array != 0)):
1094
+ raise ValueError(
1095
+ f"{variable_name} array is not of dtype boolean or "
1096
+ f"contains values other than 0 and 1 so cannot be "
1097
+ f"safely cast to boolean array."
1098
+ )
1099
+ return np.asarray(array, dtype=bool)
envs/kitoverlay/skimage/feature/__pycache__/_daisy.cpython-311.pyc ADDED
Binary file (13.1 kB). View file
 
envs/kitoverlay/skimage/feature/__pycache__/brief.cpython-311.pyc ADDED
Binary file (9.5 kB). View file
 
envs/kitoverlay/skimage/feature/__pycache__/template.cpython-311.pyc ADDED
Binary file (8.35 kB). View file
 
envs/kitoverlay/skimage/graph/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Graph-based operations, e.g., shortest paths.
3
+
4
+ This includes creating adjacency graphs of pixels in an image, finding the
5
+ central pixel in an image, finding (minimum-cost) paths across pixels, merging
6
+ and cutting of graphs, etc.
7
+
8
+ """
9
+
10
+ import lazy_loader as _lazy
11
+
12
+ __getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__)
envs/kitoverlay/skimage/graph/__init__.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Explicitly setting `__all__` is necessary for type inference engines
2
+ # to know which symbols are exported. See
3
+ # https://peps.python.org/pep-0484/#stub-files
4
+
5
+ __all__ = [
6
+ 'pixel_graph',
7
+ 'central_pixel',
8
+ 'shortest_path',
9
+ 'MCP',
10
+ 'MCP_Geometric',
11
+ 'MCP_Connect',
12
+ 'MCP_Flexible',
13
+ 'route_through_array',
14
+ 'rag_mean_color',
15
+ 'rag_boundary',
16
+ 'cut_threshold',
17
+ 'cut_normalized',
18
+ 'merge_hierarchical',
19
+ 'RAG',
20
+ ]
21
+
22
+ from ._graph import pixel_graph, central_pixel
23
+ from ._graph_cut import cut_threshold, cut_normalized
24
+ from ._graph_merge import merge_hierarchical
25
+ from ._rag import rag_mean_color, RAG, show_rag, rag_boundary
26
+ from .spath import shortest_path
27
+ from .mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible, route_through_array
envs/kitoverlay/skimage/graph/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (597 Bytes). View file
 
envs/kitoverlay/skimage/graph/__pycache__/_graph.cpython-311.pyc ADDED
Binary file (9.18 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/_graph_cut.cpython-311.pyc ADDED
Binary file (11.7 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/_graph_merge.cpython-311.pyc ADDED
Binary file (5.44 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/_ncut.cpython-311.pyc ADDED
Binary file (2.58 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/_rag.cpython-311.pyc ADDED
Binary file (25.6 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/mcp.cpython-311.pyc ADDED
Binary file (3.65 kB). View file
 
envs/kitoverlay/skimage/graph/__pycache__/spath.cpython-311.pyc ADDED
Binary file (4.1 kB). View file
 
envs/kitoverlay/skimage/graph/_graph.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy import sparse
3
+ from scipy.sparse import csgraph
4
+ from ..morphology._util import _raveled_offsets_and_distances
5
+ from ..util._map_array import map_array
6
+ from ..segmentation.random_walker_segmentation import _safe_downcast_indices
7
+
8
+
9
+ def _weighted_abs_diff(values0, values1, distances):
10
+ """A default edge function for complete image graphs.
11
+
12
+ A pixel graph on an image with no edge values and no mask is a very
13
+ boring regular lattice, so we define a default edge weight to be the
14
+ absolute difference between values *weighted* by the distance
15
+ between them.
16
+
17
+ Parameters
18
+ ----------
19
+ values0 : array
20
+ The pixel values for each node.
21
+ values1 : array
22
+ The pixel values for each neighbor.
23
+ distances : array
24
+ The distance between each node and its neighbor.
25
+
26
+ Returns
27
+ -------
28
+ edge_values : array of float
29
+ The computed values: abs(values0 - values1) * distances.
30
+ """
31
+ return np.abs(values0 - values1) * distances
32
+
33
+
34
+ def pixel_graph(
35
+ image,
36
+ *,
37
+ mask=None,
38
+ edge_function=None,
39
+ connectivity=1,
40
+ spacing=None,
41
+ sparse_type="matrix",
42
+ ):
43
+ """Create an adjacency graph of pixels in an image.
44
+
45
+ Pixels where the mask is True are nodes in the returned graph, and they are
46
+ connected by edges to their neighbors according to the connectivity
47
+ parameter. By default, the *value* of an edge when a mask is given, or when
48
+ the image is itself the mask, is the Euclidean distance between the pixels.
49
+
50
+ However, if an int- or float-valued image is given with no mask, the value
51
+ of the edges is the absolute difference in intensity between adjacent
52
+ pixels, weighted by the Euclidean distance.
53
+
54
+ Parameters
55
+ ----------
56
+ image : array
57
+ The input image. If the image is of type bool, it will be used as the
58
+ mask as well.
59
+ mask : array of bool
60
+ Which pixels to use. If None, the graph for the whole image is used.
61
+ edge_function : callable
62
+ A function taking an array of pixel values, and an array of neighbor
63
+ pixel values, and an array of distances, and returning a value for the
64
+ edge. If no function is given, the value of an edge is just the
65
+ distance.
66
+ connectivity : int
67
+ The square connectivity of the pixel neighborhood: the number of
68
+ orthogonal steps allowed to consider a pixel a neighbor. See
69
+ `scipy.ndimage.generate_binary_structure` for details.
70
+ spacing : tuple of float
71
+ The spacing between pixels along each axis.
72
+ sparse_type : {"matrix", "array"}, optional
73
+ The return type of `graph`, either `scipy.sparse.csr_array` or
74
+ `scipy.sparse.csr_matrix` (default).
75
+
76
+ Returns
77
+ -------
78
+ graph : scipy.sparse.csr_matrix or scipy.sparse.csr_array
79
+ A sparse adjacency matrix in which entry (i, j) is 1 if nodes i and j
80
+ are neighbors, 0 otherwise. Depending on `sparse_type`, this can be
81
+ returned as a `scipy.sparse.csr_array`.
82
+ nodes : array of int
83
+ The nodes of the graph. These correspond to the raveled indices of the
84
+ nonzero pixels in the mask.
85
+ """
86
+ if mask is None:
87
+ if image.dtype == bool:
88
+ mask = image
89
+ else:
90
+ mask = np.ones_like(image, dtype=bool)
91
+
92
+ if edge_function is None:
93
+ if image.dtype == bool:
94
+
95
+ def edge_function(x, y, distances):
96
+ return distances
97
+
98
+ else:
99
+ edge_function = _weighted_abs_diff
100
+
101
+ # Strategy: we are going to build the (i, j, data) arrays of a scipy
102
+ # sparse CSR matrix.
103
+ # - grab the raveled IDs of the foreground (mask == True) parts of the
104
+ # image **in the padded space**.
105
+ # - broadcast them together with the raveled offsets to their neighbors.
106
+ # This gives us for each foreground pixel a list of neighbors (that
107
+ # may or may not be selected by the mask). (We also track the *distance*
108
+ # to each neighbor.)
109
+ # - select "valid" entries in the neighbors and distance arrays by indexing
110
+ # into the mask, which we can do since these are raveled indices.
111
+ # - use np.repeat() to repeat each source index according to the number
112
+ # of neighbors selected by the mask it has. Each of these repeated
113
+ # indices will be lined up with its neighbor, i.e. **this is the row_ind
114
+ # array** of the CSR format matrix.
115
+ # - use the mask as a boolean index to get a 1D view of the selected
116
+ # neighbors. **This is the col_ind array.**
117
+ # - by default, the same boolean indexing can be applied to the distances
118
+ # to each neighbor, to give the **data array.** Optionally, a
119
+ # provided edge function can be computed on the pixel values and the
120
+ # distances to give a different value for the edges.
121
+ # Note, we use map_array to map the raveled coordinates in the padded
122
+ # image to the ones in the original image, and those are the returned
123
+ # nodes.
124
+ padded = np.pad(mask, 1, mode='constant', constant_values=False)
125
+ nodes_padded = np.flatnonzero(padded)
126
+ neighbor_offsets_padded, distances_padded = _raveled_offsets_and_distances(
127
+ padded.shape, connectivity=connectivity, spacing=spacing
128
+ )
129
+ neighbors_padded = nodes_padded[:, np.newaxis] + neighbor_offsets_padded
130
+ neighbor_distances_full = np.broadcast_to(distances_padded, neighbors_padded.shape)
131
+ nodes = np.flatnonzero(mask)
132
+ nodes_sequential = np.arange(nodes.size)
133
+ # neighbors outside the mask get mapped to 0, which is a valid index,
134
+ # BUT, they will be masked out in the next step.
135
+ neighbors = map_array(neighbors_padded, nodes_padded, nodes)
136
+ neighbors_mask = padded.reshape(-1)[neighbors_padded]
137
+ num_neighbors = np.sum(neighbors_mask, axis=1)
138
+ indices = np.repeat(nodes, num_neighbors)
139
+ indices_sequential = np.repeat(nodes_sequential, num_neighbors)
140
+ neighbor_indices = neighbors[neighbors_mask]
141
+ neighbor_distances = neighbor_distances_full[neighbors_mask]
142
+ neighbor_indices_sequential = map_array(neighbor_indices, nodes, nodes_sequential)
143
+
144
+ image_r = image.reshape(-1)
145
+ data = edge_function(
146
+ image_r[indices], image_r[neighbor_indices], neighbor_distances
147
+ )
148
+
149
+ m = nodes_sequential.size
150
+ graph = sparse.csr_array(
151
+ (data, (indices_sequential, neighbor_indices_sequential)), shape=(m, m)
152
+ )
153
+
154
+ if sparse_type == "matrix":
155
+ graph = sparse.csr_matrix(graph)
156
+ elif sparse_type != "array":
157
+ msg = f"`sparse_type` must be 'array' or 'matrix', got {sparse_type}"
158
+ raise ValueError(msg)
159
+
160
+ return graph, nodes
161
+
162
+
163
+ def central_pixel(graph, nodes=None, shape=None, partition_size=100):
164
+ """Find the pixel with the highest closeness centrality.
165
+
166
+ Closeness centrality is the inverse of the total sum of shortest distances
167
+ from a node to every other node.
168
+
169
+ Parameters
170
+ ----------
171
+ graph : scipy.sparse.csr_array or scipy.sparse.csr_matrix
172
+ The sparse representation of the graph.
173
+ nodes : array of int
174
+ The raveled index of each node in graph in the image. If not provided,
175
+ the returned value will be the index in the input graph.
176
+ shape : tuple of int
177
+ The shape of the image in which the nodes are embedded. If provided,
178
+ the returned coordinates are a NumPy multi-index of the same
179
+ dimensionality as the input shape. Otherwise, the returned coordinate
180
+ is the raveled index provided in `nodes`.
181
+ partition_size : int
182
+ This function computes the shortest path distance between every pair
183
+ of nodes in the graph. This can result in a very large (N*N) matrix.
184
+ As a simple performance tweak, the distance values are computed in
185
+ lots of `partition_size`, resulting in a memory requirement of only
186
+ partition_size*N.
187
+
188
+ Returns
189
+ -------
190
+ position : int or tuple of int
191
+ If shape is given, the coordinate of the central pixel in the image.
192
+ Otherwise, the raveled index of that pixel.
193
+ distances : array of float
194
+ The total sum of distances from each node to each other reachable
195
+ node.
196
+ """
197
+ if nodes is None:
198
+ nodes = np.arange(graph.shape[0])
199
+ if partition_size is None:
200
+ num_splits = 1
201
+ else:
202
+ num_splits = max(2, graph.shape[0] // partition_size)
203
+ graph.indices, graph.indptr = _safe_downcast_indices(
204
+ graph, np.int32, 'index values too large for csgraph'
205
+ )
206
+ idxs = np.arange(graph.shape[0])
207
+ total_shortest_path_len_list = []
208
+ for partition in np.array_split(idxs, num_splits):
209
+ shortest_paths = csgraph.shortest_path(graph, directed=False, indices=partition)
210
+ shortest_paths_no_inf = np.nan_to_num(shortest_paths)
211
+ total_shortest_path_len_list.append(np.sum(shortest_paths_no_inf, axis=1))
212
+ total_shortest_path_len = np.concatenate(total_shortest_path_len_list)
213
+ nonzero = np.flatnonzero(total_shortest_path_len)
214
+ min_sp = np.argmin(total_shortest_path_len[nonzero])
215
+ raveled_index = nodes[nonzero[min_sp]]
216
+ if shape is not None:
217
+ central = np.unravel_index(raveled_index, shape)
218
+ else:
219
+ central = raveled_index
220
+ return central, total_shortest_path_len
envs/kitoverlay/skimage/graph/_graph_cut.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import numpy as np
3
+ from scipy.sparse import linalg
4
+
5
+ from skimage._shared.compat import SCIPY_GE_1_17_0_DEV0
6
+ from . import _ncut, _ncut_cy
7
+
8
+
9
+ def cut_threshold(labels, rag, thresh, in_place=True):
10
+ """Combine regions separated by weight less than threshold.
11
+
12
+ Given an image's labels and its RAG, output new labels by
13
+ combining regions whose nodes are separated by a weight less
14
+ than the given threshold.
15
+
16
+ Parameters
17
+ ----------
18
+ labels : ndarray
19
+ The array of labels.
20
+ rag : RAG
21
+ The region adjacency graph.
22
+ thresh : float
23
+ The threshold. Regions connected by edges with smaller weights are
24
+ combined.
25
+ in_place : bool
26
+ If set, modifies `rag` in place. The function will remove the edges
27
+ with weights less that `thresh`. If set to `False` the function
28
+ makes a copy of `rag` before proceeding.
29
+
30
+ Returns
31
+ -------
32
+ out : ndarray
33
+ The new labelled array.
34
+
35
+ Examples
36
+ --------
37
+ >>> from skimage import data, segmentation, graph
38
+ >>> img = data.astronaut()
39
+ >>> labels = segmentation.slic(img)
40
+ >>> rag = graph.rag_mean_color(img, labels)
41
+ >>> new_labels = graph.cut_threshold(labels, rag, 10)
42
+
43
+ References
44
+ ----------
45
+ .. [1] Alain Tremeau and Philippe Colantoni
46
+ "Regions Adjacency Graph Applied To Color Image Segmentation"
47
+ :DOI:`10.1109/83.841950`
48
+
49
+ """
50
+ if not in_place:
51
+ rag = rag.copy()
52
+
53
+ # Because deleting edges while iterating through them produces an error.
54
+ to_remove = [(x, y) for x, y, d in rag.edges(data=True) if d['weight'] >= thresh]
55
+ rag.remove_edges_from(to_remove)
56
+
57
+ comps = nx.connected_components(rag)
58
+
59
+ # We construct an array which can map old labels to the new ones.
60
+ # All the labels within a connected component are assigned to a single
61
+ # label in the output.
62
+ map_array = np.arange(labels.max() + 1, dtype=labels.dtype)
63
+ for i, nodes in enumerate(comps):
64
+ for node in nodes:
65
+ for label in rag.nodes[node]['labels']:
66
+ map_array[label] = i
67
+
68
+ return map_array[labels]
69
+
70
+
71
+ def cut_normalized(
72
+ labels,
73
+ rag,
74
+ thresh=0.001,
75
+ num_cuts=10,
76
+ in_place=True,
77
+ max_edge=1.0,
78
+ *,
79
+ rng=None,
80
+ ):
81
+ """Perform Normalized Graph cut on the Region Adjacency Graph.
82
+
83
+ Given an image's labels and its similarity RAG, recursively perform
84
+ a 2-way normalized cut on it. All nodes belonging to a subgraph
85
+ that cannot be cut further are assigned a unique label in the
86
+ output.
87
+
88
+ Parameters
89
+ ----------
90
+ labels : ndarray
91
+ The array of labels.
92
+ rag : RAG
93
+ The region adjacency graph.
94
+ thresh : float
95
+ The threshold. A subgraph won't be further subdivided if the
96
+ value of the N-cut exceeds `thresh`.
97
+ num_cuts : int
98
+ The number or N-cuts to perform before determining the optimal one.
99
+ in_place : bool
100
+ If set, modifies `rag` in place. For each node `n` the function will
101
+ set a new attribute ``rag.nodes[n]['ncut label']``.
102
+ max_edge : float, optional
103
+ The maximum possible value of an edge in the RAG. This corresponds to
104
+ an edge between identical regions. This is used to put self
105
+ edges in the RAG.
106
+ rng : {`numpy.random.Generator`, int}, optional
107
+ Pseudo-random number generator.
108
+ By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
109
+ If `rng` is an int, it is used to seed the generator.
110
+
111
+ The `rng` is used to determine the starting point
112
+ of `scipy.sparse.linalg.eigsh`.
113
+
114
+ Returns
115
+ -------
116
+ out : ndarray
117
+ The new labeled array.
118
+
119
+ Examples
120
+ --------
121
+ >>> from skimage import data, segmentation, graph
122
+ >>> img = data.astronaut()
123
+ >>> labels = segmentation.slic(img)
124
+ >>> rag = graph.rag_mean_color(img, labels, mode='similarity')
125
+ >>> new_labels = graph.cut_normalized(labels, rag)
126
+
127
+ References
128
+ ----------
129
+ .. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation",
130
+ Pattern Analysis and Machine Intelligence,
131
+ IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
132
+
133
+ """
134
+ rng = np.random.default_rng(rng)
135
+ if not in_place:
136
+ rag = rag.copy()
137
+
138
+ for node in rag.nodes():
139
+ rag.add_edge(node, node, weight=max_edge)
140
+
141
+ _ncut_relabel(rag, thresh, num_cuts, rng)
142
+
143
+ map_array = np.zeros(labels.max() + 1, dtype=labels.dtype)
144
+ # Mapping from old labels to new
145
+ for n, d in rag.nodes(data=True):
146
+ map_array[d['labels']] = d['ncut label']
147
+
148
+ return map_array[labels]
149
+
150
+
151
+ def partition_by_cut(cut, rag):
152
+ """Compute resulting subgraphs from given bi-partition.
153
+
154
+ Parameters
155
+ ----------
156
+ cut : array
157
+ A array of booleans. Elements set to `True` belong to one
158
+ set.
159
+ rag : RAG
160
+ The Region Adjacency Graph.
161
+
162
+ Returns
163
+ -------
164
+ sub1, sub2 : RAG
165
+ The two resulting subgraphs from the bi-partition.
166
+ """
167
+ # `cut` is derived from `D` and `W` matrices, which also follow the
168
+ # ordering returned by `rag.nodes()` because we use
169
+ # nx.to_scipy_sparse_array.
170
+
171
+ # Example
172
+ # rag.nodes() = [3, 7, 9, 13]
173
+ # cut = [True, False, True, False]
174
+ # nodes1 = [3, 9]
175
+ # nodes2 = [7, 10]
176
+
177
+ nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]]
178
+ nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]]
179
+
180
+ sub1 = rag.subgraph(nodes1)
181
+ sub2 = rag.subgraph(nodes2)
182
+
183
+ return sub1, sub2
184
+
185
+
186
+ def get_min_ncut(ev, d, w, num_cuts):
187
+ """Threshold an eigenvector evenly, to determine minimum ncut.
188
+
189
+ Parameters
190
+ ----------
191
+ ev : array
192
+ The eigenvector to threshold.
193
+ d : ndarray
194
+ The diagonal matrix of the graph.
195
+ w : ndarray
196
+ The weight matrix of the graph.
197
+ num_cuts : int
198
+ The number of evenly spaced thresholds to check for.
199
+
200
+ Returns
201
+ -------
202
+ mask : array
203
+ The array of booleans which denotes the bi-partition.
204
+ mcut : float
205
+ The value of the minimum ncut.
206
+ """
207
+ mcut = np.inf
208
+ mn = ev.min()
209
+ mx = ev.max()
210
+
211
+ # If all values in `ev` are equal, it implies that the graph can't be
212
+ # further sub-divided. In this case the bi-partition is the the graph
213
+ # itself and an empty set.
214
+ min_mask = np.zeros_like(ev, dtype=bool)
215
+ if np.allclose(mn, mx):
216
+ return min_mask, mcut
217
+
218
+ # Refer Shi & Malik 2001, Section 3.1.3, Page 892
219
+ # Perform evenly spaced n-cuts and determine the optimal one.
220
+ for t in np.linspace(mn, mx, num_cuts, endpoint=False):
221
+ mask = ev > t
222
+ cost = _ncut.ncut_cost(mask, d, w)
223
+ if cost < mcut:
224
+ min_mask = mask
225
+ mcut = cost
226
+
227
+ return min_mask, mcut
228
+
229
+
230
+ def _label_all(rag, attr_name):
231
+ """Assign a unique integer to the given attribute in the RAG.
232
+
233
+ This function assumes that all labels in `rag` are unique. It
234
+ picks up a random label from them and assigns it to the `attr_name`
235
+ attribute of all the nodes.
236
+
237
+ rag : RAG
238
+ The Region Adjacency Graph.
239
+ attr_name : string
240
+ The attribute to which a unique integer is assigned.
241
+ """
242
+ node = min(rag.nodes())
243
+ new_label = rag.nodes[node]['labels'][0]
244
+ for n, d in rag.nodes(data=True):
245
+ d[attr_name] = new_label
246
+
247
+
248
+ def _ncut_relabel(rag, thresh, num_cuts, random_generator):
249
+ """Perform Normalized Graph cut on the Region Adjacency Graph.
250
+
251
+ Recursively partition the graph into 2, until further subdivision
252
+ yields a cut greater than `thresh` or such a cut cannot be computed.
253
+ For such a subgraph, indices to labels of all its nodes map to a single
254
+ unique value.
255
+
256
+ Parameters
257
+ ----------
258
+ rag : RAG
259
+ The region adjacency graph.
260
+ thresh : float
261
+ The threshold. A subgraph won't be further subdivided if the
262
+ value of the N-cut exceeds `thresh`.
263
+ num_cuts : int
264
+ The number or N-cuts to perform before determining the optimal one.
265
+ random_generator : `numpy.random.Generator`
266
+ Provides initial values for eigenvalue solver.
267
+ """
268
+ d, w = _ncut.DW_matrices(rag)
269
+ m = w.shape[0]
270
+
271
+ if (m > 2) and (d != w).nnz > 0:
272
+ # This avoids further segmenting a graph that is too small,
273
+ # and the degenerate case (d == w), which typically occurs
274
+ # when only three single pixels remain.
275
+ #
276
+ # We're not sure exactly why this latter case arises. For
277
+ # SciPy <= 0.14, SciPy continued to compute an eigenvector,
278
+ # but newer versions (correctly) won't. We refuse to guess,
279
+ # and stop further segmentation.
280
+ #
281
+ # It may make sense to a warning here; on the other hand segmentations
282
+ # are not a ground truth, so this level of "noise" should be acceptable.
283
+
284
+ d2 = d.copy()
285
+ # Since d is diagonal, we can directly operate on its data
286
+ # the inverse of the square root
287
+ d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data)
288
+
289
+ # Refer Shi & Malik 2001, Equation 7, Page 891
290
+ A = d2 @ (d - w) @ d2
291
+ # Initialize the vector to ensure reproducibility.
292
+ v0 = random_generator.random(A.shape[0])
293
+
294
+ # SciPy 1.17.0.dev0 adds the new `rng` keyword, allowing `eigsh` to
295
+ # become deterministic
296
+ rng_kw = {"rng": random_generator} if SCIPY_GE_1_17_0_DEV0 else {}
297
+ vals, vectors = linalg.eigsh(A, which='SM', v0=v0, k=min(100, m - 2), **rng_kw)
298
+
299
+ # Pick second smallest eigenvector.
300
+ # Refer Shi & Malik 2001, Section 3.2.3, Page 893
301
+ vals, vectors = np.real(vals), np.real(vectors)
302
+ index2 = _ncut_cy.argmin2(vals)
303
+ ev = vectors[:, index2]
304
+
305
+ cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts)
306
+ if mcut < thresh:
307
+ # Sub divide and perform N-cut again
308
+ # Refer Shi & Malik 2001, Section 3.2.5, Page 893
309
+ sub1, sub2 = partition_by_cut(cut_mask, rag)
310
+
311
+ _ncut_relabel(sub1, thresh, num_cuts, random_generator)
312
+ _ncut_relabel(sub2, thresh, num_cuts, random_generator)
313
+ return
314
+
315
+ # The N-cut wasn't small enough, or could not be computed.
316
+ # The remaining graph is a region.
317
+ # Assign `ncut label` by picking any label from the existing nodes, since
318
+ # `labels` are unique, `new_label` is also unique.
319
+ _label_all(rag, 'ncut label')
envs/kitoverlay/skimage/graph/_graph_merge.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import heapq
3
+
4
+
5
+ def _revalidate_node_edges(rag, node, heap_list):
6
+ """Handles validation and invalidation of edges incident to a node.
7
+
8
+ This function invalidates all existing edges incident on `node` and inserts
9
+ new items in `heap_list` updated with the valid weights.
10
+
11
+ rag : RAG
12
+ The Region Adjacency Graph.
13
+ node : int
14
+ The id of the node whose incident edges are to be validated/invalidated
15
+ .
16
+ heap_list : list
17
+ The list containing the existing heap of edges.
18
+ """
19
+ # networkx updates data dictionary if edge exists
20
+ # this would mean we have to reposition these edges in
21
+ # heap if their weight is updated.
22
+ # instead we invalidate them
23
+
24
+ for nbr in rag.neighbors(node):
25
+ data = rag[node][nbr]
26
+ try:
27
+ # invalidate edges incident on `dst`, they have new weights
28
+ data['heap item'][3] = False
29
+ _invalidate_edge(rag, node, nbr)
30
+ except KeyError:
31
+ # will handle the case where the edge did not exist in the existing
32
+ # graph
33
+ pass
34
+
35
+ wt = data['weight']
36
+ heap_item = [wt, node, nbr, True]
37
+ data['heap item'] = heap_item
38
+ heapq.heappush(heap_list, heap_item)
39
+
40
+
41
+ def _rename_node(graph, node_id, copy_id):
42
+ """Rename `node_id` in `graph` to `copy_id`."""
43
+
44
+ graph._add_node_silent(copy_id)
45
+ graph.nodes[copy_id].update(graph.nodes[node_id])
46
+
47
+ for nbr in graph.neighbors(node_id):
48
+ wt = graph[node_id][nbr]['weight']
49
+ graph.add_edge(nbr, copy_id, {'weight': wt})
50
+
51
+ graph.remove_node(node_id)
52
+
53
+
54
+ def _invalidate_edge(graph, n1, n2):
55
+ """Invalidates the edge (n1, n2) in the heap."""
56
+ graph[n1][n2]['heap item'][3] = False
57
+
58
+
59
+ def merge_hierarchical(
60
+ labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func
61
+ ):
62
+ """Perform hierarchical merging of a RAG.
63
+
64
+ Greedily merges the most similar pair of nodes until no edges lower than
65
+ `thresh` remain.
66
+
67
+ Parameters
68
+ ----------
69
+ labels : ndarray
70
+ The array of labels.
71
+ rag : RAG
72
+ The Region Adjacency Graph.
73
+ thresh : float
74
+ Regions connected by an edge with weight smaller than `thresh` are
75
+ merged.
76
+ rag_copy : bool
77
+ If set, the RAG copied before modifying.
78
+ in_place_merge : bool
79
+ If set, the nodes are merged in place. Otherwise, a new node is
80
+ created for each merge..
81
+ merge_func : callable
82
+ This function is called before merging two nodes. For the RAG `graph`
83
+ while merging `src` and `dst`, it is called as follows
84
+ ``merge_func(graph, src, dst)``.
85
+ weight_func : callable
86
+ The function to compute the new weights of the nodes adjacent to the
87
+ merged node. This is directly supplied as the argument `weight_func`
88
+ to `merge_nodes`.
89
+
90
+ Returns
91
+ -------
92
+ out : ndarray
93
+ The new labeled array.
94
+
95
+ """
96
+ if rag_copy:
97
+ rag = rag.copy()
98
+
99
+ edge_heap = []
100
+ for n1, n2, data in rag.edges(data=True):
101
+ # Push a valid edge in the heap
102
+ wt = data['weight']
103
+ heap_item = [wt, n1, n2, True]
104
+ heapq.heappush(edge_heap, heap_item)
105
+
106
+ # Reference to the heap item in the graph
107
+ data['heap item'] = heap_item
108
+
109
+ while len(edge_heap) > 0 and edge_heap[0][0] < thresh:
110
+ _, n1, n2, valid = heapq.heappop(edge_heap)
111
+
112
+ # Ensure popped edge is valid, if not, the edge is discarded
113
+ if valid:
114
+ # Invalidate all neighbors of `src` before its deleted
115
+
116
+ for nbr in rag.neighbors(n1):
117
+ _invalidate_edge(rag, n1, nbr)
118
+
119
+ for nbr in rag.neighbors(n2):
120
+ _invalidate_edge(rag, n2, nbr)
121
+
122
+ if not in_place_merge:
123
+ next_id = rag.next_id()
124
+ _rename_node(rag, n2, next_id)
125
+ src, dst = n1, next_id
126
+ else:
127
+ src, dst = n1, n2
128
+
129
+ merge_func(rag, src, dst)
130
+ new_id = rag.merge_nodes(src, dst, weight_func)
131
+ _revalidate_node_edges(rag, new_id, edge_heap)
132
+
133
+ label_map = np.arange(labels.max() + 1)
134
+ for ix, (n, d) in enumerate(rag.nodes(data=True)):
135
+ for label in d['labels']:
136
+ label_map[label] = ix
137
+
138
+ return label_map[labels]
envs/kitoverlay/skimage/graph/_ncut.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import numpy as np
3
+ from scipy import sparse
4
+ from . import _ncut_cy
5
+
6
+
7
+ def DW_matrices(graph):
8
+ """Returns the diagonal and weight matrices of a graph.
9
+
10
+ Parameters
11
+ ----------
12
+ graph : RAG
13
+ A Region Adjacency Graph.
14
+
15
+ Returns
16
+ -------
17
+ D : csc_array
18
+ The diagonal matrix of the graph. ``D[i, i]`` is the sum of weights of
19
+ all edges incident on `i`. All other entries are `0`.
20
+ W : csc_array
21
+ The weight matrix of the graph. ``W[i, j]`` is the weight of the edge
22
+ joining `i` to `j`.
23
+ """
24
+ # sparse.eighsh is most efficient with CSC-formatted input
25
+ W = nx.to_scipy_sparse_array(graph, format='csc')
26
+ entries = W.sum(axis=0)
27
+ D = sparse.dia_array((entries, 0), shape=W.shape).tocsc()
28
+
29
+ return D, W
30
+
31
+
32
+ def ncut_cost(cut, D, W):
33
+ """Returns the N-cut cost of a bi-partition of a graph.
34
+
35
+ Parameters
36
+ ----------
37
+ cut : ndarray
38
+ The mask for the nodes in the graph. Nodes corresponding to a `True`
39
+ value are in one set.
40
+ D : csc_array
41
+ The diagonal matrix of the graph.
42
+ W : csc_array
43
+ The weight matrix of the graph.
44
+
45
+ Returns
46
+ -------
47
+ cost : float
48
+ The cost of performing the N-cut.
49
+
50
+ References
51
+ ----------
52
+ .. [1] Normalized Cuts and Image Segmentation, Jianbo Shi and
53
+ Jitendra Malik, IEEE Transactions on Pattern Analysis and Machine
54
+ Intelligence, Page 889, Equation 2.
55
+ """
56
+ cut = np.array(cut)
57
+ cut_cost = _ncut_cy.cut_cost(cut, W.data, W.indices, W.indptr, num_cols=W.shape[0])
58
+
59
+ # D has elements only along the diagonal, one per node, so we can directly
60
+ # index the data attribute with cut.
61
+ assoc_a = D.data[cut].sum()
62
+ assoc_b = D.data[~cut].sum()
63
+
64
+ return (cut_cost / assoc_a) + (cut_cost / assoc_b)
envs/kitoverlay/skimage/graph/_rag.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import networkx as nx
2
+ import numpy as np
3
+ from scipy import ndimage as ndi
4
+ from scipy import sparse
5
+ import math
6
+
7
+ from .. import measure, segmentation, util, color
8
+ from .._shared.version_requirements import require
9
+
10
+
11
+ __doctest_requires__ = {("show_rag",): ["matplotlib"]}
12
+
13
+
14
+ def _edge_generator_from_csr(csr_array):
15
+ """Yield weighted edge triples for use by NetworkX from a CSR matrix.
16
+
17
+ This function is a straight rewrite of
18
+ `networkx.convert_matrix._csr_gen_triples`. Since that is a private
19
+ function, it is safer to include our own here.
20
+
21
+ Parameters
22
+ ----------
23
+ csr_array : scipy.sparse.csr_array
24
+ The input matrix. An edge (i, j, w) will be yielded if there is a
25
+ data value for coordinates (i, j) in the matrix, even if that value
26
+ is 0.
27
+
28
+ Yields
29
+ ------
30
+ i, j, w : (int, int, float) tuples
31
+ Each value `w` in the matrix along with its coordinates (i, j).
32
+
33
+ Examples
34
+ --------
35
+
36
+ >>> dense = np.eye(2, dtype=float)
37
+ >>> csr = sparse.csr_array(dense)
38
+ >>> edges = _edge_generator_from_csr(csr)
39
+ >>> list(edges)
40
+ [(0, 0, 1.0), (1, 1, 1.0)]
41
+ """
42
+ nrows = csr_array.shape[0]
43
+ values = csr_array.data
44
+ indptr = csr_array.indptr
45
+ col_indices = csr_array.indices
46
+ for i in range(nrows):
47
+ for j in range(indptr[i], indptr[i + 1]):
48
+ yield i, col_indices[j], values[j]
49
+
50
+
51
+ def min_weight(graph, src, dst, n):
52
+ """Callback to handle merging nodes by choosing minimum weight.
53
+
54
+ Returns a dictionary with `"weight"` set as either the weight between
55
+ (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when
56
+ both exist.
57
+
58
+ Parameters
59
+ ----------
60
+ graph : RAG
61
+ The graph under consideration.
62
+ src, dst : int
63
+ The verices in `graph` to be merged.
64
+ n : int
65
+ A neighbor of `src` or `dst` or both.
66
+
67
+ Returns
68
+ -------
69
+ data : dict
70
+ A dict with the `"weight"` attribute set the weight between
71
+ (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when
72
+ both exist.
73
+
74
+ """
75
+
76
+ # cover the cases where n only has edge to either `src` or `dst`
77
+ default = {'weight': np.inf}
78
+ w1 = graph[n].get(src, default)['weight']
79
+ w2 = graph[n].get(dst, default)['weight']
80
+ return {'weight': min(w1, w2)}
81
+
82
+
83
+ def _add_edge_filter(values, graph):
84
+ """Create edge in `graph` between central element of `values` and the rest.
85
+
86
+ Add an edge between the middle element in `values` and
87
+ all other elements of `values` into `graph`. ``values[len(values) // 2]``
88
+ is expected to be the central value of the footprint used.
89
+
90
+ Parameters
91
+ ----------
92
+ values : array
93
+ The array to process.
94
+ graph : RAG
95
+ The graph to add edges in.
96
+
97
+ Returns
98
+ -------
99
+ 0 : float
100
+ Always returns 0. The return value is required so that `generic_filter`
101
+ can put it in the output array, but it is ignored by this filter.
102
+ """
103
+ values = values.astype(int)
104
+ center = values[len(values) // 2]
105
+ for value in values:
106
+ if value != center and not graph.has_edge(center, value):
107
+ graph.add_edge(center, value)
108
+ return 0.0
109
+
110
+
111
+ class RAG(nx.Graph):
112
+ """The Region Adjacency Graph (RAG) of an image, subclasses :obj:`networkx.Graph`.
113
+
114
+ Parameters
115
+ ----------
116
+ label_image : array of int
117
+ An initial segmentation, with each region labeled as a different
118
+ integer. Every unique value in ``label_image`` will correspond to
119
+ a node in the graph.
120
+ connectivity : int in {1, ..., ``label_image.ndim``}, optional
121
+ The connectivity between pixels in ``label_image``. For a 2D image,
122
+ a connectivity of 1 corresponds to immediate neighbors up, down,
123
+ left, and right, while a connectivity of 2 also includes diagonal
124
+ neighbors. See :func:`scipy.ndimage.generate_binary_structure`.
125
+ data : :obj:`networkx.Graph` specification, optional
126
+ Initial or additional edges to pass to :obj:`networkx.Graph`
127
+ constructor. Valid edge specifications include edge list (list of tuples),
128
+ NumPy arrays, and SciPy sparse matrices.
129
+ **attr : keyword arguments, optional
130
+ Additional attributes to add to the graph.
131
+ """
132
+
133
+ def __init__(self, label_image=None, connectivity=1, data=None, **attr):
134
+ super().__init__(data, **attr)
135
+ if self.number_of_nodes() == 0:
136
+ self.max_id = 0
137
+ else:
138
+ self.max_id = max(self.nodes())
139
+
140
+ if label_image is not None:
141
+ fp = ndi.generate_binary_structure(label_image.ndim, connectivity)
142
+ # In the next ``ndi.generic_filter`` function, the kwarg
143
+ # ``output`` is used to provide a strided array with a single
144
+ # 64-bit floating point number, to which the function repeatedly
145
+ # writes. This is done because even if we don't care about the
146
+ # output, without this, a float array of the same shape as the
147
+ # input image will be created and that could be expensive in
148
+ # memory consumption.
149
+ output = np.broadcast_to(1.0, label_image.shape)
150
+ output.setflags(write=True)
151
+ ndi.generic_filter(
152
+ label_image,
153
+ function=_add_edge_filter,
154
+ footprint=fp,
155
+ mode='nearest',
156
+ output=output,
157
+ extra_arguments=(self,),
158
+ )
159
+
160
+ def merge_nodes(
161
+ self,
162
+ src,
163
+ dst,
164
+ weight_func=min_weight,
165
+ in_place=True,
166
+ extra_arguments=None,
167
+ extra_keywords=None,
168
+ ):
169
+ """Merge node `src` and `dst`.
170
+
171
+ The new combined node is adjacent to all the neighbors of `src`
172
+ and `dst`. `weight_func` is called to decide the weight of edges
173
+ incident on the new node.
174
+
175
+ Parameters
176
+ ----------
177
+ src, dst : int
178
+ Nodes to be merged.
179
+ weight_func : callable, optional
180
+ Function to decide the attributes of edges incident on the new
181
+ node. For each neighbor `n` for `src` and `dst`, `weight_func` will
182
+ be called as follows: `weight_func(src, dst, n, *extra_arguments,
183
+ **extra_keywords)`. `src`, `dst` and `n` are IDs of vertices in the
184
+ RAG object which is in turn a subclass of :obj:`networkx.Graph`. It is
185
+ expected to return a dict of attributes of the resulting edge.
186
+ in_place : bool, optional
187
+ If set to `True`, the merged node has the id `dst`, else merged
188
+ node has a new id which is returned.
189
+ extra_arguments : sequence, optional
190
+ The sequence of extra positional arguments passed to
191
+ `weight_func`.
192
+ extra_keywords : dictionary, optional
193
+ The dict of keyword arguments passed to the `weight_func`.
194
+
195
+ Returns
196
+ -------
197
+ id : int
198
+ The id of the new node.
199
+
200
+ Notes
201
+ -----
202
+ If `in_place` is `False` the resulting node has a new id, rather than
203
+ `dst`.
204
+ """
205
+ if extra_arguments is None:
206
+ extra_arguments = []
207
+ if extra_keywords is None:
208
+ extra_keywords = {}
209
+
210
+ src_nbrs = set(self.neighbors(src))
211
+ dst_nbrs = set(self.neighbors(dst))
212
+ neighbors = (src_nbrs | dst_nbrs) - {src, dst}
213
+
214
+ if in_place:
215
+ new = dst
216
+ else:
217
+ new = self.next_id()
218
+ self.add_node(new)
219
+
220
+ for neighbor in neighbors:
221
+ data = weight_func(
222
+ self, src, dst, neighbor, *extra_arguments, **extra_keywords
223
+ )
224
+ self.add_edge(neighbor, new, attr_dict=data)
225
+
226
+ self.nodes[new]['labels'] = (
227
+ self.nodes[src]['labels'] + self.nodes[dst]['labels']
228
+ )
229
+ self.remove_node(src)
230
+
231
+ if not in_place:
232
+ self.remove_node(dst)
233
+
234
+ return new
235
+
236
+ def add_node(self, n, attr_dict=None, **attr):
237
+ """Add node `n` while updating the maximum node id.
238
+
239
+ .. seealso:: :obj:`networkx.Graph.add_node`."""
240
+ if attr_dict is None: # compatibility with old networkx
241
+ attr_dict = attr
242
+ else:
243
+ attr_dict.update(attr)
244
+ super().add_node(n, **attr_dict)
245
+ self.max_id = max(n, self.max_id)
246
+
247
+ def add_edge(self, u, v, attr_dict=None, **attr):
248
+ """Add an edge between `u` and `v` while updating max node id.
249
+
250
+ .. seealso:: :obj:`networkx.Graph.add_edge`."""
251
+ if attr_dict is None: # compatibility with old networkx
252
+ attr_dict = attr
253
+ else:
254
+ attr_dict.update(attr)
255
+ super().add_edge(u, v, **attr_dict)
256
+ self.max_id = max(u, v, self.max_id)
257
+
258
+ def copy(self):
259
+ """Copy the graph with its max node id.
260
+
261
+ .. seealso:: :obj:`networkx.Graph.copy`."""
262
+ g = super().copy()
263
+ g.max_id = self.max_id
264
+ return g
265
+
266
+ def fresh_copy(self):
267
+ """Return a fresh copy graph with the same data structure.
268
+
269
+ A fresh copy has no nodes, edges or graph attributes. It is
270
+ the same data structure as the current graph. This method is
271
+ typically used to create an empty version of the graph.
272
+
273
+ This is required when subclassing Graph with networkx v2 and
274
+ does not cause problems for v1. Here is more detail from
275
+ the network migrating from 1.x to 2.x document::
276
+
277
+ With the new GraphViews (SubGraph, ReversedGraph, etc)
278
+ you can't assume that ``G.__class__()`` will create a new
279
+ instance of the same graph type as ``G``. In fact, the
280
+ call signature for ``__class__`` differs depending on
281
+ whether ``G`` is a view or a base class. For v2.x you
282
+ should use ``G.fresh_copy()`` to create a null graph of
283
+ the correct type---ready to fill with nodes and edges.
284
+
285
+ """
286
+ return RAG()
287
+
288
+ def next_id(self):
289
+ """Returns the `id` for the new node to be inserted.
290
+
291
+ The current implementation returns one more than the maximum `id`.
292
+
293
+ Returns
294
+ -------
295
+ id : int
296
+ The `id` of the new node to be inserted.
297
+ """
298
+ return self.max_id + 1
299
+
300
+ def _add_node_silent(self, n):
301
+ """Add node `n` without updating the maximum node id.
302
+
303
+ This is a convenience method used internally.
304
+
305
+ .. seealso:: :obj:`networkx.Graph.add_node`."""
306
+ super().add_node(n)
307
+
308
+
309
+ def rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0):
310
+ """Compute the Region Adjacency Graph using mean colors.
311
+
312
+ Given an image and its initial segmentation, this method constructs the
313
+ corresponding Region Adjacency Graph (RAG). Each node in the RAG
314
+ represents a set of pixels within `image` with the same label in `labels`.
315
+ The weight between two adjacent regions represents how similar or
316
+ dissimilar two regions are depending on the `mode` parameter.
317
+
318
+ Parameters
319
+ ----------
320
+ image : ndarray, shape(M, N[, ..., P], 3)
321
+ Input image.
322
+ labels : ndarray, shape(M, N[, ..., P])
323
+ The labelled image. This should have one dimension less than
324
+ `image`. If `image` has dimensions `(M, N, 3)` `labels` should have
325
+ dimensions `(M, N)`.
326
+ connectivity : int, optional
327
+ Pixels with a squared distance less than `connectivity` from each other
328
+ are considered adjacent. It can range from 1 to `labels.ndim`. Its
329
+ behavior is the same as `connectivity` parameter in
330
+ ``scipy.ndimage.generate_binary_structure``.
331
+ mode : {'distance', 'similarity'}, optional
332
+ The strategy to assign edge weights.
333
+
334
+ 'distance' : The weight between two adjacent regions is the
335
+ :math:`|c_1 - c_2|`, where :math:`c_1` and :math:`c_2` are the mean
336
+ colors of the two regions. It represents the Euclidean distance in
337
+ their average color.
338
+
339
+ 'similarity' : The weight between two adjacent is
340
+ :math:`e^{-d^2/sigma}` where :math:`d=|c_1 - c_2|`, where
341
+ :math:`c_1` and :math:`c_2` are the mean colors of the two regions.
342
+ It represents how similar two regions are.
343
+ sigma : float, optional
344
+ Used for computation when `mode` is "similarity". It governs how
345
+ close to each other two colors should be, for their corresponding edge
346
+ weight to be significant. A very large value of `sigma` could make
347
+ any two colors behave as though they were similar.
348
+
349
+ Returns
350
+ -------
351
+ out : RAG
352
+ The region adjacency graph.
353
+
354
+ Examples
355
+ --------
356
+ >>> from skimage import data, segmentation, graph
357
+ >>> img = data.astronaut()
358
+ >>> labels = segmentation.slic(img)
359
+ >>> rag = graph.rag_mean_color(img, labels)
360
+
361
+ References
362
+ ----------
363
+ .. [1] Alain Tremeau and Philippe Colantoni
364
+ "Regions Adjacency Graph Applied To Color Image Segmentation"
365
+ :DOI:`10.1109/83.841950`
366
+ """
367
+ graph = RAG(labels, connectivity=connectivity)
368
+
369
+ for n in graph:
370
+ graph.nodes[n].update(
371
+ {
372
+ 'labels': [n],
373
+ 'pixel count': 0,
374
+ 'total color': np.array([0, 0, 0], dtype=np.float64),
375
+ }
376
+ )
377
+
378
+ for index in np.ndindex(labels.shape):
379
+ current = labels[index]
380
+ graph.nodes[current]['pixel count'] += 1
381
+ graph.nodes[current]['total color'] += image[index]
382
+
383
+ for n in graph:
384
+ graph.nodes[n]['mean color'] = (
385
+ graph.nodes[n]['total color'] / graph.nodes[n]['pixel count']
386
+ )
387
+
388
+ for x, y, d in graph.edges(data=True):
389
+ diff = graph.nodes[x]['mean color'] - graph.nodes[y]['mean color']
390
+ diff = np.linalg.norm(diff)
391
+ if mode == 'similarity':
392
+ d['weight'] = math.e ** (-(diff**2) / sigma)
393
+ elif mode == 'distance':
394
+ d['weight'] = diff
395
+ else:
396
+ raise ValueError(f"The mode '{mode}' is not recognised")
397
+
398
+ return graph
399
+
400
+
401
+ def rag_boundary(labels, edge_map, connectivity=2):
402
+ """Comouter RAG based on region boundaries
403
+
404
+ Given an image's initial segmentation and its edge map this method
405
+ constructs the corresponding Region Adjacency Graph (RAG). Each node in the
406
+ RAG represents a set of pixels within the image with the same label in
407
+ `labels`. The weight between two adjacent regions is the average value
408
+ in `edge_map` along their boundary.
409
+
410
+ labels : ndarray
411
+ The labelled image.
412
+ edge_map : ndarray
413
+ This should have the same shape as that of `labels`. For all pixels
414
+ along the boundary between 2 adjacent regions, the average value of the
415
+ corresponding pixels in `edge_map` is the edge weight between them.
416
+ connectivity : int, optional
417
+ Pixels with a squared distance less than `connectivity` from each other
418
+ are considered adjacent. It can range from 1 to `labels.ndim`. Its
419
+ behavior is the same as `connectivity` parameter in
420
+ `scipy.ndimage.generate_binary_structure`.
421
+
422
+ Examples
423
+ --------
424
+ >>> from skimage import data, segmentation, filters, color, graph
425
+ >>> img = data.chelsea()
426
+ >>> labels = segmentation.slic(img)
427
+ >>> edge_map = filters.sobel(color.rgb2gray(img))
428
+ >>> rag = graph.rag_boundary(labels, edge_map)
429
+
430
+ """
431
+
432
+ conn = ndi.generate_binary_structure(labels.ndim, connectivity)
433
+ eroded = ndi.grey_erosion(labels, footprint=conn)
434
+ dilated = ndi.grey_dilation(labels, footprint=conn)
435
+ boundaries0 = eroded != labels
436
+ boundaries1 = dilated != labels
437
+ labels_small = np.concatenate((eroded[boundaries0], labels[boundaries1]))
438
+ labels_large = np.concatenate((labels[boundaries0], dilated[boundaries1]))
439
+ n = np.max(labels_large) + 1
440
+
441
+ # use a dummy broadcast array as data for RAG
442
+ ones = np.broadcast_to(1.0, labels_small.shape)
443
+ count_matrix = sparse.csr_array(
444
+ (ones, (labels_small, labels_large)), dtype=int, shape=(n, n)
445
+ )
446
+ data = np.concatenate((edge_map[boundaries0], edge_map[boundaries1]))
447
+
448
+ graph_matrix = sparse.csr_array((data, (labels_small, labels_large)))
449
+ graph_matrix.data /= count_matrix.data
450
+
451
+ rag = RAG()
452
+ rag.add_weighted_edges_from(_edge_generator_from_csr(graph_matrix), weight='weight')
453
+ rag.add_weighted_edges_from(_edge_generator_from_csr(count_matrix), weight='count')
454
+
455
+ for n in rag.nodes():
456
+ rag.nodes[n].update({'labels': [n]})
457
+
458
+ return rag
459
+
460
+
461
+ @require("matplotlib", ">=3.3")
462
+ def show_rag(
463
+ labels,
464
+ rag,
465
+ image,
466
+ border_color='black',
467
+ edge_width=1.5,
468
+ edge_cmap='magma',
469
+ img_cmap='bone',
470
+ in_place=True,
471
+ ax=None,
472
+ ):
473
+ """Show a Region Adjacency Graph on an image.
474
+
475
+ Given a labelled image and its corresponding RAG, show the nodes and edges
476
+ of the RAG on the image with the specified colors. Edges are displayed between
477
+ the centroid of the 2 adjacent regions in the image.
478
+
479
+ Parameters
480
+ ----------
481
+ labels : ndarray, shape (M, N)
482
+ The labelled image.
483
+ rag : RAG
484
+ The Region Adjacency Graph.
485
+ image : ndarray, shape (M, N[, 3])
486
+ Input image. If `colormap` is `None`, the image should be in RGB
487
+ format.
488
+ border_color : color spec, optional
489
+ Color with which the borders between regions are drawn.
490
+ edge_width : float, optional
491
+ The thickness with which the RAG edges are drawn.
492
+ edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional
493
+ Any matplotlib colormap with which the edges are drawn.
494
+ img_cmap : :py:class:`matplotlib.colors.Colormap`, optional
495
+ Any matplotlib colormap with which the image is draw. If set to `None`
496
+ the image is drawn as it is.
497
+ in_place : bool, optional
498
+ If set, the RAG is modified in place. For each node `n` the function
499
+ will set a new attribute ``rag.nodes[n]['centroid']``.
500
+ ax : :py:class:`matplotlib.axes.Axes`, optional
501
+ The axes to draw on. If not specified, new axes are created and drawn
502
+ on.
503
+
504
+ Returns
505
+ -------
506
+ lc : :py:class:`matplotlib.collections.LineCollection`
507
+ A collection of lines that represent the edges of the graph. It can be
508
+ passed to the :meth:`matplotlib.figure.Figure.colorbar` function.
509
+
510
+ Examples
511
+ --------
512
+ >>> from skimage import data, segmentation, graph
513
+ >>> import matplotlib.pyplot as plt
514
+ >>>
515
+ >>> img = data.coffee()
516
+ >>> labels = segmentation.slic(img)
517
+ >>> g = graph.rag_mean_color(img, labels)
518
+ >>> lc = graph.show_rag(labels, g, img)
519
+ >>> cbar = plt.colorbar(lc)
520
+ """
521
+ from matplotlib import colors
522
+ from matplotlib import pyplot as plt
523
+ from matplotlib.collections import LineCollection
524
+
525
+ if not in_place:
526
+ rag = rag.copy()
527
+
528
+ if ax is None:
529
+ fig, ax = plt.subplots()
530
+ out = util.img_as_float(image, force_copy=True)
531
+
532
+ if img_cmap is None:
533
+ if image.ndim < 3 or image.shape[2] not in [3, 4]:
534
+ msg = 'If colormap is `None`, an RGB or RGBA image should be given'
535
+ raise ValueError(msg)
536
+ # Ignore the alpha channel
537
+ out = image[:, :, :3]
538
+ else:
539
+ img_cmap = plt.get_cmap(img_cmap)
540
+ out = color.rgb2gray(image)
541
+ # Ignore the alpha channel
542
+ out = img_cmap(out)[:, :, :3]
543
+
544
+ edge_cmap = plt.get_cmap(edge_cmap)
545
+
546
+ # Handling the case where one node has multiple labels
547
+ # offset is 1 so that regionprops does not ignore 0
548
+ offset = 1
549
+ map_array = np.arange(labels.max() + 1)
550
+ for n, d in rag.nodes(data=True):
551
+ for label in d['labels']:
552
+ map_array[label] = offset
553
+ offset += 1
554
+
555
+ rag_labels = map_array[labels]
556
+ regions = measure.regionprops(rag_labels)
557
+
558
+ for (n, data), region in zip(rag.nodes(data=True), regions):
559
+ data['centroid'] = tuple(map(int, region['centroid']))
560
+
561
+ cc = colors.ColorConverter()
562
+ if border_color is not None:
563
+ border_color = cc.to_rgb(border_color)
564
+ out = segmentation.mark_boundaries(out, rag_labels, color=border_color)
565
+
566
+ ax.imshow(out)
567
+
568
+ # Defining the end points of the edges
569
+ # The tuple[::-1] syntax reverses a tuple as matplotlib uses (x,y)
570
+ # convention while skimage uses (row, column)
571
+ lines = [
572
+ [rag.nodes[n1]['centroid'][::-1], rag.nodes[n2]['centroid'][::-1]]
573
+ for (n1, n2) in rag.edges()
574
+ ]
575
+
576
+ lc = LineCollection(lines, linewidths=edge_width, cmap=edge_cmap)
577
+ edge_weights = [d['weight'] for x, y, d in rag.edges(data=True)]
578
+ lc.set_array(np.array(edge_weights))
579
+ ax.add_collection(lc)
580
+
581
+ return lc
envs/kitoverlay/skimage/graph/mcp.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible # noqa: F401
2
+
3
+
4
+ def route_through_array(array, start, end, fully_connected=True, geometric=True):
5
+ """Simple example of how to use the MCP and MCP_Geometric classes.
6
+
7
+ See the MCP and MCP_Geometric class documentation for explanation of the
8
+ path-finding algorithm.
9
+
10
+ Parameters
11
+ ----------
12
+ array : ndarray
13
+ Array of costs.
14
+ start : iterable
15
+ n-d index into `array` defining the starting point
16
+ end : iterable
17
+ n-d index into `array` defining the end point
18
+ fully_connected : bool (optional)
19
+ If True, diagonal moves are permitted, if False, only axial moves.
20
+ geometric : bool (optional)
21
+ If True, the MCP_Geometric class is used to calculate costs, if False,
22
+ the MCP base class is used. See the class documentation for
23
+ an explanation of the differences between MCP and MCP_Geometric.
24
+
25
+ Returns
26
+ -------
27
+ path : list
28
+ List of n-d index tuples defining the path from `start` to `end`.
29
+ cost : float
30
+ Cost of the path. If `geometric` is False, the cost of the path is
31
+ the sum of the values of `array` along the path. If `geometric` is
32
+ True, a finer computation is made (see the documentation of the
33
+ MCP_Geometric class).
34
+
35
+ See Also
36
+ --------
37
+ MCP, MCP_Geometric
38
+
39
+ Examples
40
+ --------
41
+ >>> import numpy as np
42
+ >>> from skimage.graph import route_through_array
43
+ >>>
44
+ >>> image = np.array([[1, 3], [10, 12]])
45
+ >>> image
46
+ array([[ 1, 3],
47
+ [10, 12]])
48
+ >>> # Forbid diagonal steps
49
+ >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False)
50
+ ([(0, 0), (0, 1), (1, 1)], 9.5)
51
+ >>> # Now allow diagonal steps: the path goes directly from start to end
52
+ >>> route_through_array(image, [0, 0], [1, 1])
53
+ ([(0, 0), (1, 1)], 9.19238815542512)
54
+ >>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12)
55
+ >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False,
56
+ ... geometric=False)
57
+ ([(0, 0), (0, 1), (1, 1)], 16.0)
58
+ >>> # Larger array where we display the path that is selected
59
+ >>> image = np.arange((36)).reshape((6, 6))
60
+ >>> image
61
+ array([[ 0, 1, 2, 3, 4, 5],
62
+ [ 6, 7, 8, 9, 10, 11],
63
+ [12, 13, 14, 15, 16, 17],
64
+ [18, 19, 20, 21, 22, 23],
65
+ [24, 25, 26, 27, 28, 29],
66
+ [30, 31, 32, 33, 34, 35]])
67
+ >>> # Find the path with lowest cost
68
+ >>> indices, weight = route_through_array(image, (0, 0), (5, 5))
69
+ >>> indices = np.stack(indices, axis=-1)
70
+ >>> path = np.zeros_like(image)
71
+ >>> path[indices[0], indices[1]] = 1
72
+ >>> path
73
+ array([[1, 1, 1, 1, 1, 0],
74
+ [0, 0, 0, 0, 0, 1],
75
+ [0, 0, 0, 0, 0, 1],
76
+ [0, 0, 0, 0, 0, 1],
77
+ [0, 0, 0, 0, 0, 1],
78
+ [0, 0, 0, 0, 0, 1]])
79
+
80
+ """
81
+ start, end = tuple(start), tuple(end)
82
+ if geometric:
83
+ mcp_class = MCP_Geometric
84
+ else:
85
+ mcp_class = MCP
86
+ m = mcp_class(array, fully_connected=fully_connected)
87
+ costs, traceback_array = m.find_costs([start], [end])
88
+ return m.traceback(end), costs[end]
envs/kitoverlay/skimage/graph/spath.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from . import _spath
3
+
4
+
5
+ def shortest_path(arr, reach=1, axis=-1, output_indexlist=False):
6
+ """Find the shortest path through an n-d array from one side to another.
7
+
8
+ Parameters
9
+ ----------
10
+ arr : ndarray of float64
11
+ reach : int, optional
12
+ By default (``reach = 1``), the shortest path can only move
13
+ one row up or down for every step it moves forward (i.e.,
14
+ the path gradient is limited to 1). `reach` defines the
15
+ number of elements that can be skipped along each non-axis
16
+ dimension at each step.
17
+ axis : int, optional
18
+ The axis along which the path must always move forward (default -1)
19
+ output_indexlist : bool, optional
20
+ See return value `p` for explanation.
21
+
22
+ Returns
23
+ -------
24
+ p : iterable of int
25
+ For each step along `axis`, the coordinate of the shortest path.
26
+ If `output_indexlist` is True, then the path is returned as a list of
27
+ n-d tuples that index into `arr`. If False, then the path is returned
28
+ as an array listing the coordinates of the path along the non-axis
29
+ dimensions for each step along the axis dimension. That is,
30
+ `p.shape == (arr.shape[axis], arr.ndim-1)` except that p is squeezed
31
+ before returning so if `arr.ndim == 2`, then
32
+ `p.shape == (arr.shape[axis],)`
33
+ cost : float
34
+ Cost of path. This is the absolute sum of all the
35
+ differences along the path.
36
+
37
+ """
38
+ # First: calculate the valid moves from any given position. Basically,
39
+ # always move +1 along the given axis, and then can move anywhere within
40
+ # a grid defined by the reach.
41
+ if axis < 0:
42
+ axis += arr.ndim
43
+ offset_ind_shape = (2 * reach + 1,) * (arr.ndim - 1)
44
+ offset_indices = np.indices(offset_ind_shape) - reach
45
+ offset_indices = np.insert(offset_indices, axis, np.ones(offset_ind_shape), axis=0)
46
+ offset_size = np.multiply.reduce(offset_ind_shape)
47
+ offsets = np.reshape(offset_indices, (arr.ndim, offset_size), order='F').T
48
+
49
+ # Valid starting positions are anywhere on the hyperplane defined by
50
+ # position 0 on the given axis. Ending positions are anywhere on the
51
+ # hyperplane at position -1 along the same.
52
+ non_axis_shape = arr.shape[:axis] + arr.shape[axis + 1 :]
53
+ non_axis_indices = np.indices(non_axis_shape)
54
+ non_axis_size = np.multiply.reduce(non_axis_shape)
55
+ start_indices = np.insert(non_axis_indices, axis, np.zeros(non_axis_shape), axis=0)
56
+ starts = np.reshape(start_indices, (arr.ndim, non_axis_size), order='F').T
57
+ end_indices = np.insert(
58
+ non_axis_indices,
59
+ axis,
60
+ np.full(non_axis_shape, -1, dtype=non_axis_indices.dtype),
61
+ axis=0,
62
+ )
63
+ ends = np.reshape(end_indices, (arr.ndim, non_axis_size), order='F').T
64
+
65
+ # Find the minimum-cost path to one of the end-points
66
+ m = _spath.MCP_Diff(arr, offsets=offsets)
67
+ costs, traceback = m.find_costs(starts, ends, find_all_ends=False)
68
+
69
+ # Figure out which end-point was found
70
+ for end in ends:
71
+ cost = costs[tuple(end)]
72
+ if cost != np.inf:
73
+ break
74
+ traceback = m.traceback(end)
75
+
76
+ if not output_indexlist:
77
+ traceback = np.array(traceback)
78
+ traceback = np.concatenate(
79
+ [traceback[:, :axis], traceback[:, axis + 1 :]], axis=1
80
+ )
81
+ traceback = np.squeeze(traceback)
82
+
83
+ return traceback, cost
envs/kitoverlay/skimage/registration/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Image registration algorithms, e.g., optical flow or phase cross correlation."""
2
+
3
+ import lazy_loader as _lazy
4
+
5
+ __getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__)
envs/kitoverlay/skimage/registration/__init__.pyi ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Explicitly setting `__all__` is necessary for type inference engines
2
+ # to know which symbols are exported. See
3
+ # https://peps.python.org/pep-0484/#stub-files
4
+
5
+ __all__ = ['optical_flow_ilk', 'optical_flow_tvl1', 'phase_cross_correlation']
6
+
7
+ from ._optical_flow import optical_flow_tvl1, optical_flow_ilk
8
+ from ._phase_cross_correlation import phase_cross_correlation
envs/kitoverlay/skimage/registration/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (444 Bytes). View file
 
envs/kitoverlay/skimage/registration/__pycache__/_masked_phase_cross_correlation.cpython-311.pyc ADDED
Binary file (13.7 kB). View file
 
envs/kitoverlay/skimage/registration/__pycache__/_optical_flow.cpython-311.pyc ADDED
Binary file (17.1 kB). View file
 
envs/kitoverlay/skimage/registration/__pycache__/_optical_flow_utils.cpython-311.pyc ADDED
Binary file (5.52 kB). View file
 
envs/kitoverlay/skimage/registration/__pycache__/_phase_cross_correlation.cpython-311.pyc ADDED
Binary file (20.9 kB). View file
 
envs/kitoverlay/skimage/registration/_masked_phase_cross_correlation.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of the masked normalized cross-correlation.
3
+
4
+ Based on the following publication:
5
+ D. Padfield. Masked object registration in the Fourier domain.
6
+ IEEE Transactions on Image Processing (2012)
7
+
8
+ and the author's original MATLAB implementation, available on this website:
9
+ http://www.dirkpadfield.com/
10
+ """
11
+
12
+ from functools import partial
13
+
14
+ import numpy as np
15
+ import scipy.fft as fftmodule
16
+ from scipy.fft import next_fast_len
17
+
18
+ from .._shared.utils import _supported_float_type
19
+
20
+
21
+ def _masked_phase_cross_correlation(
22
+ reference_image, moving_image, reference_mask, moving_mask=None, overlap_ratio=0.3
23
+ ):
24
+ """Masked image translation registration by masked normalized
25
+ cross-correlation.
26
+
27
+ Parameters
28
+ ----------
29
+ reference_image : ndarray
30
+ Reference image.
31
+ moving_image : ndarray
32
+ Image to register. Must be same dimensionality as ``reference_image``,
33
+ but not necessarily the same size.
34
+ reference_mask : ndarray
35
+ Boolean mask for ``reference_image``. The mask should evaluate
36
+ to ``True`` (or 1) on valid pixels. ``reference_mask`` should
37
+ have the same shape as ``reference_image``.
38
+ moving_mask : ndarray or None, optional
39
+ Boolean mask for ``moving_image``. The mask should evaluate to ``True``
40
+ (or 1) on valid pixels. ``moving_mask`` should have the same shape
41
+ as ``moving_image``. If ``None``, ``reference_mask`` will be used.
42
+ overlap_ratio : float, optional
43
+ Minimum allowed overlap ratio between images. The correlation for
44
+ translations corresponding with an overlap ratio lower than this
45
+ threshold will be ignored. A lower `overlap_ratio` leads to smaller
46
+ maximum translation, while a higher `overlap_ratio` leads to greater
47
+ robustness against spurious matches due to small overlap between
48
+ masked images.
49
+
50
+ Returns
51
+ -------
52
+ shifts : ndarray
53
+ Shift vector (in pixels) required to register ``moving_image``
54
+ with ``reference_image``. Axis ordering is consistent with numpy.
55
+
56
+ References
57
+ ----------
58
+ .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain.
59
+ IEEE Transactions on Image Processing, vol. 21(5),
60
+ pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402`
61
+ .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and
62
+ Pattern Recognition, pp. 2918-2925 (2010).
63
+ :DOI:`10.1109/CVPR.2010.5540032`
64
+
65
+ """
66
+ if moving_mask is None:
67
+ if reference_image.shape != moving_image.shape:
68
+ raise ValueError(
69
+ "Input images have different shapes, moving_mask must "
70
+ "be explicitly set."
71
+ )
72
+ moving_mask = reference_mask.astype(bool)
73
+
74
+ # We need masks to be of the same size as their respective images
75
+ for im, mask in [(reference_image, reference_mask), (moving_image, moving_mask)]:
76
+ if im.shape != mask.shape:
77
+ raise ValueError("Image sizes must match their respective mask sizes.")
78
+
79
+ xcorr = cross_correlate_masked(
80
+ moving_image,
81
+ reference_image,
82
+ moving_mask,
83
+ reference_mask,
84
+ axes=tuple(range(moving_image.ndim)),
85
+ mode='full',
86
+ overlap_ratio=overlap_ratio,
87
+ )
88
+
89
+ # Generalize to the average of multiple equal maxima
90
+ maxima = np.stack(np.nonzero(xcorr == xcorr.max()), axis=1)
91
+ center = np.mean(maxima, axis=0)
92
+ shifts = center - np.array(reference_image.shape) + 1
93
+
94
+ # The mismatch in size will impact the center location of the
95
+ # cross-correlation
96
+ size_mismatch = np.array(moving_image.shape) - np.array(reference_image.shape)
97
+
98
+ return -shifts + (size_mismatch / 2)
99
+
100
+
101
+ def cross_correlate_masked(
102
+ arr1, arr2, m1, m2, mode='full', axes=(-2, -1), overlap_ratio=0.3
103
+ ):
104
+ """
105
+ Masked normalized cross-correlation between arrays.
106
+
107
+ Parameters
108
+ ----------
109
+ arr1 : ndarray
110
+ First array.
111
+ arr2 : ndarray
112
+ Seconds array. The dimensions of `arr2` along axes that are not
113
+ transformed should be equal to that of `arr1`.
114
+ m1 : ndarray
115
+ Mask of `arr1`. The mask should evaluate to `True`
116
+ (or 1) on valid pixels. `m1` should have the same shape as `arr1`.
117
+ m2 : ndarray
118
+ Mask of `arr2`. The mask should evaluate to `True`
119
+ (or 1) on valid pixels. `m2` should have the same shape as `arr2`.
120
+ mode : {'full', 'same'}, optional
121
+ 'full':
122
+ This returns the convolution at each point of overlap. At
123
+ the end-points of the convolution, the signals do not overlap
124
+ completely, and boundary effects may be seen.
125
+ 'same':
126
+ The output is the same size as `arr1`, centered with respect
127
+ to the `‘full’` output. Boundary effects are less prominent.
128
+ axes : tuple of ints, optional
129
+ Axes along which to compute the cross-correlation.
130
+ overlap_ratio : float, optional
131
+ Minimum allowed overlap ratio between images. The correlation for
132
+ translations corresponding with an overlap ratio lower than this
133
+ threshold will be ignored. A lower `overlap_ratio` leads to smaller
134
+ maximum translation, while a higher `overlap_ratio` leads to greater
135
+ robustness against spurious matches due to small overlap between
136
+ masked images.
137
+
138
+ Returns
139
+ -------
140
+ out : ndarray
141
+ Masked normalized cross-correlation.
142
+
143
+ Raises
144
+ ------
145
+ ValueError : if correlation `mode` is not valid, or array dimensions along
146
+ non-transformation axes are not equal.
147
+
148
+ References
149
+ ----------
150
+ .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain.
151
+ IEEE Transactions on Image Processing, vol. 21(5),
152
+ pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402`
153
+ .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and
154
+ Pattern Recognition, pp. 2918-2925 (2010).
155
+ :DOI:`10.1109/CVPR.2010.5540032`
156
+ """
157
+ if mode not in {'full', 'same'}:
158
+ raise ValueError(f"Correlation mode '{mode}' is not valid.")
159
+
160
+ fixed_image = np.asarray(arr1)
161
+ moving_image = np.asarray(arr2)
162
+ float_dtype = _supported_float_type((fixed_image.dtype, moving_image.dtype))
163
+ if float_dtype.kind == 'c':
164
+ raise ValueError("complex-valued arr1, arr2 are not supported")
165
+
166
+ fixed_image = fixed_image.astype(float_dtype)
167
+ fixed_mask = np.array(m1, dtype=bool)
168
+ moving_image = moving_image.astype(float_dtype)
169
+ moving_mask = np.array(m2, dtype=bool)
170
+ eps = np.finfo(float_dtype).eps
171
+
172
+ # Array dimensions along non-transformation axes should be equal.
173
+ all_axes = set(range(fixed_image.ndim))
174
+ for axis in all_axes - set(axes):
175
+ if fixed_image.shape[axis] != moving_image.shape[axis]:
176
+ raise ValueError(
177
+ f'Array shapes along non-transformation axes should be '
178
+ f'equal, but dimensions along axis {axis} are not.'
179
+ )
180
+
181
+ # Determine final size along transformation axes
182
+ # Note that it might be faster to compute Fourier transform in a slightly
183
+ # larger shape (`fast_shape`). Then, after all fourier transforms are done,
184
+ # we slice back to`final_shape` using `final_slice`.
185
+ final_shape = list(arr1.shape)
186
+ for axis in axes:
187
+ final_shape[axis] = fixed_image.shape[axis] + moving_image.shape[axis] - 1
188
+ final_shape = tuple(final_shape)
189
+ final_slice = tuple([slice(0, int(sz)) for sz in final_shape])
190
+
191
+ # Extent transform axes to the next fast length (i.e. multiple of 3, 5, or
192
+ # 7)
193
+ fast_shape = tuple([next_fast_len(final_shape[ax]) for ax in axes])
194
+
195
+ # We use the new scipy.fft because they allow leaving the transform axes
196
+ # unchanged which was not possible with scipy.fftpack's
197
+ # fftn/ifftn in older versions of SciPy.
198
+ # E.g. arr shape (2, 3, 7), transform along axes (0, 1) with shape (4, 4)
199
+ # results in arr_fft shape (4, 4, 7)
200
+ fft = partial(fftmodule.fftn, s=fast_shape, axes=axes)
201
+ _ifft = partial(fftmodule.ifftn, s=fast_shape, axes=axes)
202
+
203
+ def ifft(x):
204
+ return _ifft(x).real
205
+
206
+ fixed_image[np.logical_not(fixed_mask)] = 0.0
207
+ moving_image[np.logical_not(moving_mask)] = 0.0
208
+
209
+ # N-dimensional analog to rotation by 180deg is flip over all relevant axes.
210
+ # See [1] for discussion.
211
+ rotated_moving_image = _flip(moving_image, axes=axes)
212
+ rotated_moving_mask = _flip(moving_mask, axes=axes)
213
+
214
+ fixed_fft = fft(fixed_image)
215
+ rotated_moving_fft = fft(rotated_moving_image)
216
+ fixed_mask_fft = fft(fixed_mask.astype(float_dtype))
217
+ rotated_moving_mask_fft = fft(rotated_moving_mask.astype(float_dtype))
218
+
219
+ # Calculate overlap of masks at every point in the convolution.
220
+ # Locations with high overlap should not be taken into account.
221
+ number_overlap_masked_px = ifft(rotated_moving_mask_fft * fixed_mask_fft)
222
+ number_overlap_masked_px[:] = np.round(number_overlap_masked_px)
223
+ number_overlap_masked_px[:] = np.fmax(number_overlap_masked_px, eps)
224
+ masked_correlated_fixed_fft = ifft(rotated_moving_mask_fft * fixed_fft)
225
+ masked_correlated_rotated_moving_fft = ifft(fixed_mask_fft * rotated_moving_fft)
226
+
227
+ numerator = ifft(rotated_moving_fft * fixed_fft)
228
+ numerator -= (
229
+ masked_correlated_fixed_fft
230
+ * masked_correlated_rotated_moving_fft
231
+ / number_overlap_masked_px
232
+ )
233
+
234
+ fixed_squared_fft = fft(np.square(fixed_image))
235
+ fixed_denom = ifft(rotated_moving_mask_fft * fixed_squared_fft)
236
+ fixed_denom -= np.square(masked_correlated_fixed_fft) / number_overlap_masked_px
237
+ fixed_denom[:] = np.fmax(fixed_denom, 0.0)
238
+
239
+ rotated_moving_squared_fft = fft(np.square(rotated_moving_image))
240
+ moving_denom = ifft(fixed_mask_fft * rotated_moving_squared_fft)
241
+ moving_denom -= (
242
+ np.square(masked_correlated_rotated_moving_fft) / number_overlap_masked_px
243
+ )
244
+ moving_denom[:] = np.fmax(moving_denom, 0.0)
245
+
246
+ denom = np.sqrt(fixed_denom * moving_denom)
247
+
248
+ # Slice back to expected convolution shape.
249
+ numerator = numerator[final_slice]
250
+ denom = denom[final_slice]
251
+ number_overlap_masked_px = number_overlap_masked_px[final_slice]
252
+
253
+ if mode == 'same':
254
+ _centering = partial(_centered, newshape=fixed_image.shape, axes=axes)
255
+ denom = _centering(denom)
256
+ numerator = _centering(numerator)
257
+ number_overlap_masked_px = _centering(number_overlap_masked_px)
258
+
259
+ # Pixels where `denom` is very small will introduce large
260
+ # numbers after division. To get around this problem,
261
+ # we zero-out problematic pixels.
262
+ tol = 1e3 * eps * np.max(np.abs(denom), axis=axes, keepdims=True)
263
+ nonzero_indices = denom > tol
264
+
265
+ # explicitly set out dtype for compatibility with SciPy < 1.4, where
266
+ # fftmodule will be numpy.fft which always uses float64 dtype.
267
+ out = np.zeros_like(denom, dtype=float_dtype)
268
+ out[nonzero_indices] = numerator[nonzero_indices] / denom[nonzero_indices]
269
+ np.clip(out, a_min=-1, a_max=1, out=out)
270
+
271
+ # Apply overlap ratio threshold
272
+ number_px_threshold = overlap_ratio * np.max(
273
+ number_overlap_masked_px, axis=axes, keepdims=True
274
+ )
275
+ out[number_overlap_masked_px < number_px_threshold] = 0.0
276
+
277
+ return out
278
+
279
+
280
+ def _centered(arr, newshape, axes):
281
+ """Return the center `newshape` portion of `arr`, leaving axes not
282
+ in `axes` untouched."""
283
+ newshape = np.asarray(newshape)
284
+ currshape = np.array(arr.shape)
285
+
286
+ slices = [slice(None, None)] * arr.ndim
287
+
288
+ for ax in axes:
289
+ startind = (currshape[ax] - newshape[ax]) // 2
290
+ endind = startind + newshape[ax]
291
+ slices[ax] = slice(startind, endind)
292
+
293
+ return arr[tuple(slices)]
294
+
295
+
296
+ def _flip(arr, axes=None):
297
+ """Reverse array over many axes. Generalization of arr[::-1] for many
298
+ dimensions. If `axes` is `None`, flip along all axes."""
299
+ if axes is None:
300
+ reverse = [slice(None, None, -1)] * arr.ndim
301
+ else:
302
+ reverse = [slice(None, None, None)] * arr.ndim
303
+ for axis in axes:
304
+ reverse[axis] = slice(None, None, -1)
305
+
306
+ return arr[tuple(reverse)]
envs/kitoverlay/skimage/registration/_optical_flow.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TV-L1 optical flow algorithm implementation."""
2
+
3
+ from functools import partial
4
+ from itertools import combinations_with_replacement
5
+
6
+ import numpy as np
7
+ from scipy import ndimage as ndi
8
+
9
+ from .._shared.filters import gaussian as gaussian_filter
10
+ from .._shared.utils import _supported_float_type
11
+ from ..transform import warp
12
+ from ._optical_flow_utils import _coarse_to_fine, _get_warp_points
13
+
14
+
15
+ def _tvl1(
16
+ reference_image,
17
+ moving_image,
18
+ flow0,
19
+ attachment,
20
+ tightness,
21
+ num_warp,
22
+ num_iter,
23
+ tol,
24
+ prefilter,
25
+ ):
26
+ """TV-L1 solver for optical flow estimation.
27
+
28
+ Parameters
29
+ ----------
30
+ reference_image : ndarray, shape (M, N[, P[, ...]])
31
+ The first grayscale image of the sequence.
32
+ moving_image : ndarray, shape (M, N[, P[, ...]])
33
+ The second grayscale image of the sequence.
34
+ flow0 : ndarray, shape (image0.ndim, M, N[, P[, ...]])
35
+ Initialization for the vector field.
36
+ attachment : float
37
+ Attachment parameter. The smaller this parameter is,
38
+ the smoother is the solutions.
39
+ tightness : float
40
+ Tightness parameter. It should have a small value in order to
41
+ maintain attachment and regularization parts in
42
+ correspondence.
43
+ num_warp : int
44
+ Number of times moving_image is warped.
45
+ num_iter : int
46
+ Number of fixed point iteration.
47
+ tol : float
48
+ Tolerance used as stopping criterion based on the L² distance
49
+ between two consecutive values of (u, v).
50
+ prefilter : bool
51
+ Whether to prefilter the estimated optical flow before each
52
+ image warp.
53
+
54
+ Returns
55
+ -------
56
+ flow : ndarray, shape (image0.ndim, M, N[, P[, ...]])
57
+ The estimated optical flow components for each axis.
58
+
59
+ """
60
+
61
+ dtype = reference_image.dtype
62
+ grid = np.meshgrid(
63
+ *[np.arange(n, dtype=dtype) for n in reference_image.shape],
64
+ indexing='ij',
65
+ sparse=True,
66
+ )
67
+
68
+ # dt corresponds to tau in [3]_, i.e. the time step
69
+ dt = 0.5 / reference_image.ndim
70
+ reg_num_iter = 2
71
+ f0 = attachment * tightness
72
+ f1 = dt / tightness
73
+ tol *= reference_image.size
74
+
75
+ flow_current = flow_previous = flow0
76
+
77
+ g = np.zeros((reference_image.ndim,) + reference_image.shape, dtype=dtype)
78
+ proj = np.zeros(
79
+ (
80
+ reference_image.ndim,
81
+ reference_image.ndim,
82
+ )
83
+ + reference_image.shape,
84
+ dtype=dtype,
85
+ )
86
+
87
+ s_g = [
88
+ slice(None),
89
+ ] * g.ndim
90
+ s_p = [
91
+ slice(None),
92
+ ] * proj.ndim
93
+ s_d = [
94
+ slice(None),
95
+ ] * (proj.ndim - 2)
96
+
97
+ for _ in range(num_warp):
98
+ if prefilter:
99
+ flow_current = ndi.median_filter(
100
+ flow_current, [1] + reference_image.ndim * [3]
101
+ )
102
+
103
+ image1_warp = warp(
104
+ moving_image, _get_warp_points(grid, flow_current), mode='edge'
105
+ )
106
+ grad = np.array(np.gradient(image1_warp))
107
+ NI = (grad * grad).sum(0)
108
+ NI[NI == 0] = 1
109
+
110
+ rho_0 = image1_warp - reference_image - (grad * flow_current).sum(0)
111
+
112
+ for _ in range(num_iter):
113
+ # Data term
114
+
115
+ rho = rho_0 + (grad * flow_current).sum(0)
116
+
117
+ idx = abs(rho) <= f0 * NI
118
+
119
+ flow_auxiliary = flow_current
120
+
121
+ flow_auxiliary[:, idx] -= rho[idx] * grad[:, idx] / NI[idx]
122
+
123
+ idx = ~idx
124
+ srho = f0 * np.sign(rho[idx])
125
+ flow_auxiliary[:, idx] -= srho * grad[:, idx]
126
+
127
+ # Regularization term
128
+ flow_current = flow_auxiliary.copy()
129
+
130
+ for idx in range(reference_image.ndim):
131
+ s_p[0] = idx
132
+ for _ in range(reg_num_iter):
133
+ for ax in range(reference_image.ndim):
134
+ s_g[0] = ax
135
+ s_g[ax + 1] = slice(0, -1)
136
+ g[tuple(s_g)] = np.diff(flow_current[idx], axis=ax)
137
+ s_g[ax + 1] = slice(None)
138
+
139
+ norm = np.sqrt((g**2).sum(0))[np.newaxis, ...]
140
+ norm *= f1
141
+ norm += 1.0
142
+ proj[idx] -= dt * g
143
+ proj[idx] /= norm
144
+
145
+ # d will be the (negative) divergence of proj[idx]
146
+ d = -proj[idx].sum(0)
147
+ for ax in range(reference_image.ndim):
148
+ s_p[1] = ax
149
+ s_p[ax + 2] = slice(0, -1)
150
+ s_d[ax] = slice(1, None)
151
+ d[tuple(s_d)] += proj[tuple(s_p)]
152
+ s_p[ax + 2] = slice(None)
153
+ s_d[ax] = slice(None)
154
+
155
+ flow_current[idx] = flow_auxiliary[idx] + d
156
+
157
+ flow_previous -= flow_current # The difference as stopping criteria
158
+ if (flow_previous * flow_previous).sum() < tol:
159
+ break
160
+
161
+ flow_previous = flow_current
162
+
163
+ return flow_current
164
+
165
+
166
+ def optical_flow_tvl1(
167
+ reference_image,
168
+ moving_image,
169
+ *,
170
+ attachment=15,
171
+ tightness=0.3,
172
+ num_warp=5,
173
+ num_iter=10,
174
+ tol=1e-4,
175
+ prefilter=False,
176
+ dtype=np.float32,
177
+ ):
178
+ r"""Coarse to fine optical flow estimator.
179
+
180
+ The TV-L1 solver is applied at each level of the image
181
+ pyramid. TV-L1 is a popular algorithm for optical flow estimation
182
+ introduced by Zack et al. [1]_, improved in [2]_ and detailed in [3]_.
183
+
184
+ Parameters
185
+ ----------
186
+ reference_image : ndarray, shape (M, N[, P[, ...]])
187
+ The first grayscale image of the sequence.
188
+ moving_image : ndarray, shape (M, N[, P[, ...]])
189
+ The second grayscale image of the sequence.
190
+ attachment : float, optional
191
+ Attachment parameter (:math:`\lambda` in [1]_). The smaller
192
+ this parameter is, the smoother the returned result will be.
193
+ tightness : float, optional
194
+ Tightness parameter (:math:`\theta` in [1]_). It should have
195
+ a small value in order to maintain attachment and
196
+ regularization parts in correspondence.
197
+ num_warp : int, optional
198
+ Number of times moving_image is warped.
199
+ num_iter : int, optional
200
+ Number of fixed point iteration.
201
+ tol : float, optional
202
+ Tolerance used as stopping criterion based on the L² distance
203
+ between two consecutive values of (u, v).
204
+ prefilter : bool, optional
205
+ Whether to prefilter the estimated optical flow before each
206
+ image warp. When True, a median filter with window size 3
207
+ along each axis is applied. This helps to remove potential
208
+ outliers.
209
+ dtype : dtype, optional
210
+ Output data type: must be floating point. Single precision
211
+ provides good results and saves memory usage and computation
212
+ time compared to double precision.
213
+
214
+ Returns
215
+ -------
216
+ flow : ndarray, shape (image0.ndim, M, N[, P[, ...]])
217
+ The estimated optical flow components for each axis.
218
+
219
+ Notes
220
+ -----
221
+ Color images are not supported.
222
+
223
+ References
224
+ ----------
225
+ .. [1] Zach, C., Pock, T., & Bischof, H. (2007, September). A
226
+ duality based approach for realtime TV-L 1 optical flow. In Joint
227
+ pattern recognition symposium (pp. 214-223). Springer, Berlin,
228
+ Heidelberg. :DOI:`10.1007/978-3-540-74936-3_22`
229
+ .. [2] Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers,
230
+ D. (2009). An improved algorithm for TV-L 1 optical flow. In
231
+ Statistical and geometrical approaches to visual motion analysis
232
+ (pp. 23-45). Springer, Berlin, Heidelberg.
233
+ :DOI:`10.1007/978-3-642-03061-1_2`
234
+ .. [3] Pérez, J. S., Meinhardt-Llopis, E., & Facciolo,
235
+ G. (2013). TV-L1 optical flow estimation. Image Processing On
236
+ Line, 2013, 137-150. :DOI:`10.5201/ipol.2013.26`
237
+
238
+ Examples
239
+ --------
240
+ >>> from skimage.color import rgb2gray
241
+ >>> from skimage.data import stereo_motorcycle
242
+ >>> from skimage.registration import optical_flow_tvl1
243
+ >>> image0, image1, disp = stereo_motorcycle()
244
+ >>> # --- Convert the images to gray level: color is not supported.
245
+ >>> image0 = rgb2gray(image0)
246
+ >>> image1 = rgb2gray(image1)
247
+ >>> flow = optical_flow_tvl1(image1, image0)
248
+
249
+ """
250
+
251
+ solver = partial(
252
+ _tvl1,
253
+ attachment=attachment,
254
+ tightness=tightness,
255
+ num_warp=num_warp,
256
+ num_iter=num_iter,
257
+ tol=tol,
258
+ prefilter=prefilter,
259
+ )
260
+
261
+ if np.dtype(dtype) != _supported_float_type(dtype):
262
+ msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'"
263
+ raise ValueError(msg)
264
+
265
+ return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype)
266
+
267
+
268
+ def _ilk(reference_image, moving_image, flow0, radius, num_warp, gaussian, prefilter):
269
+ """Iterative Lucas-Kanade (iLK) solver for optical flow estimation.
270
+
271
+ Parameters
272
+ ----------
273
+ reference_image : ndarray, shape (M, N[, P[, ...]])
274
+ The first grayscale image of the sequence.
275
+ moving_image : ndarray, shape (M, N[, P[, ...]])
276
+ The second grayscale image of the sequence.
277
+ flow0 : ndarray, shape (reference_image.ndim, M, N[, P[, ...]])
278
+ Initialization for the vector field.
279
+ radius : int
280
+ Radius of the window considered around each pixel.
281
+ num_warp : int
282
+ Number of times moving_image is warped.
283
+ gaussian : bool
284
+ if True, a gaussian kernel is used for the local
285
+ integration. Otherwise, a uniform kernel is used.
286
+ prefilter : bool
287
+ Whether to prefilter the estimated optical flow before each
288
+ image warp. This helps to remove potential outliers.
289
+
290
+ Returns
291
+ -------
292
+ flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]])
293
+ The estimated optical flow components for each axis.
294
+
295
+ """
296
+ dtype = reference_image.dtype
297
+ ndim = reference_image.ndim
298
+ size = 2 * radius + 1
299
+
300
+ if gaussian:
301
+ sigma = ndim * (size / 4,)
302
+ filter_func = partial(gaussian_filter, sigma=sigma, mode='mirror')
303
+ else:
304
+ filter_func = partial(ndi.uniform_filter, size=ndim * (size,), mode='mirror')
305
+
306
+ flow = flow0
307
+ # For each pixel location (i, j), the optical flow X = flow[:, i, j]
308
+ # is the solution of the ndim x ndim linear system
309
+ # A[i, j] * X = b[i, j]
310
+ A = np.zeros(reference_image.shape + (ndim, ndim), dtype=dtype)
311
+ b = np.zeros(reference_image.shape + (ndim, 1), dtype=dtype)
312
+
313
+ grid = np.meshgrid(
314
+ *[np.arange(n, dtype=dtype) for n in reference_image.shape],
315
+ indexing='ij',
316
+ sparse=True,
317
+ )
318
+
319
+ for _ in range(num_warp):
320
+ if prefilter:
321
+ flow = ndi.median_filter(flow, (1,) + ndim * (3,))
322
+
323
+ moving_image_warp = warp(
324
+ moving_image, _get_warp_points(grid, flow), mode='edge'
325
+ )
326
+ grad = np.stack(np.gradient(moving_image_warp), axis=0)
327
+ error_image = (grad * flow).sum(axis=0) + reference_image - moving_image_warp
328
+
329
+ # Local linear systems creation
330
+ for i, j in combinations_with_replacement(range(ndim), 2):
331
+ A[..., i, j] = A[..., j, i] = filter_func(grad[i] * grad[j])
332
+
333
+ for i in range(ndim):
334
+ b[..., i, 0] = filter_func(grad[i] * error_image)
335
+
336
+ # Don't consider badly conditioned linear systems
337
+ idx = abs(np.linalg.det(A)) < 1e-14
338
+ A[idx] = np.eye(ndim, dtype=dtype)
339
+ b[idx] = 0
340
+
341
+ # Solve the local linear systems
342
+ flow = np.moveaxis(np.linalg.solve(A, b)[..., 0], ndim, 0)
343
+
344
+ return flow
345
+
346
+
347
+ def optical_flow_ilk(
348
+ reference_image,
349
+ moving_image,
350
+ *,
351
+ radius=7,
352
+ num_warp=10,
353
+ gaussian=False,
354
+ prefilter=False,
355
+ dtype=np.float32,
356
+ ):
357
+ """Coarse to fine optical flow estimator.
358
+
359
+ The iterative Lucas-Kanade (iLK) solver is applied at each level
360
+ of the image pyramid. iLK [1]_ is a fast and robust alternative to
361
+ TVL1 algorithm although less accurate for rendering flat surfaces
362
+ and object boundaries (see [2]_).
363
+
364
+ Parameters
365
+ ----------
366
+ reference_image : ndarray, shape (M, N[, P[, ...]])
367
+ The first grayscale image of the sequence.
368
+ moving_image : ndarray, shape (M, N[, P[, ...]])
369
+ The second grayscale image of the sequence.
370
+ radius : int, optional
371
+ Radius of the window considered around each pixel.
372
+ num_warp : int, optional
373
+ Number of times moving_image is warped.
374
+ gaussian : bool, optional
375
+ If True, a Gaussian kernel is used for the local
376
+ integration. Otherwise, a uniform kernel is used.
377
+ prefilter : bool, optional
378
+ Whether to prefilter the estimated optical flow before each
379
+ image warp. When True, a median filter with window size 3
380
+ along each axis is applied. This helps to remove potential
381
+ outliers.
382
+ dtype : dtype, optional
383
+ Output data type: must be floating point. Single precision
384
+ provides good results and saves memory usage and computation
385
+ time compared to double precision.
386
+
387
+ Returns
388
+ -------
389
+ flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]])
390
+ The estimated optical flow components for each axis.
391
+
392
+ Notes
393
+ -----
394
+ - The implemented algorithm is described in **Table2** of [1]_.
395
+ - Color images are not supported.
396
+
397
+ References
398
+ ----------
399
+ .. [1] Le Besnerais, G., & Champagnat, F. (2005, September). Dense
400
+ optical flow by iterative local window registration. In IEEE
401
+ International Conference on Image Processing 2005 (Vol. 1,
402
+ pp. I-137). IEEE. :DOI:`10.1109/ICIP.2005.1529706`
403
+ .. [2] Plyer, A., Le Besnerais, G., & Champagnat,
404
+ F. (2016). Massively parallel Lucas Kanade optical flow for
405
+ real-time video processing applications. Journal of Real-Time
406
+ Image Processing, 11(4), 713-730. :DOI:`10.1007/s11554-014-0423-0`
407
+
408
+ Examples
409
+ --------
410
+ >>> from skimage.color import rgb2gray
411
+ >>> from skimage.data import stereo_motorcycle
412
+ >>> from skimage.registration import optical_flow_ilk
413
+ >>> reference_image, moving_image, disp = stereo_motorcycle()
414
+ >>> # --- Convert the images to gray level: color is not supported.
415
+ >>> reference_image = rgb2gray(reference_image)
416
+ >>> moving_image = rgb2gray(moving_image)
417
+ >>> flow = optical_flow_ilk(moving_image, reference_image)
418
+
419
+ """
420
+
421
+ solver = partial(
422
+ _ilk, radius=radius, num_warp=num_warp, gaussian=gaussian, prefilter=prefilter
423
+ )
424
+
425
+ if np.dtype(dtype) != _supported_float_type(dtype):
426
+ msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'"
427
+ raise ValueError(msg)
428
+
429
+ return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype)