diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca83864bc3ec04db58e87f782ad6a64130d07af9 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/_dependency_checks.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/_dependency_checks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12a9abc8f86d01f810d19e4aef42fce6c337d8fb Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/_dependency_checks.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/_geometry.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/_geometry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27049c80268f8e9c80ea52cb5cef14301fc864f8 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/_geometry.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/_tempfile.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/_tempfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6243a6f9a6724ba0e9337f3f5a52f4f12a87bcf5 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/_tempfile.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/_warnings.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/_warnings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb70fe23cac818782eda2c7bfe5cb8e0ca83691 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/_warnings.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/compat.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42c69d61fcee909433ee92a00a5ad709f37dd2bf Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/compat.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/coord.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/coord.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83387a095f322dc1c01e9cd531e058c4eda64380 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/coord.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/dtype.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/dtype.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7264d13a1f9f297b5da245a4767e372db4344fc8 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/dtype.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/filters.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a2fc3a84faef654dad883a873b3d9d14ccf733 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/filters.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/tester.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/tester.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0aad682afdbc10b0ed3ae660f96c156b457b1b32 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/tester.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/testing.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..061b4657648d2e0b5071e5b09da953d3061d88d7 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/testing.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/utils.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f151e053a85f3621bfb0cc85bd9c8f1acc921d16 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/utils.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/__pycache__/version_requirements.cpython-311.pyc b/envs/kitoverlay/skimage/_shared/__pycache__/version_requirements.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..928fb1a94841c4a02e4bf0c9965fc70870fdd8c3 Binary files /dev/null and b/envs/kitoverlay/skimage/_shared/__pycache__/version_requirements.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_shared/_dependency_checks.py b/envs/kitoverlay/skimage/_shared/_dependency_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2cb660e5dddbff22b6ee859c3f214c4d484e82 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/_dependency_checks.py @@ -0,0 +1,7 @@ +from .version_requirements import is_installed +import sys +import platform + +has_mpl = is_installed("matplotlib", ">=3.3") + +is_wasm = (sys.platform == "emscripten") or (platform.machine() in ["wasm32", "wasm64"]) diff --git a/envs/kitoverlay/skimage/_shared/_warnings.py b/envs/kitoverlay/skimage/_shared/_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..73af960073cf31f0dd8714fc4bb501a0bf8f3e49 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/_warnings.py @@ -0,0 +1,149 @@ +from contextlib import contextmanager +import sys +import warnings +import re +import functools +import os + +__all__ = ['all_warnings', 'expected_warnings', 'warn'] + + +# A version of `warnings.warn` with a default stacklevel of 2. +# functool is used so as not to increase the call stack accidentally +warn = functools.partial(warnings.warn, stacklevel=2) + + +@contextmanager +def all_warnings(): + """ + Context for use in testing to ensure that all warnings are raised. + + Examples + -------- + >>> import warnings + >>> def foo(): + ... warnings.warn(RuntimeWarning("bar"), stacklevel=2) + + We raise the warning once, while the warning filter is set to "once". + Hereafter, the warning is invisible, even with custom filters: + + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('once') + ... foo() # doctest: +SKIP + + We can now run ``foo()`` without a warning being raised: + + >>> from numpy.testing import assert_warns + >>> foo() # doctest: +SKIP + + To catch the warning, we call in the help of ``all_warnings``: + + >>> with all_warnings(): + ... assert_warns(RuntimeWarning, foo) + """ + # _warnings.py is on the critical import path. + # Since this is a testing only function, we lazy import inspect. + import inspect + + # Whenever a warning is triggered, Python adds a __warningregistry__ + # member to the *calling* module. The exercise here is to find + # and eradicate all those breadcrumbs that were left lying around. + # + # We proceed by first searching all parent calling frames and explicitly + # clearing their warning registries (necessary for the doctests above to + # pass). Then, we search for all submodules of skimage and clear theirs + # as well (necessary for the skimage test suite to pass). + + frame = inspect.currentframe() + if frame: + for f in inspect.getouterframes(frame): + f[0].f_locals['__warningregistry__'] = {} + del frame + + for mod_name, mod in list(sys.modules.items()): + try: + mod.__warningregistry__.clear() + except AttributeError: + pass + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + yield w + + +@contextmanager +def expected_warnings(matching): + r"""Context for use in testing to catch known warnings matching regexes + + Parameters + ---------- + matching : None or a list of strings or compiled regexes + Regexes for the desired warning to catch + If matching is None, this behaves as a no-op. + + Examples + -------- + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> image = rng.integers(0, 2**16, size=(100, 100), dtype=np.uint16) + >>> # rank filters are slow when bit-depth exceeds 10 bits + >>> from skimage import filters + >>> with expected_warnings(['Bad rank filter performance']): + ... median_filtered = filters.rank.median(image) + + Notes + ----- + Uses `all_warnings` to ensure all warnings are raised. + Upon exiting, it checks the recorded warnings for the desired matching + pattern(s). + Raises a ValueError if any match was not found or an unexpected + warning was raised. + Allows for three types of behaviors: `and`, `or`, and `optional` matches. + This is done to accommodate different build environments or loop conditions + that may produce different warnings. The behaviors can be combined. + If you pass multiple patterns, you get an orderless `and`, where all of the + warnings must be raised. + If you use the `|` operator in a pattern, you can catch one of several + warnings. + Finally, you can use `|\A\Z` in a pattern to signify it as optional. + + """ + if isinstance(matching, str): + raise ValueError( + '``matching`` should be a list of strings and not a string itself.' + ) + + # Special case for disabling the context manager + if matching is None: + yield None + return + + strict_warnings = os.environ.get('SKIMAGE_TEST_STRICT_WARNINGS', '1') + if strict_warnings.lower() == 'true': + strict_warnings = True + elif strict_warnings.lower() == 'false': + strict_warnings = False + else: + strict_warnings = bool(int(strict_warnings)) + + with all_warnings() as w: + # enter context + yield w + # exited user context, check the recorded warnings + # Allow users to provide None + while None in matching: + matching.remove(None) + remaining = [m for m in matching if r'\A\Z' not in m.split('|')] + for warn in w: + found = False + for match in matching: + if re.search(match, str(warn.message)) is not None: + found = True + if match in remaining: + remaining.remove(match) + if strict_warnings and not found: + raise ValueError(f'Unexpected warning: {str(warn.message)}') + if strict_warnings and (len(remaining) > 0): + newline = "\n" + msg = f"No warning raised matching:{newline}{newline.join(remaining)}" + raise ValueError(msg) diff --git a/envs/kitoverlay/skimage/_shared/compat.py b/envs/kitoverlay/skimage/_shared/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..a669d0749fdd5db0a542464eeb97dd107d5d7f58 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/compat.py @@ -0,0 +1,32 @@ +"""Compatibility helpers for dependencies.""" + +from packaging.version import parse + +import numpy as np +import scipy as sp + + +__all__ = [ + "NP_COPY_IF_NEEDED", + "SCIPY_CG_TOL_PARAM_NAME", +] + + +NUMPY_LT_2_0_0 = parse(np.__version__) < parse('2.0.0.dev0') + +# With NumPy 2.0.0, `copy=False` now raises a ValueError if the copy cannot be +# made. The previous behavior to only copy if needed is provided with `copy=None`. +# During the transition period, use this symbol instead. +# Remove once NumPy 2.0.0 is the minimal required version. +# https://numpy.org/devdocs/release/2.0.0-notes.html#new-copy-keyword-meaning-for-array-and-asarray-constructors +# https://github.com/numpy/numpy/pull/25168 +NP_COPY_IF_NEEDED = False if NUMPY_LT_2_0_0 else None + + +SCIPY_LT_1_12 = parse(sp.__version__) < parse('1.12') + +# Starting in SciPy v1.12, 'scipy.sparse.linalg.cg' keyword argument `tol` is +# deprecated in favor of `rtol`. +SCIPY_CG_TOL_PARAM_NAME = "tol" if SCIPY_LT_1_12 else "rtol" + +SCIPY_GE_1_17_0_DEV0 = parse('1.17.0.dev0') <= parse(sp.__version__) diff --git a/envs/kitoverlay/skimage/_shared/dtype.py b/envs/kitoverlay/skimage/_shared/dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..6aed88c21b12bf527d66eadd68f34bbe503f243f --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/dtype.py @@ -0,0 +1,73 @@ +import numpy as np + +# Define classes of supported dtypes and Python scalar types +# Variables ending in `_dtypes` only contain numpy.dtypes of the respective +# class; variables ending in `_types` additionally include Python scalar types. +signed_integer_dtypes = {np.int8, np.int16, np.int32, np.int64} +signed_integer_types = signed_integer_dtypes | {int} + +unsigned_integer_dtypes = {np.uint8, np.uint16, np.uint32, np.uint64} + +integer_dtypes = signed_integer_dtypes | unsigned_integer_dtypes +integer_types = signed_integer_types | unsigned_integer_dtypes + +floating_dtypes = {np.float16, np.float32, np.float64} +floating_types = floating_dtypes | {float} + +complex_dtypes = {np.complex64, np.complex128} +complex_types = complex_dtypes | {complex} + +inexact_dtypes = floating_dtypes | complex_dtypes +inexact_types = floating_types | complex_types + +bool_types = {np.dtype(bool), bool} + +numeric_dtypes = integer_dtypes | inexact_dtypes | {np.bool_} +numeric_types = integer_types | inexact_types | bool_types + + +def numeric_dtype_min_max(dtype): + """Return minimum and maximum representable value for a given dtype. + + A convenient wrapper around `numpy.finfo` and `numpy.iinfo` that + additionally supports numpy.bool as well. + + Parameters + ---------- + dtype : numpy.dtype + The dtype. Tries to convert Python "types" such as int or float, to + the corresponding NumPy dtype. + + Returns + ------- + min, max : number + Minimum and maximum of the given `dtype`. These scalars are themselves + of the given `dtype`. + + Examples + -------- + >>> import numpy as np + >>> numeric_dtype_min_max(np.uint8) + (0, 255) + >>> numeric_dtype_min_max(bool) + (False, True) + >>> numeric_dtype_min_max(np.float64) + (-1.7976931348623157e+308, 1.7976931348623157e+308) + >>> numeric_dtype_min_max(int) + (-9223372036854775808, 9223372036854775807) + """ + dtype = np.dtype(dtype) + if np.issubdtype(dtype, np.integer): + info = np.iinfo(dtype) + min_ = dtype.type(info.min) + max_ = dtype.type(info.max) + elif np.issubdtype(dtype, np.inexact): + info = np.finfo(dtype) + min_ = info.min + max_ = info.max + elif np.issubdtype(dtype, np.dtype(bool)): + min_ = dtype.type(False) + max_ = dtype.type(True) + else: + raise ValueError(f"unsupported dtype {dtype!r}") + return min_, max_ diff --git a/envs/kitoverlay/skimage/_shared/fast_exp.h b/envs/kitoverlay/skimage/_shared/fast_exp.h new file mode 100644 index 0000000000000000000000000000000000000000..fae57fde5f13d797163cccf906ad6130269e0353 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/fast_exp.h @@ -0,0 +1,47 @@ +/* A fast approximation of the exponential function. + * Reference [1]: https://schraudolph.org/pubs/Schraudolph99.pdf + * Reference [2]: https://doi.org/10.1162/089976600300015033 + * Additional improvements by Leonid Bloch. */ + +#include + +/* use just EXP_A = 1512775 for integer version, to avoid FP calculations */ +#define EXP_A (1512775.3951951856938) /* 2^20/ln2 */ +/* For min. RMS error */ +#define EXP_BC 1072632447 /* 1023*2^20 - 60801 */ +/* For min. max. relative error */ +/* #define EXP_BC 1072647449 */ /* 1023*2^20 - 45799 */ +/* For min. mean relative error */ +/* #define EXP_BC 1072625005 */ /* 1023*2^20 - 68243 */ + +__inline double _fast_exp (double y) +{ + union + { + double d; + struct { int32_t i, j; } n; + char t[8]; + } _eco; + + _eco.n.i = 1; + + switch(_eco.t[0]) { + case 1: + /* Little endian */ + _eco.n.j = (int32_t)(EXP_A*(y)) + EXP_BC; + _eco.n.i = 0; + break; + case 0: + /* Big endian */ + _eco.n.i = (int32_t)(EXP_A*(y)) + EXP_BC; + _eco.n.j = 0; + break; + } + + return _eco.d; +} + +__inline float _fast_expf (float y) +{ + return (float)_fast_exp((double)y); +} diff --git a/envs/kitoverlay/skimage/_shared/filters.py b/envs/kitoverlay/skimage/_shared/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..88a6cb7af1f468dd6334f3b71c22c6c6b75d96f5 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/filters.py @@ -0,0 +1,136 @@ +"""Filters used across multiple skimage submodules. + +These are defined here to avoid circular imports. + +The unit tests remain under skimage/filters/tests/ +""" + +from collections.abc import Iterable + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import ( + _supported_float_type, + convert_to_float, +) + + +def gaussian( + image, + sigma=1.0, + *, + mode='nearest', + cval=0, + preserve_range=False, + truncate=4.0, + channel_axis=None, + out=None, +): + """Multi-dimensional Gaussian filter. + + Parameters + ---------- + image : ndarray + Input image (grayscale or color) to filter. + sigma : scalar or sequence of scalars, optional + Standard deviation for Gaussian kernel. The standard + deviations of the Gaussian filter are given for each axis as a + sequence, or as a single number, in which case it is equal for + all axes. + mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The ``mode`` parameter determines how the array borders are + handled, where ``cval`` is the value when mode is equal to + 'constant'. Default is 'nearest'. + cval : scalar, optional + Value to fill past edges of input if ``mode`` is 'constant'. Default + is 0.0 + preserve_range : bool, optional + If True, keep the original range of values. Otherwise, the input + ``image`` is converted according to the conventions of ``img_as_float`` + (Normalized first to values [-1.0 ; 1.0] or [0 ; 1.0] depending on + dtype of input) + + For more information, see: + https://scikit-image.org/docs/dev/user_guide/data_types.html + truncate : float, optional + Truncate the filter at this many standard deviations. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + `channel_axis` was added in 0.19. + out : ndarray, optional + If given, the filtered image will be stored in this array. + + .. versionadded:: 0.23 + `out` was added in 0.23. + + Returns + ------- + filtered_image : ndarray + the filtered array + + Notes + ----- + This function is a wrapper around :func:`scipy.ndimage.gaussian_filter`. + + Integer arrays are converted to float. + + `out` should be of floating-point data type since `gaussian` converts the + input `image` to float. If `out` is not provided, another array + will be allocated and returned as the result. + + The multi-dimensional filter is implemented as a sequence of + one-dimensional convolution filters. The intermediate arrays are + stored in the same data type as the output. Therefore, for output + types with a limited precision, the results may be imprecise + because intermediate results may be stored with insufficient + precision. + + Examples + -------- + >>> import skimage as ski + >>> a = np.zeros((3, 3)) + >>> a[1, 1] = 1 + >>> a + array([[0., 0., 0.], + [0., 1., 0.], + [0., 0., 0.]]) + >>> ski.filters.gaussian(a, sigma=0.4) # mild smoothing + array([[0.00163116, 0.03712502, 0.00163116], + [0.03712502, 0.84496158, 0.03712502], + [0.00163116, 0.03712502, 0.00163116]]) + >>> ski.filters.gaussian(a, sigma=1) # more smoothing + array([[0.05855018, 0.09653293, 0.05855018], + [0.09653293, 0.15915589, 0.09653293], + [0.05855018, 0.09653293, 0.05855018]]) + >>> # Several modes are possible for handling boundaries + >>> ski.filters.gaussian(a, sigma=1, mode='reflect') + array([[0.08767308, 0.12075024, 0.08767308], + [0.12075024, 0.16630671, 0.12075024], + [0.08767308, 0.12075024, 0.08767308]]) + >>> # For RGB images, each is filtered separately + >>> image = ski.data.astronaut() + >>> filtered_img = ski.filters.gaussian(image, sigma=1, channel_axis=-1) + + """ + if np.any(np.asarray(sigma) < 0.0): + raise ValueError("Sigma values less than zero are not valid") + if channel_axis is not None: + # do not filter across channels + if not isinstance(sigma, Iterable): + sigma = [sigma] * (image.ndim - 1) + if len(sigma) == image.ndim - 1: + sigma = list(sigma) + sigma.insert(channel_axis % image.ndim, 0) + image = convert_to_float(image, preserve_range) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if (out is not None) and (not np.issubdtype(out.dtype, np.floating)): + raise ValueError(f"dtype of `out` must be float; got {out.dtype!r}.") + return ndi.gaussian_filter( + image, sigma, output=out, mode=mode, cval=cval, truncate=truncate + ) diff --git a/envs/kitoverlay/skimage/_shared/testing.py b/envs/kitoverlay/skimage/_shared/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..9e76bbf87400fcc91df5173e8bdc4c7f0cc0d8b4 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/testing.py @@ -0,0 +1,327 @@ +""" +Testing utilities. +""" + +import os +import platform +import re +import struct +import sys +import functools +import inspect +from tempfile import NamedTemporaryFile + +import numpy as np +from numpy import testing +from numpy.testing import ( + TestCase, + assert_, + assert_warns, + assert_no_warnings, + assert_equal, + assert_almost_equal, + assert_array_equal, + assert_allclose, + assert_array_almost_equal, + assert_array_almost_equal_nulp, + assert_array_less, +) + +from .. import data, io +from ..data._fetchers import _fetch +from ..util import img_as_uint, img_as_float, img_as_int, img_as_ubyte +from ._warnings import expected_warnings +from ._dependency_checks import is_wasm + +import pytest + + +skipif = pytest.mark.skipif +xfail = pytest.mark.xfail +parametrize = pytest.mark.parametrize +raises = pytest.raises +fixture = pytest.fixture + +SKIP_RE = re.compile(r"(\s*>>>.*?)(\s*)#\s*skip\s+if\s+(.*)$") + +# true if python is running in 32bit mode +# Calculate the size of a void * pointer in bits +# https://docs.python.org/3/library/struct.html +arch32 = struct.calcsize("P") * 8 == 32 + + +def assert_less(a, b, msg=None): + message = f"{a!r} is not lower than {b!r}" + if msg is not None: + message += ": " + msg + assert a < b, message + + +def assert_greater(a, b, msg=None): + message = f"{a!r} is not greater than {b!r}" + if msg is not None: + message += ": " + msg + assert a > b, message + + +def doctest_skip_parser(func): + """Decorator replaces custom skip test markup in doctests + + Say a function has a docstring:: + + >>> something, HAVE_AMODULE, HAVE_BMODULE = 0, False, False + >>> something # skip if not HAVE_AMODULE + 0 + >>> something # skip if HAVE_BMODULE + 0 + + This decorator will evaluate the expression after ``skip if``. If this + evaluates to True, then the comment is replaced by ``# doctest: +SKIP``. If + False, then the comment is just removed. The expression is evaluated in the + ``globals`` scope of `func`. + + For example, if the module global ``HAVE_AMODULE`` is False, and module + global ``HAVE_BMODULE`` is False, the returned function will have docstring:: + + >>> something # doctest: +SKIP + >>> something + else # doctest: +SKIP + >>> something # doctest: +SKIP + + """ + lines = func.__doc__.split('\n') + new_lines = [] + for line in lines: + match = SKIP_RE.match(line) + if match is None: + new_lines.append(line) + continue + code, space, expr = match.groups() + + try: + # Works as a function decorator + if eval(expr, func.__globals__): + code = code + space + "# doctest: +SKIP" + except AttributeError: + # Works as a class decorator + if eval(expr, func.__init__.__globals__): + code = code + space + "# doctest: +SKIP" + + new_lines.append(code) + func.__doc__ = "\n".join(new_lines) + return func + + +def roundtrip(image, plugin, suffix): + """Save and read an image using a specified plugin""" + if '.' not in suffix: + suffix = '.' + suffix + with NamedTemporaryFile(suffix=suffix, delete=False) as temp_file: + fname = temp_file.name + io.imsave(fname, image, plugin=plugin) + new = io.imread(fname, plugin=plugin) + try: + os.remove(fname) + except Exception: + pass + return new + + +def color_check(plugin, fmt='png'): + """Check roundtrip behavior for color images. + + All major input types should be handled as ubytes and read + back correctly. + """ + img = img_as_ubyte(data.chelsea()) + r1 = roundtrip(img, plugin, fmt) + testing.assert_allclose(img, r1) + + img2 = img > 128 + r2 = roundtrip(img2, plugin, fmt) + testing.assert_allclose(img2, r2.astype(bool)) + + img3 = img_as_float(img) + r3 = roundtrip(img3, plugin, fmt) + testing.assert_allclose(r3, img) + + img4 = img_as_int(img) + if fmt.lower() in (('tif', 'tiff')): + img4 -= 100 + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img4) + else: + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_ubyte(img4)) + + img5 = img_as_uint(img) + r5 = roundtrip(img5, plugin, fmt) + testing.assert_allclose(r5, img) + + +def mono_check(plugin, fmt='png'): + """Check the roundtrip behavior for images that support most types. + + All major input types should be handled. + """ + + img = img_as_ubyte(data.moon()) + r1 = roundtrip(img, plugin, fmt) + testing.assert_allclose(img, r1) + + img2 = img > 128 + r2 = roundtrip(img2, plugin, fmt) + testing.assert_allclose(img2, r2.astype(bool)) + + img3 = img_as_float(img) + r3 = roundtrip(img3, plugin, fmt) + if r3.dtype.kind == 'f': + testing.assert_allclose(img3, r3) + else: + testing.assert_allclose(r3, img_as_uint(img)) + + img4 = img_as_int(img) + if fmt.lower() in (('tif', 'tiff')): + img4 -= 100 + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img4) + else: + r4 = roundtrip(img4, plugin, fmt) + testing.assert_allclose(r4, img_as_uint(img4)) + + img5 = img_as_uint(img) + r5 = roundtrip(img5, plugin, fmt) + testing.assert_allclose(r5, img5) + + +def fetch(data_filename, prefix=None): + """Attempt to fetch data, but if unavailable, skip the tests. + + Parameters + ---------- + data_filename : str + File path in the scikit-image repo tree, e.g., + 'restoration/camera_rl.npy', possibly pointing to a remote location. + + prefix : str, optional + If None, `data_filename` is prefixed by 'src/skimage' + If 'tests', `data_filename` is prefixed by 'tests/skimage'. + + Returns + ------- + file_path : str + Path of the local file, possibly pointing to a remote location. + + """ + try: + return _fetch(data_filename, prefix=prefix) + except (ConnectionError, ModuleNotFoundError): + pytest.skip(f'Unable to download {data_filename}', allow_module_level=True) + + +# Ref: about the lack of threading support in WASM, please see +# https://github.com/pyodide/pyodide/issues/237 +def run_in_parallel(workers=2, warnings_matching=None): + """Decorator to run the same function multiple times in parallel. + + This decorator is useful to ensure that separate threads execute + concurrently and correctly while releasing the GIL. + + It is currently skipped when running on WASM-based platforms, as + the threading module is not supported. + + Parameters + ---------- + workers : int, optional + The number of times the function is run in parallel. + warnings_matching : list or None + This parameter is passed on to `expected_warnings` so as not to have + race conditions with the warnings filters. A single + `expected_warnings` context manager is used for all threads. + If None, then no warnings are checked. + + """ + + assert workers > 0 + + def wrapper(func): + if is_wasm: + # Threading isn't supported on WASM, return early + return func + + import threading + + @functools.wraps(func) + def inner(*args, **kwargs): + with expected_warnings(warnings_matching): + threads = [] + for i in range(workers - 1): + thread = threading.Thread(target=func, args=args, kwargs=kwargs) + threads.append(thread) + for thread in threads: + thread.start() + + func(*args, **kwargs) + + for thread in threads: + thread.join() + + return inner + + return wrapper + + +def assert_stacklevel(warnings, *, offset=-1): + """Assert correct stacklevel of captured warnings. + + When scikit-image raises warnings, the stacklevel should ideally be set + so that the origin of the warnings will point to the public function + that was called by the user and not necessarily the very place where the + warnings were emitted (which may be inside some internal function). + This utility function helps with checking that + the stacklevel was set correctly on warnings captured by `pytest.warns`. + + Parameters + ---------- + warnings : collections.abc.Iterable[warning.WarningMessage] + Warnings that were captured by `pytest.warns`. + offset : int, optional + Offset from the line this function is called to the line were the + warning is supposed to originate from. For multiline calls, the + first line is relevant. Defaults to -1 which corresponds to the line + right above the one where this function is called. + + Raises + ------ + AssertionError + If a warning in `warnings` does not match the expected line number or + file name. + + Examples + -------- + >>> def test_something(): + ... with pytest.warns(UserWarning, match="some message") as record: + ... something_raising_a_warning() + ... assert_stacklevel(record) + ... + >>> def test_another_thing(): + ... with pytest.warns(UserWarning, match="some message") as record: + ... iam_raising_many_warnings( + ... "A long argument that forces the call to wrap." + ... ) + ... assert_stacklevel(record, offset=-3) + """ + __tracebackhide__ = True # Hide traceback for py.test + + frame = inspect.stack()[1].frame # 0 is current frame, 1 is outer frame + line_number = frame.f_lineno + offset + filename = frame.f_code.co_filename + expected = f"{filename}:{line_number}" + for warning in warnings: + actual = f"{warning.filename}:{warning.lineno}" + msg = ( + "Warning with wrong stacklevel:\n" + f" Expected: {expected}\n" + f" Actual: {actual}\n" + f" {warning.category.__name__}: {warning.message}" + ) + assert actual == expected, msg diff --git a/envs/kitoverlay/skimage/_shared/utils.py b/envs/kitoverlay/skimage/_shared/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..02132e75050fad74775862e866ac353ae69858e2 --- /dev/null +++ b/envs/kitoverlay/skimage/_shared/utils.py @@ -0,0 +1,1099 @@ +import functools +import inspect +import sys +import warnings +from contextlib import contextmanager + +import numpy as np + +from ._warnings import all_warnings, warn + +__all__ = [ + 'deprecate_func', + 'get_bound_method_class', + 'all_warnings', + 'safe_as_int', + 'check_shape_equality', + 'check_nD', + 'warn', + 'reshape_nd', + 'identity', + 'slice_at_axis', + "deprecate_parameter", + "DEPRECATED", +] + + +def count_inner_wrappers(func): + """Count the number of inner wrappers by unpacking ``__wrapped__``. + + If a wrapped function wraps another wrapped function, then we refer to the + wrapping of the second function as an *inner wrapper*. + + For example, consider this code fragment: + + .. code-block:: python + @wrap_outer + @wrap_inner + def foo(): + pass + + Here ``@wrap_inner`` applies a wrapper to ``foo``, and ``@wrap_outer`` + applies a wrapper to the result. + + Parameters + ---------- + func : callable + The callable of which to determine the number of inner wrappers. + + Returns + ------- + count : int + The number of times `func` has been wrapped. + + See Also + -------- + count_global_wrappers + """ + unwrapped = func + count = 0 + while hasattr(unwrapped, "__wrapped__"): + unwrapped = unwrapped.__wrapped__ + count += 1 + return count + + +def _warning_stacklevel(func): + """Find stacklevel of `func` relative to its global representation. + + Determine automatically with which stacklevel a warning should be raised. + + Parameters + ---------- + func : Callable + Tries to find the global version of `func` and counts the number of + additional wrappers around `func`. + + Returns + ------- + stacklevel : int + The stacklevel. Minimum of 2. + """ + # Count number of wrappers around `func` + inner_wrapped_count = count_inner_wrappers(func) + global_wrapped_count = count_global_wrappers(func) + + stacklevel = global_wrapped_count - inner_wrapped_count + 1 + return max(stacklevel, 2) + + +def count_global_wrappers(func): + """Count the total number of times a function as been wrapped globally. + + Similar to :func:`count_inner_wrappers`, this counts the number of times + `func` has been wrapped. However, this function doesn't start counting + from `func` but instead tries to access the "global representation" of + `func`. This means that you could use this function from inside a wrapper + that was applied first, and still count wrappers that were applied on + top of it afterwards. + + E.g., `func` might be wrapped by multiple decorators that emit + warnings. In that case, calling this function in the inner-most decorator + will still return the total count of wrappers. + + Parameters + ---------- + func : callable + The callable of which to determine the number of wrappers. Can be a + function or method of a class. + + Returns + ------- + count : int + The number of times `func` has been wrapped. + + See Also + -------- + count_inner_wrappers + """ + if "" in func.__qualname__: + msg = ( + "Cannot determine stacklevel of a function defined in another " + "function's local namespace. Set the stacklevel manually." + ) + raise ValueError(msg) + + first_name, *other = func.__qualname__.split(".") + global_func = func.__globals__.get(first_name, func) + + # Account for `func` being a method, in which case it's an attribute of + # what we got from `func.__globals__` + for part in other: + global_func = getattr(global_func, part, global_func) + + count = count_inner_wrappers(global_func) + assert count >= 0 + return count + + +class change_default_value: + """Decorator for changing the default value of an argument. + + Parameters + ---------- + arg_name : str + The name of the argument to be updated. + new_value : any + The argument new value. + changed_version : str + The package version in which the change will be introduced. + warning_msg : str + Optional warning message. If None, a generic warning message + is used. + stacklevel : {None, int}, optional + If None, the decorator attempts to detect the appropriate stacklevel for the + deprecation warning automatically. This can fail, e.g., due to + decorating a closure, in which case you can set the stacklevel manually + here. The outermost decorator should have stacklevel 2, the next inner + one stacklevel 3, etc. + """ + + def __init__( + self, arg_name, *, new_value, changed_version, warning_msg=None, stacklevel=None + ): + self.arg_name = arg_name + self.new_value = new_value + self.warning_msg = warning_msg + self.changed_version = changed_version + self.stacklevel = stacklevel + + def __call__(self, func): + parameters = inspect.signature(func).parameters + arg_idx = list(parameters.keys()).index(self.arg_name) + old_value = parameters[self.arg_name].default + + if self.warning_msg is None: + self.warning_msg = ( + f'The new recommended value for {self.arg_name} is ' + f'{self.new_value}. Until version {self.changed_version}, ' + f'the default {self.arg_name} value is {old_value}. ' + f'From version {self.changed_version}, the {self.arg_name} ' + f'default value will be {self.new_value}. To avoid ' + f'this warning, please explicitly set {self.arg_name} value.' + ) + + @functools.wraps(func) + def fixed_func(*args, **kwargs): + if len(args) < arg_idx + 1 and self.arg_name not in kwargs.keys(): + stacklevel = ( + self.stacklevel + if self.stacklevel is not None + else _warning_stacklevel(func) + ) + # warn that arg_name default value changed: + warnings.warn(self.warning_msg, FutureWarning, stacklevel=stacklevel) + return func(*args, **kwargs) + + return fixed_func + + +class PatchClassRepr(type): + """Control class representations in rendered signatures.""" + + def __repr__(cls): + return f"<{cls.__name__}>" + + +class DEPRECATED(metaclass=PatchClassRepr): + """Signal value to help with deprecating parameters that use None. + + This is a proxy object, used to signal that a parameter has not been set. + This is useful if ``None`` is already used for a different purpose or just + to highlight a deprecated parameter in the signature. + """ + + +class deprecate_parameter: + """Deprecate a parameter of a function. + + Parameters + ---------- + deprecated_name : str + The name of the deprecated parameter. + start_version : str + The package version in which the warning was introduced. + stop_version : str + The package version in which the warning will be replaced by + an error / the deprecation is completed. + template : str, optional + If given, this message template is used instead of the default one. + new_name : str, optional + If given, the default message will recommend the new parameter name and an + error will be raised if the user uses both old and new names for the + same parameter. + modify_docstring : bool, optional + If the wrapped function has a docstring, add the deprecated parameters + to the "Other Parameters" section. + stacklevel : {None, int}, optional + If None, the decorator attempts to detect the appropriate stacklevel for the + deprecation warning automatically. This can fail, e.g., due to + decorating a closure, in which case you can set the stacklevel manually + here. The outermost decorator should have stacklevel 2, the next inner + one stacklevel 3, etc. + + Notes + ----- + Assign `DEPRECATED` as the new default value for the deprecated parameter. + This marks the status of the parameter also in the signature and rendered + HTML docs. + + This decorator can be stacked to deprecate more than one parameter. + + Examples + -------- + >>> from skimage._shared.utils import deprecate_parameter, DEPRECATED + >>> @deprecate_parameter( + ... "b", new_name="c", start_version="0.1", stop_version="0.3" + ... ) + ... def foo(a, b=DEPRECATED, *, c=None): + ... return a, c + + Calling ``foo(1, b=2)`` will warn with:: + + FutureWarning: Parameter `b` is deprecated since version 0.1 and will + be removed in 0.3 (or later). To avoid this warning, please use the + parameter `c` instead. For more details, see the documentation of + `foo`. + """ + + DEPRECATED = DEPRECATED # Make signal value accessible for convenience + + remove_parameter_template = ( + "Parameter `{deprecated_name}` is deprecated since version " + "{deprecated_version} and will be removed in {changed_version} (or " + "later). To avoid this warning, please do not use the parameter " + "`{deprecated_name}`. For more details, see the documentation of " + "`{func_name}`." + ) + + replace_parameter_template = ( + "Parameter `{deprecated_name}` is deprecated since version " + "{deprecated_version} and will be removed in {changed_version} (or " + "later). To avoid this warning, please use the parameter `{new_name}` " + "instead. For more details, see the documentation of `{func_name}`." + ) + + def __init__( + self, + deprecated_name, + *, + start_version, + stop_version, + template=None, + new_name=None, + modify_docstring=True, + stacklevel=None, + ): + self.deprecated_name = deprecated_name + self.new_name = new_name + self.template = template + self.start_version = start_version + self.stop_version = stop_version + self.modify_docstring = modify_docstring + self.stacklevel = stacklevel + + def __call__(self, func): + parameters = inspect.signature(func).parameters + try: + deprecated_idx = list(parameters.keys()).index(self.deprecated_name) + except ValueError as e: + raise ValueError(f"{self.deprecated_name!r} not in parameters") from e + + new_idx = False + if self.new_name: + try: + new_idx = list(parameters.keys()).index(self.new_name) + except ValueError as e: + raise ValueError(f"{self.new_name!r} not in parameters") from e + + if parameters[self.deprecated_name].default is not DEPRECATED: + raise RuntimeError( + f"Expected `{self.deprecated_name}` to have the value {DEPRECATED!r} " + f"to indicate its status in the rendered signature." + ) + + if self.template is not None: + template = self.template + elif self.new_name is not None: + template = self.replace_parameter_template + else: + template = self.remove_parameter_template + warning_message = template.format( + deprecated_name=self.deprecated_name, + deprecated_version=self.start_version, + changed_version=self.stop_version, + func_name=func.__qualname__, + new_name=self.new_name, + ) + + @functools.wraps(func) + def fixed_func(*args, **kwargs): + deprecated_value = DEPRECATED + new_value = DEPRECATED + + # Extract value of deprecated parameter + if len(args) > deprecated_idx: + deprecated_value = args[deprecated_idx] + # Overwrite old with DEPRECATED if replacement exists + if self.new_name is not None: + args = ( + args[:deprecated_idx] + + (DEPRECATED,) + + args[deprecated_idx + 1 :] + ) + if self.deprecated_name in kwargs.keys(): + deprecated_value = kwargs[self.deprecated_name] + # Overwrite old with DEPRECATED if replacement exists + if self.new_name is not None: + kwargs[self.deprecated_name] = DEPRECATED + + # Extract value of new parameter (if present) + if new_idx is not False and len(args) > new_idx: + new_value = args[new_idx] + if self.new_name and self.new_name in kwargs.keys(): + new_value = kwargs[self.new_name] + + if deprecated_value is not DEPRECATED: + stacklevel = ( + self.stacklevel + if self.stacklevel is not None + else _warning_stacklevel(func) + ) + warnings.warn( + warning_message, category=FutureWarning, stacklevel=stacklevel + ) + + if new_value is not DEPRECATED: + raise ValueError( + f"Both deprecated parameter `{self.deprecated_name}` " + f"and new parameter `{self.new_name}` are used. Use " + f"only the latter to avoid conflicting values." + ) + elif self.new_name is not None: + # Assign old value to new one + kwargs[self.new_name] = deprecated_value + + return func(*args, **kwargs) + + if self.modify_docstring and func.__doc__ is not None: + newdoc = _docstring_add_deprecated( + func, {self.deprecated_name: self.new_name}, self.start_version + ) + fixed_func.__doc__ = newdoc + + return fixed_func + + +def _docstring_add_deprecated(func, kwarg_mapping, deprecated_version): + """Add deprecated kwarg(s) to the "Other Params" section of a docstring. + + Parameters + ---------- + func : function + The function whose docstring we wish to update. + kwarg_mapping : dict + A dict containing {old_arg: new_arg} key/value pairs, see + `deprecate_parameter`. + deprecated_version : str + A major.minor version string specifying when old_arg was + deprecated. + + Returns + ------- + new_doc : str + The updated docstring. Returns the original docstring if numpydoc is + not available. + """ + if func.__doc__ is None: + return None + try: + from numpydoc.docscrape import FunctionDoc, Parameter + except ImportError: + # Return an unmodified docstring if numpydoc is not available. + return func.__doc__ + + Doc = FunctionDoc(func) + for old_arg, new_arg in kwarg_mapping.items(): + desc = [] + if new_arg is None: + desc.append(f'`{old_arg}` is deprecated.') + else: + desc.append(f'Deprecated in favor of `{new_arg}`.') + + desc += ['', f'.. deprecated:: {deprecated_version}'] + Doc['Other Parameters'].append( + Parameter(name=old_arg, type='DEPRECATED', desc=desc) + ) + new_docstring = str(Doc) + + # new_docstring will have a header starting with: + # + # .. function:: func.__name__ + # + # and some additional blank lines. We strip these off below. + split = new_docstring.split('\n') + no_header = split[1:] + while not no_header[0].strip(): + no_header.pop(0) + + # Store the initial description before any of the Parameters fields. + # Usually this is a single line, but the while loop covers any case + # where it is not. + descr = no_header.pop(0) + while no_header[0].strip(): + descr += '\n ' + no_header.pop(0) + descr += '\n\n' + # '\n ' rather than '\n' here to restore the original indentation. + final_docstring = descr + '\n '.join(no_header) + # strip any extra spaces from ends of lines + final_docstring = '\n'.join([line.rstrip() for line in final_docstring.split('\n')]) + return final_docstring + + +class FailedEstimationAccessError(AttributeError): + """Error from use of failed estimation instance + + This error arises from attempts to use an instance of + :class:`FailedEstimation`. + """ + + +class FailedEstimation: + """Class to indicate a failed transform estimation. + + The ``from_estimate`` class method of each transform type may return an + instance of this class to indicate some failure in the estimation process. + + Parameters + ---------- + message : str + Message indicating reason for failed estimation. + + Attributes + ---------- + message : str + Message above. + + Raises + ------ + FailedEstimationAccessError + Exception raised for missing attributes or if the instance is used as a + callable. + """ + + error_cls = FailedEstimationAccessError + + hint = ( + "You can check for a failed estimation by truth testing the returned " + "object. For failed estimations, `bool(estimation_result)` will be `False`. " + "E.g.\n\n" + " if not estimation_result:\n" + " raise RuntimeError(f'Failed estimation: {estimation_result}')" + ) + + def __init__(self, message): + self.message = message + + def __bool__(self): + return False + + def __repr__(self): + return f"{type(self).__name__}({self.message!r})" + + def __str__(self): + return self.message + + def __call__(self, *args, **kwargs): + msg = ( + f'{type(self).__name__} is not callable. {self.message}\n\n' + f'Hint: {self.hint}' + ) + raise self.error_cls(msg) + + def __getattr__(self, name): + msg = ( + f'{type(self).__name__} has no attribute {name!r}. {self.message}\n\n' + f'Hint: {self.hint}' + ) + raise self.error_cls(msg) + + +@contextmanager +def _ignore_deprecated_estimate_warning(): + """Filter warnings about the deprecated `estimate` method. + + Use either as decorator or context manager. + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + action="ignore", + category=FutureWarning, + message="`estimate` is deprecated", + module="skimage", + ) + yield + + +class channel_as_last_axis: + """Decorator for automatically making channels axis last for all arrays. + + This decorator reorders axes for compatibility with functions that only + support channels along the last axis. After the function call is complete + the channels axis is restored back to its original position. + + Parameters + ---------- + channel_arg_positions : tuple of int, optional + Positional arguments at the positions specified in this tuple are + assumed to be multichannel arrays. The default is to assume only the + first argument to the function is a multichannel array. + channel_kwarg_names : tuple of str, optional + A tuple containing the names of any keyword arguments corresponding to + multichannel arrays. + multichannel_output : bool, optional + A boolean that should be True if the output of the function is not a + multichannel array and False otherwise. This decorator does not + currently support the general case of functions with multiple outputs + where some or all are multichannel. + + """ + + def __init__( + self, + channel_arg_positions=(0,), + channel_kwarg_names=(), + multichannel_output=True, + ): + self.arg_positions = set(channel_arg_positions) + self.kwarg_names = set(channel_kwarg_names) + self.multichannel_output = multichannel_output + + def __call__(self, func): + @functools.wraps(func) + def fixed_func(*args, **kwargs): + channel_axis = kwargs.get('channel_axis', None) + + if channel_axis is None: + return func(*args, **kwargs) + + # TODO: convert scalars to a tuple in anticipation of eventually + # supporting a tuple of channel axes. Right now, only an + # integer or a single-element tuple is supported, though. + if np.isscalar(channel_axis): + channel_axis = (channel_axis,) + if len(channel_axis) > 1: + raise ValueError("only a single channel axis is currently supported") + + if channel_axis == (-1,) or channel_axis == -1: + return func(*args, **kwargs) + + if self.arg_positions: + new_args = [] + for pos, arg in enumerate(args): + if pos in self.arg_positions: + new_args.append(np.moveaxis(arg, channel_axis[0], -1)) + else: + new_args.append(arg) + new_args = tuple(new_args) + else: + new_args = args + + for name in self.kwarg_names: + kwargs[name] = np.moveaxis(kwargs[name], channel_axis[0], -1) + + # now that we have moved the channels axis to the last position, + # change the channel_axis argument to -1 + kwargs["channel_axis"] = -1 + + # Call the function with the fixed arguments + out = func(*new_args, **kwargs) + if self.multichannel_output: + out = np.moveaxis(out, -1, channel_axis[0]) + return out + + return fixed_func + + +class deprecate_func: + """Decorate a deprecated function and warn when it is called. + + Adapted from . + + Parameters + ---------- + deprecated_version : str + The package version when the deprecation was introduced. + removed_version : str + The package version in which the deprecated function will be removed. + hint : str, optional + A hint on how to address this deprecation, + e.g., "Use `skimage.submodule.alternative_func` instead." + stacklevel : {None, int}, optional + If None, the decorator attempts to detect the appropriate stacklevel for the + deprecation warning automatically. This can fail, e.g., due to + decorating a closure, in which case you can set the stacklevel manually + here. The outermost decorator should have stacklevel 2, the next inner + one stacklevel 3, etc. + + Examples + -------- + >>> @deprecate_func( + ... deprecated_version="1.0.0", + ... removed_version="1.2.0", + ... hint="Use `bar` instead." + ... ) + ... def foo(): + ... pass + + Calling ``foo`` will warn with:: + + FutureWarning: `foo` is deprecated since version 1.0.0 + and will be removed in version 1.2.0. Use `bar` instead. + """ + + def __init__( + self, *, deprecated_version, removed_version=None, hint=None, stacklevel=None + ): + self.deprecated_version = deprecated_version + self.removed_version = removed_version + self.hint = hint + self.stacklevel = stacklevel + + def __call__(self, func): + message = ( + f"`{func.__name__}` is deprecated since version {self.deprecated_version}" + ) + if self.removed_version: + message += f" and will be removed in version {self.removed_version}." + if self.hint: + # Prepend space and make sure it closes with "." + message += f" {self.hint.rstrip('.')}." + + @functools.wraps(func) + def wrapped(*args, **kwargs): + stacklevel = ( + self.stacklevel + if self.stacklevel is not None + else _warning_stacklevel(func) + ) + warnings.warn(message, category=FutureWarning, stacklevel=stacklevel) + return func(*args, **kwargs) + + # modify docstring to display deprecation warning + doc = f'**Deprecated:** {message}' + if wrapped.__doc__ is None: + wrapped.__doc__ = doc + else: + wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__ + + return wrapped + + +def _deprecate_estimate(func, class_name=None): + """Deprecate ``estimate`` method.""" + class_name = func.__qualname__.split('.')[0] if class_name is None else class_name + return deprecate_func( + deprecated_version="0.26", + removed_version="2.2", + hint=f"Please use `{class_name}.from_estimate` class constructor instead.", + stacklevel=2, + )(func) + + +def _deprecate_inherited_estimate(cls): + """Deprecate inherited ``estimate`` instance method. + + This needs a class decorator so we can correctly specify the class of the + `from_estimate` class method in the deprecation message. + """ + + def estimate(self, *args, **kwargs): + return self._estimate(*args, **kwargs) is None + + # The inherited method will always be wrapped by deprecator. + inherited_meth = getattr(cls, 'estimate').__wrapped__ + estimate.__doc__ = inherited_meth.__doc__ + estimate.__signature__ = inspect.signature(inherited_meth) + + cls.estimate = _deprecate_estimate(estimate, cls.__name__) + return cls + + +def _update_from_estimate_docstring(cls): + """Fix docstring for inherited ``from_estimate`` class method. + + Even for classes that inherit the `from_estimate` method, and do not + override it, we nevertheless need to change the *docstring* of the + `from_estimate` method to point the user to the current (inheriting) class, + rather than the class in which the method is defined (the inherited class). + + This needs a class decorator so we can modify the docstring of the new + class method. CPython currently does not allow us to modify class method + docstrings by updating ``__doc__``. + """ + + inherited_cmeth = getattr(cls, 'from_estimate') + + def from_estimate(cls, *args, **kwargs): + return inherited_cmeth(*args, **kwargs) + + inherited_class_name = inherited_cmeth.__qualname__.split('.')[-2] + + from_estimate.__doc__ = inherited_cmeth.__doc__.replace( + inherited_class_name, cls.__name__ + ) + from_estimate.__signature__ = inspect.signature(inherited_cmeth) + + cls.from_estimate = classmethod(from_estimate) + return cls + + +def get_bound_method_class(m): + """Return the class for a bound method.""" + return m.im_class if sys.version < '3' else m.__self__.__class__ + + +def safe_as_int(val, atol=1e-3): + """ + Attempt to safely cast values to integer format. + + Parameters + ---------- + val : scalar or iterable of scalars + Number or container of numbers which are intended to be interpreted as + integers, e.g., for indexing purposes, but which may not carry integer + type. + atol : float + Absolute tolerance away from nearest integer to consider values in + ``val`` functionally integers. + + Returns + ------- + val_int : NumPy scalar or ndarray of dtype `np.int64` + Returns the input value(s) coerced to dtype `np.int64` assuming all + were within ``atol`` of the nearest integer. + + Notes + ----- + This operation calculates ``val`` modulo 1, which returns the mantissa of + all values. Then all mantissas greater than 0.5 are subtracted from one. + Finally, the absolute tolerance from zero is calculated. If it is less + than ``atol`` for all value(s) in ``val``, they are rounded and returned + in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is + returned. + + If any value(s) are outside the specified tolerance, an informative error + is raised. + + Examples + -------- + >>> safe_as_int(7.0) + 7 + + >>> safe_as_int([9, 4, 2.9999999999]) + array([9, 4, 3]) + + >>> safe_as_int(53.1) + Traceback (most recent call last): + ... + ValueError: Integer argument required but received 53.1, check inputs. + + >>> safe_as_int(53.01, atol=0.01) + 53 + + """ + mod = np.asarray(val) % 1 # Extract mantissa + + # Check for and subtract any mod values > 0.5 from 1 + if mod.ndim == 0: # Scalar input, cannot be indexed + if mod > 0.5: + mod = 1 - mod + else: # Iterable input, now ndarray + mod[mod > 0.5] = 1 - mod[mod > 0.5] # Test on each side of nearest int + + if not np.allclose(mod, 0, atol=atol): + raise ValueError(f'Integer argument required but received {val}, check inputs.') + + return np.round(val).astype(np.int64) + + +def check_shape_equality(*images): + """Check that all images have the same shape""" + image0 = images[0] + if not all(image0.shape == image.shape for image in images[1:]): + raise ValueError('Input images must have the same dimensions.') + return + + +def slice_at_axis(sl, axis): + """ + Construct tuple of slices to slice an array in the given dimension. + + Parameters + ---------- + sl : slice + The slice for the given dimension. + axis : int + The axis to which `sl` is applied. All other dimensions are left + "unsliced". + + Returns + ------- + sl : tuple of slices + A tuple with slices matching `shape` in length. + + Examples + -------- + >>> slice_at_axis(slice(None, 3, -1), 1) + (slice(None, None, None), slice(None, 3, -1), Ellipsis) + """ + return (slice(None),) * axis + (sl,) + (...,) + + +def reshape_nd(arr, ndim, dim): + """Reshape a 1D array to have n dimensions, all singletons but one. + + Parameters + ---------- + arr : array, shape (N,) + Input array + ndim : int + Number of desired dimensions of reshaped array. + dim : int + Which dimension/axis will not be singleton-sized. + + Returns + ------- + arr_reshaped : array, shape ([1, ...], N, [1,...]) + View of `arr` reshaped to the desired shape. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> arr = rng.random(7) + >>> reshape_nd(arr, 2, 0).shape + (7, 1) + >>> reshape_nd(arr, 3, 1).shape + (1, 7, 1) + >>> reshape_nd(arr, 4, -1).shape + (1, 1, 1, 7) + """ + if arr.ndim != 1: + raise ValueError("arr must be a 1D array") + new_shape = [1] * ndim + new_shape[dim] = -1 + return np.reshape(arr, new_shape) + + +def check_nD(array, ndim, arg_name='image'): + """ + Verify an array meets the desired ndims and array isn't empty. + + Parameters + ---------- + array : array-like + Input array to be validated + ndim : int or iterable of ints + Allowable ndim or ndims for the array. + arg_name : str, optional + The name of the array in the original function. + + """ + array = np.asanyarray(array) + msg_incorrect_dim = "The parameter `%s` must be a %s-dimensional array" + msg_empty_array = "The parameter `%s` cannot be an empty array" + if isinstance(ndim, int): + ndim = [ndim] + if array.size == 0: + raise ValueError(msg_empty_array % (arg_name)) + if array.ndim not in ndim: + raise ValueError( + msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim])) + ) + + +def convert_to_float(image, preserve_range): + """Convert input image to float image with the appropriate range. + + Parameters + ---------- + image : ndarray + Input image. + preserve_range : bool + Determines if the range of the image should be kept or transformed + using img_as_float. Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + Notes + ----- + * Input images with `float32` data type are not upcast. + + Returns + ------- + image : ndarray + Transformed version of the input. + + """ + if image.dtype == np.float16: + return image.astype(np.float32) + if preserve_range: + # Convert image to double only if it is not single or double + # precision float + if image.dtype.char not in 'df': + image = image.astype(float) + else: + from ..util.dtype import img_as_float + + image = img_as_float(image) + return image + + +def _validate_interpolation_order(image_dtype, order): + """Validate and return spline interpolation's order. + + Parameters + ---------- + image_dtype : dtype + Image dtype. + order : {None, int}, optional + The order of the spline interpolation. The order has to be in the range + 0-5. If ``None`` assume order 0 for Boolean images, otherwise 1. See + `skimage.transform.warp` for detail. + + Returns + ------- + order : int + if input order is None, returns 0 if image_dtype is bool and 1 + otherwise. Otherwise, image_dtype is checked and input order + is validated accordingly (order > 0 is not supported for bool + image dtype) + + """ + + if order is None: + return 0 if image_dtype == bool else 1 + + if order < 0 or order > 5: + raise ValueError("Spline interpolation order has to be in the range 0-5.") + + if image_dtype == bool and order != 0: + raise ValueError( + "Input image dtype is bool. Interpolation is not defined " + "with bool data type. Please set order to 0 or explicitly " + "cast input image to another data type." + ) + + return order + + +def _to_np_mode(mode): + """Convert padding modes from `ndi.correlate` to `np.pad`.""" + mode_translation_dict = dict(nearest='edge', reflect='symmetric', mirror='reflect') + if mode in mode_translation_dict: + mode = mode_translation_dict[mode] + return mode + + +def _to_ndimage_mode(mode): + """Convert from `numpy.pad` mode name to the corresponding ndimage mode.""" + mode_translation_dict = dict( + constant='constant', + edge='nearest', + symmetric='reflect', + reflect='mirror', + wrap='wrap', + ) + if mode not in mode_translation_dict: + raise ValueError( + f"Unknown mode: '{mode}', or cannot translate mode. The " + f"mode should be one of 'constant', 'edge', 'symmetric', " + f"'reflect', or 'wrap'. See the documentation of numpy.pad for " + f"more info." + ) + return _fix_ndimage_mode(mode_translation_dict[mode]) + + +def _fix_ndimage_mode(mode): + # SciPy 1.6.0 introduced grid variants of constant and wrap which + # have less surprising behavior for images. Use these when available + grid_modes = {'constant': 'grid-constant', 'wrap': 'grid-wrap'} + return grid_modes.get(mode, mode) + + +new_float_type = { + # preserved types + np.float32().dtype.char: np.float32, + np.float64().dtype.char: np.float64, + np.complex64().dtype.char: np.complex64, + np.complex128().dtype.char: np.complex128, + # altered types + np.float16().dtype.char: np.float32, + 'g': np.float64, # np.float128 ; doesn't exist on windows + 'G': np.complex128, # np.complex256 ; doesn't exist on windows +} + + +def _supported_float_type(input_dtype, allow_complex=False): + """Return an appropriate floating-point dtype for a given dtype. + + float32, float64, complex64, complex128 are preserved. + float16 is promoted to float32. + complex256 is demoted to complex128. + Other types are cast to float64. + + Parameters + ---------- + input_dtype : np.dtype or tuple of np.dtype + The input dtype. If a tuple of multiple dtypes is provided, each + dtype is first converted to a supported floating point type and the + final dtype is then determined by applying `np.result_type` on the + sequence of supported floating point types. + allow_complex : bool, optional + If False, raise a ValueError on complex-valued inputs. + + Returns + ------- + float_type : dtype + Floating-point dtype for the image. + """ + if isinstance(input_dtype, tuple): + return np.result_type(*(_supported_float_type(d) for d in input_dtype)) + input_dtype = np.dtype(input_dtype) + if not allow_complex and input_dtype.kind == 'c': + raise ValueError("complex valued input is not supported") + return new_float_type.get(input_dtype.char, np.float64) + + +def identity(image, *args, **kwargs): + """Returns the first argument unmodified.""" + return image + + +def as_binary_ndarray(array, *, variable_name): + """Return `array` as a numpy.ndarray of dtype bool. + + Raises + ------ + ValueError: + An error including the given `variable_name` if `array` can not be + safely cast to a boolean array. + """ + array = np.asarray(array) + if array.dtype != bool: + if np.any((array != 1) & (array != 0)): + raise ValueError( + f"{variable_name} array is not of dtype boolean or " + f"contains values other than 0 and 1 so cannot be " + f"safely cast to boolean array." + ) + return np.asarray(array, dtype=bool) diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_daisy.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_daisy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5783a44eb888110029659003d1c0cab6ee0bdcc Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_daisy.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/brief.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/brief.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ff921ad226ab36d6c8f83ded848a954235eb8d9 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/brief.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/template.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/template.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b76aca6da13f897be381f5accd4e3e2abf78f42c Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/template.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__init__.py b/envs/kitoverlay/skimage/graph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e366208a84906e3e7ca12e352845299bd2555e1 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/__init__.py @@ -0,0 +1,12 @@ +""" +Graph-based operations, e.g., shortest paths. + +This includes creating adjacency graphs of pixels in an image, finding the +central pixel in an image, finding (minimum-cost) paths across pixels, merging +and cutting of graphs, etc. + +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/graph/__init__.pyi b/envs/kitoverlay/skimage/graph/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5582d999e90ecd56805004550b19f0de04a33012 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/__init__.pyi @@ -0,0 +1,27 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'pixel_graph', + 'central_pixel', + 'shortest_path', + 'MCP', + 'MCP_Geometric', + 'MCP_Connect', + 'MCP_Flexible', + 'route_through_array', + 'rag_mean_color', + 'rag_boundary', + 'cut_threshold', + 'cut_normalized', + 'merge_hierarchical', + 'RAG', +] + +from ._graph import pixel_graph, central_pixel +from ._graph_cut import cut_threshold, cut_normalized +from ._graph_merge import merge_hierarchical +from ._rag import rag_mean_color, RAG, show_rag, rag_boundary +from .spath import shortest_path +from .mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible, route_through_array diff --git a/envs/kitoverlay/skimage/graph/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe2361cf70d8b21ce50bcce908ea27d800b291ca Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/_graph.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/_graph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0667780af05c3b6801a933f5a922f5b894fe93e7 Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/_graph.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/_graph_cut.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/_graph_cut.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1684049ab3b5749a595fa25b9902c592a8ff0a78 Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/_graph_cut.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/_graph_merge.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/_graph_merge.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af0d488da32def793b6f1f5a1c652d2f13470ab9 Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/_graph_merge.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/_ncut.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/_ncut.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..529083dd3c936b5eae3b1355b3cd35145d1d8dcd Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/_ncut.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/_rag.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/_rag.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49e410994ba5c0b4a3dae3986a3de14c8fa9afa3 Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/_rag.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/mcp.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/mcp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8aea17fae901ef7904f576f5276c5e991598796b Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/mcp.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/__pycache__/spath.cpython-311.pyc b/envs/kitoverlay/skimage/graph/__pycache__/spath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6717ad5c603dad37f11801f190f5697189ae1c1f Binary files /dev/null and b/envs/kitoverlay/skimage/graph/__pycache__/spath.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/graph/_graph.py b/envs/kitoverlay/skimage/graph/_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..228c4dfddc2a3acfde981c864a262a727483b123 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/_graph.py @@ -0,0 +1,220 @@ +import numpy as np +from scipy import sparse +from scipy.sparse import csgraph +from ..morphology._util import _raveled_offsets_and_distances +from ..util._map_array import map_array +from ..segmentation.random_walker_segmentation import _safe_downcast_indices + + +def _weighted_abs_diff(values0, values1, distances): + """A default edge function for complete image graphs. + + A pixel graph on an image with no edge values and no mask is a very + boring regular lattice, so we define a default edge weight to be the + absolute difference between values *weighted* by the distance + between them. + + Parameters + ---------- + values0 : array + The pixel values for each node. + values1 : array + The pixel values for each neighbor. + distances : array + The distance between each node and its neighbor. + + Returns + ------- + edge_values : array of float + The computed values: abs(values0 - values1) * distances. + """ + return np.abs(values0 - values1) * distances + + +def pixel_graph( + image, + *, + mask=None, + edge_function=None, + connectivity=1, + spacing=None, + sparse_type="matrix", +): + """Create an adjacency graph of pixels in an image. + + Pixels where the mask is True are nodes in the returned graph, and they are + connected by edges to their neighbors according to the connectivity + parameter. By default, the *value* of an edge when a mask is given, or when + the image is itself the mask, is the Euclidean distance between the pixels. + + However, if an int- or float-valued image is given with no mask, the value + of the edges is the absolute difference in intensity between adjacent + pixels, weighted by the Euclidean distance. + + Parameters + ---------- + image : array + The input image. If the image is of type bool, it will be used as the + mask as well. + mask : array of bool + Which pixels to use. If None, the graph for the whole image is used. + edge_function : callable + A function taking an array of pixel values, and an array of neighbor + pixel values, and an array of distances, and returning a value for the + edge. If no function is given, the value of an edge is just the + distance. + connectivity : int + The square connectivity of the pixel neighborhood: the number of + orthogonal steps allowed to consider a pixel a neighbor. See + `scipy.ndimage.generate_binary_structure` for details. + spacing : tuple of float + The spacing between pixels along each axis. + sparse_type : {"matrix", "array"}, optional + The return type of `graph`, either `scipy.sparse.csr_array` or + `scipy.sparse.csr_matrix` (default). + + Returns + ------- + graph : scipy.sparse.csr_matrix or scipy.sparse.csr_array + A sparse adjacency matrix in which entry (i, j) is 1 if nodes i and j + are neighbors, 0 otherwise. Depending on `sparse_type`, this can be + returned as a `scipy.sparse.csr_array`. + nodes : array of int + The nodes of the graph. These correspond to the raveled indices of the + nonzero pixels in the mask. + """ + if mask is None: + if image.dtype == bool: + mask = image + else: + mask = np.ones_like(image, dtype=bool) + + if edge_function is None: + if image.dtype == bool: + + def edge_function(x, y, distances): + return distances + + else: + edge_function = _weighted_abs_diff + + # Strategy: we are going to build the (i, j, data) arrays of a scipy + # sparse CSR matrix. + # - grab the raveled IDs of the foreground (mask == True) parts of the + # image **in the padded space**. + # - broadcast them together with the raveled offsets to their neighbors. + # This gives us for each foreground pixel a list of neighbors (that + # may or may not be selected by the mask). (We also track the *distance* + # to each neighbor.) + # - select "valid" entries in the neighbors and distance arrays by indexing + # into the mask, which we can do since these are raveled indices. + # - use np.repeat() to repeat each source index according to the number + # of neighbors selected by the mask it has. Each of these repeated + # indices will be lined up with its neighbor, i.e. **this is the row_ind + # array** of the CSR format matrix. + # - use the mask as a boolean index to get a 1D view of the selected + # neighbors. **This is the col_ind array.** + # - by default, the same boolean indexing can be applied to the distances + # to each neighbor, to give the **data array.** Optionally, a + # provided edge function can be computed on the pixel values and the + # distances to give a different value for the edges. + # Note, we use map_array to map the raveled coordinates in the padded + # image to the ones in the original image, and those are the returned + # nodes. + padded = np.pad(mask, 1, mode='constant', constant_values=False) + nodes_padded = np.flatnonzero(padded) + neighbor_offsets_padded, distances_padded = _raveled_offsets_and_distances( + padded.shape, connectivity=connectivity, spacing=spacing + ) + neighbors_padded = nodes_padded[:, np.newaxis] + neighbor_offsets_padded + neighbor_distances_full = np.broadcast_to(distances_padded, neighbors_padded.shape) + nodes = np.flatnonzero(mask) + nodes_sequential = np.arange(nodes.size) + # neighbors outside the mask get mapped to 0, which is a valid index, + # BUT, they will be masked out in the next step. + neighbors = map_array(neighbors_padded, nodes_padded, nodes) + neighbors_mask = padded.reshape(-1)[neighbors_padded] + num_neighbors = np.sum(neighbors_mask, axis=1) + indices = np.repeat(nodes, num_neighbors) + indices_sequential = np.repeat(nodes_sequential, num_neighbors) + neighbor_indices = neighbors[neighbors_mask] + neighbor_distances = neighbor_distances_full[neighbors_mask] + neighbor_indices_sequential = map_array(neighbor_indices, nodes, nodes_sequential) + + image_r = image.reshape(-1) + data = edge_function( + image_r[indices], image_r[neighbor_indices], neighbor_distances + ) + + m = nodes_sequential.size + graph = sparse.csr_array( + (data, (indices_sequential, neighbor_indices_sequential)), shape=(m, m) + ) + + if sparse_type == "matrix": + graph = sparse.csr_matrix(graph) + elif sparse_type != "array": + msg = f"`sparse_type` must be 'array' or 'matrix', got {sparse_type}" + raise ValueError(msg) + + return graph, nodes + + +def central_pixel(graph, nodes=None, shape=None, partition_size=100): + """Find the pixel with the highest closeness centrality. + + Closeness centrality is the inverse of the total sum of shortest distances + from a node to every other node. + + Parameters + ---------- + graph : scipy.sparse.csr_array or scipy.sparse.csr_matrix + The sparse representation of the graph. + nodes : array of int + The raveled index of each node in graph in the image. If not provided, + the returned value will be the index in the input graph. + shape : tuple of int + The shape of the image in which the nodes are embedded. If provided, + the returned coordinates are a NumPy multi-index of the same + dimensionality as the input shape. Otherwise, the returned coordinate + is the raveled index provided in `nodes`. + partition_size : int + This function computes the shortest path distance between every pair + of nodes in the graph. This can result in a very large (N*N) matrix. + As a simple performance tweak, the distance values are computed in + lots of `partition_size`, resulting in a memory requirement of only + partition_size*N. + + Returns + ------- + position : int or tuple of int + If shape is given, the coordinate of the central pixel in the image. + Otherwise, the raveled index of that pixel. + distances : array of float + The total sum of distances from each node to each other reachable + node. + """ + if nodes is None: + nodes = np.arange(graph.shape[0]) + if partition_size is None: + num_splits = 1 + else: + num_splits = max(2, graph.shape[0] // partition_size) + graph.indices, graph.indptr = _safe_downcast_indices( + graph, np.int32, 'index values too large for csgraph' + ) + idxs = np.arange(graph.shape[0]) + total_shortest_path_len_list = [] + for partition in np.array_split(idxs, num_splits): + shortest_paths = csgraph.shortest_path(graph, directed=False, indices=partition) + shortest_paths_no_inf = np.nan_to_num(shortest_paths) + total_shortest_path_len_list.append(np.sum(shortest_paths_no_inf, axis=1)) + total_shortest_path_len = np.concatenate(total_shortest_path_len_list) + nonzero = np.flatnonzero(total_shortest_path_len) + min_sp = np.argmin(total_shortest_path_len[nonzero]) + raveled_index = nodes[nonzero[min_sp]] + if shape is not None: + central = np.unravel_index(raveled_index, shape) + else: + central = raveled_index + return central, total_shortest_path_len diff --git a/envs/kitoverlay/skimage/graph/_graph_cut.py b/envs/kitoverlay/skimage/graph/_graph_cut.py new file mode 100644 index 0000000000000000000000000000000000000000..92e792bab541ad1fe2beeb400f420ccabc8c926d --- /dev/null +++ b/envs/kitoverlay/skimage/graph/_graph_cut.py @@ -0,0 +1,319 @@ +import networkx as nx +import numpy as np +from scipy.sparse import linalg + +from skimage._shared.compat import SCIPY_GE_1_17_0_DEV0 +from . import _ncut, _ncut_cy + + +def cut_threshold(labels, rag, thresh, in_place=True): + """Combine regions separated by weight less than threshold. + + Given an image's labels and its RAG, output new labels by + combining regions whose nodes are separated by a weight less + than the given threshold. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The region adjacency graph. + thresh : float + The threshold. Regions connected by edges with smaller weights are + combined. + in_place : bool + If set, modifies `rag` in place. The function will remove the edges + with weights less that `thresh`. If set to `False` the function + makes a copy of `rag` before proceeding. + + Returns + ------- + out : ndarray + The new labelled array. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels) + >>> new_labels = graph.cut_threshold(labels, rag, 10) + + References + ---------- + .. [1] Alain Tremeau and Philippe Colantoni + "Regions Adjacency Graph Applied To Color Image Segmentation" + :DOI:`10.1109/83.841950` + + """ + if not in_place: + rag = rag.copy() + + # Because deleting edges while iterating through them produces an error. + to_remove = [(x, y) for x, y, d in rag.edges(data=True) if d['weight'] >= thresh] + rag.remove_edges_from(to_remove) + + comps = nx.connected_components(rag) + + # We construct an array which can map old labels to the new ones. + # All the labels within a connected component are assigned to a single + # label in the output. + map_array = np.arange(labels.max() + 1, dtype=labels.dtype) + for i, nodes in enumerate(comps): + for node in nodes: + for label in rag.nodes[node]['labels']: + map_array[label] = i + + return map_array[labels] + + +def cut_normalized( + labels, + rag, + thresh=0.001, + num_cuts=10, + in_place=True, + max_edge=1.0, + *, + rng=None, +): + """Perform Normalized Graph cut on the Region Adjacency Graph. + + Given an image's labels and its similarity RAG, recursively perform + a 2-way normalized cut on it. All nodes belonging to a subgraph + that cannot be cut further are assigned a unique label in the + output. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The region adjacency graph. + thresh : float + The threshold. A subgraph won't be further subdivided if the + value of the N-cut exceeds `thresh`. + num_cuts : int + The number or N-cuts to perform before determining the optimal one. + in_place : bool + If set, modifies `rag` in place. For each node `n` the function will + set a new attribute ``rag.nodes[n]['ncut label']``. + max_edge : float, optional + The maximum possible value of an edge in the RAG. This corresponds to + an edge between identical regions. This is used to put self + edges in the RAG. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The `rng` is used to determine the starting point + of `scipy.sparse.linalg.eigsh`. + + Returns + ------- + out : ndarray + The new labeled array. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels, mode='similarity') + >>> new_labels = graph.cut_normalized(labels, rag) + + References + ---------- + .. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation", + Pattern Analysis and Machine Intelligence, + IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000. + + """ + rng = np.random.default_rng(rng) + if not in_place: + rag = rag.copy() + + for node in rag.nodes(): + rag.add_edge(node, node, weight=max_edge) + + _ncut_relabel(rag, thresh, num_cuts, rng) + + map_array = np.zeros(labels.max() + 1, dtype=labels.dtype) + # Mapping from old labels to new + for n, d in rag.nodes(data=True): + map_array[d['labels']] = d['ncut label'] + + return map_array[labels] + + +def partition_by_cut(cut, rag): + """Compute resulting subgraphs from given bi-partition. + + Parameters + ---------- + cut : array + A array of booleans. Elements set to `True` belong to one + set. + rag : RAG + The Region Adjacency Graph. + + Returns + ------- + sub1, sub2 : RAG + The two resulting subgraphs from the bi-partition. + """ + # `cut` is derived from `D` and `W` matrices, which also follow the + # ordering returned by `rag.nodes()` because we use + # nx.to_scipy_sparse_array. + + # Example + # rag.nodes() = [3, 7, 9, 13] + # cut = [True, False, True, False] + # nodes1 = [3, 9] + # nodes2 = [7, 10] + + nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]] + nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]] + + sub1 = rag.subgraph(nodes1) + sub2 = rag.subgraph(nodes2) + + return sub1, sub2 + + +def get_min_ncut(ev, d, w, num_cuts): + """Threshold an eigenvector evenly, to determine minimum ncut. + + Parameters + ---------- + ev : array + The eigenvector to threshold. + d : ndarray + The diagonal matrix of the graph. + w : ndarray + The weight matrix of the graph. + num_cuts : int + The number of evenly spaced thresholds to check for. + + Returns + ------- + mask : array + The array of booleans which denotes the bi-partition. + mcut : float + The value of the minimum ncut. + """ + mcut = np.inf + mn = ev.min() + mx = ev.max() + + # If all values in `ev` are equal, it implies that the graph can't be + # further sub-divided. In this case the bi-partition is the the graph + # itself and an empty set. + min_mask = np.zeros_like(ev, dtype=bool) + if np.allclose(mn, mx): + return min_mask, mcut + + # Refer Shi & Malik 2001, Section 3.1.3, Page 892 + # Perform evenly spaced n-cuts and determine the optimal one. + for t in np.linspace(mn, mx, num_cuts, endpoint=False): + mask = ev > t + cost = _ncut.ncut_cost(mask, d, w) + if cost < mcut: + min_mask = mask + mcut = cost + + return min_mask, mcut + + +def _label_all(rag, attr_name): + """Assign a unique integer to the given attribute in the RAG. + + This function assumes that all labels in `rag` are unique. It + picks up a random label from them and assigns it to the `attr_name` + attribute of all the nodes. + + rag : RAG + The Region Adjacency Graph. + attr_name : string + The attribute to which a unique integer is assigned. + """ + node = min(rag.nodes()) + new_label = rag.nodes[node]['labels'][0] + for n, d in rag.nodes(data=True): + d[attr_name] = new_label + + +def _ncut_relabel(rag, thresh, num_cuts, random_generator): + """Perform Normalized Graph cut on the Region Adjacency Graph. + + Recursively partition the graph into 2, until further subdivision + yields a cut greater than `thresh` or such a cut cannot be computed. + For such a subgraph, indices to labels of all its nodes map to a single + unique value. + + Parameters + ---------- + rag : RAG + The region adjacency graph. + thresh : float + The threshold. A subgraph won't be further subdivided if the + value of the N-cut exceeds `thresh`. + num_cuts : int + The number or N-cuts to perform before determining the optimal one. + random_generator : `numpy.random.Generator` + Provides initial values for eigenvalue solver. + """ + d, w = _ncut.DW_matrices(rag) + m = w.shape[0] + + if (m > 2) and (d != w).nnz > 0: + # This avoids further segmenting a graph that is too small, + # and the degenerate case (d == w), which typically occurs + # when only three single pixels remain. + # + # We're not sure exactly why this latter case arises. For + # SciPy <= 0.14, SciPy continued to compute an eigenvector, + # but newer versions (correctly) won't. We refuse to guess, + # and stop further segmentation. + # + # It may make sense to a warning here; on the other hand segmentations + # are not a ground truth, so this level of "noise" should be acceptable. + + d2 = d.copy() + # Since d is diagonal, we can directly operate on its data + # the inverse of the square root + d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data) + + # Refer Shi & Malik 2001, Equation 7, Page 891 + A = d2 @ (d - w) @ d2 + # Initialize the vector to ensure reproducibility. + v0 = random_generator.random(A.shape[0]) + + # SciPy 1.17.0.dev0 adds the new `rng` keyword, allowing `eigsh` to + # become deterministic + rng_kw = {"rng": random_generator} if SCIPY_GE_1_17_0_DEV0 else {} + vals, vectors = linalg.eigsh(A, which='SM', v0=v0, k=min(100, m - 2), **rng_kw) + + # Pick second smallest eigenvector. + # Refer Shi & Malik 2001, Section 3.2.3, Page 893 + vals, vectors = np.real(vals), np.real(vectors) + index2 = _ncut_cy.argmin2(vals) + ev = vectors[:, index2] + + cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts) + if mcut < thresh: + # Sub divide and perform N-cut again + # Refer Shi & Malik 2001, Section 3.2.5, Page 893 + sub1, sub2 = partition_by_cut(cut_mask, rag) + + _ncut_relabel(sub1, thresh, num_cuts, random_generator) + _ncut_relabel(sub2, thresh, num_cuts, random_generator) + return + + # The N-cut wasn't small enough, or could not be computed. + # The remaining graph is a region. + # Assign `ncut label` by picking any label from the existing nodes, since + # `labels` are unique, `new_label` is also unique. + _label_all(rag, 'ncut label') diff --git a/envs/kitoverlay/skimage/graph/_graph_merge.py b/envs/kitoverlay/skimage/graph/_graph_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7a20c4bff0f63d00d0e3a760b93e6b2d543bd4 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/_graph_merge.py @@ -0,0 +1,138 @@ +import numpy as np +import heapq + + +def _revalidate_node_edges(rag, node, heap_list): + """Handles validation and invalidation of edges incident to a node. + + This function invalidates all existing edges incident on `node` and inserts + new items in `heap_list` updated with the valid weights. + + rag : RAG + The Region Adjacency Graph. + node : int + The id of the node whose incident edges are to be validated/invalidated + . + heap_list : list + The list containing the existing heap of edges. + """ + # networkx updates data dictionary if edge exists + # this would mean we have to reposition these edges in + # heap if their weight is updated. + # instead we invalidate them + + for nbr in rag.neighbors(node): + data = rag[node][nbr] + try: + # invalidate edges incident on `dst`, they have new weights + data['heap item'][3] = False + _invalidate_edge(rag, node, nbr) + except KeyError: + # will handle the case where the edge did not exist in the existing + # graph + pass + + wt = data['weight'] + heap_item = [wt, node, nbr, True] + data['heap item'] = heap_item + heapq.heappush(heap_list, heap_item) + + +def _rename_node(graph, node_id, copy_id): + """Rename `node_id` in `graph` to `copy_id`.""" + + graph._add_node_silent(copy_id) + graph.nodes[copy_id].update(graph.nodes[node_id]) + + for nbr in graph.neighbors(node_id): + wt = graph[node_id][nbr]['weight'] + graph.add_edge(nbr, copy_id, {'weight': wt}) + + graph.remove_node(node_id) + + +def _invalidate_edge(graph, n1, n2): + """Invalidates the edge (n1, n2) in the heap.""" + graph[n1][n2]['heap item'][3] = False + + +def merge_hierarchical( + labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func +): + """Perform hierarchical merging of a RAG. + + Greedily merges the most similar pair of nodes until no edges lower than + `thresh` remain. + + Parameters + ---------- + labels : ndarray + The array of labels. + rag : RAG + The Region Adjacency Graph. + thresh : float + Regions connected by an edge with weight smaller than `thresh` are + merged. + rag_copy : bool + If set, the RAG copied before modifying. + in_place_merge : bool + If set, the nodes are merged in place. Otherwise, a new node is + created for each merge.. + merge_func : callable + This function is called before merging two nodes. For the RAG `graph` + while merging `src` and `dst`, it is called as follows + ``merge_func(graph, src, dst)``. + weight_func : callable + The function to compute the new weights of the nodes adjacent to the + merged node. This is directly supplied as the argument `weight_func` + to `merge_nodes`. + + Returns + ------- + out : ndarray + The new labeled array. + + """ + if rag_copy: + rag = rag.copy() + + edge_heap = [] + for n1, n2, data in rag.edges(data=True): + # Push a valid edge in the heap + wt = data['weight'] + heap_item = [wt, n1, n2, True] + heapq.heappush(edge_heap, heap_item) + + # Reference to the heap item in the graph + data['heap item'] = heap_item + + while len(edge_heap) > 0 and edge_heap[0][0] < thresh: + _, n1, n2, valid = heapq.heappop(edge_heap) + + # Ensure popped edge is valid, if not, the edge is discarded + if valid: + # Invalidate all neighbors of `src` before its deleted + + for nbr in rag.neighbors(n1): + _invalidate_edge(rag, n1, nbr) + + for nbr in rag.neighbors(n2): + _invalidate_edge(rag, n2, nbr) + + if not in_place_merge: + next_id = rag.next_id() + _rename_node(rag, n2, next_id) + src, dst = n1, next_id + else: + src, dst = n1, n2 + + merge_func(rag, src, dst) + new_id = rag.merge_nodes(src, dst, weight_func) + _revalidate_node_edges(rag, new_id, edge_heap) + + label_map = np.arange(labels.max() + 1) + for ix, (n, d) in enumerate(rag.nodes(data=True)): + for label in d['labels']: + label_map[label] = ix + + return label_map[labels] diff --git a/envs/kitoverlay/skimage/graph/_ncut.py b/envs/kitoverlay/skimage/graph/_ncut.py new file mode 100644 index 0000000000000000000000000000000000000000..504bd6f69bab25672a05b908d419825a51158ee8 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/_ncut.py @@ -0,0 +1,64 @@ +import networkx as nx +import numpy as np +from scipy import sparse +from . import _ncut_cy + + +def DW_matrices(graph): + """Returns the diagonal and weight matrices of a graph. + + Parameters + ---------- + graph : RAG + A Region Adjacency Graph. + + Returns + ------- + D : csc_array + The diagonal matrix of the graph. ``D[i, i]`` is the sum of weights of + all edges incident on `i`. All other entries are `0`. + W : csc_array + The weight matrix of the graph. ``W[i, j]`` is the weight of the edge + joining `i` to `j`. + """ + # sparse.eighsh is most efficient with CSC-formatted input + W = nx.to_scipy_sparse_array(graph, format='csc') + entries = W.sum(axis=0) + D = sparse.dia_array((entries, 0), shape=W.shape).tocsc() + + return D, W + + +def ncut_cost(cut, D, W): + """Returns the N-cut cost of a bi-partition of a graph. + + Parameters + ---------- + cut : ndarray + The mask for the nodes in the graph. Nodes corresponding to a `True` + value are in one set. + D : csc_array + The diagonal matrix of the graph. + W : csc_array + The weight matrix of the graph. + + Returns + ------- + cost : float + The cost of performing the N-cut. + + References + ---------- + .. [1] Normalized Cuts and Image Segmentation, Jianbo Shi and + Jitendra Malik, IEEE Transactions on Pattern Analysis and Machine + Intelligence, Page 889, Equation 2. + """ + cut = np.array(cut) + cut_cost = _ncut_cy.cut_cost(cut, W.data, W.indices, W.indptr, num_cols=W.shape[0]) + + # D has elements only along the diagonal, one per node, so we can directly + # index the data attribute with cut. + assoc_a = D.data[cut].sum() + assoc_b = D.data[~cut].sum() + + return (cut_cost / assoc_a) + (cut_cost / assoc_b) diff --git a/envs/kitoverlay/skimage/graph/_rag.py b/envs/kitoverlay/skimage/graph/_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..17729967caf38bd68eecf688623a4fe1f40a23a9 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/_rag.py @@ -0,0 +1,581 @@ +import networkx as nx +import numpy as np +from scipy import ndimage as ndi +from scipy import sparse +import math + +from .. import measure, segmentation, util, color +from .._shared.version_requirements import require + + +__doctest_requires__ = {("show_rag",): ["matplotlib"]} + + +def _edge_generator_from_csr(csr_array): + """Yield weighted edge triples for use by NetworkX from a CSR matrix. + + This function is a straight rewrite of + `networkx.convert_matrix._csr_gen_triples`. Since that is a private + function, it is safer to include our own here. + + Parameters + ---------- + csr_array : scipy.sparse.csr_array + The input matrix. An edge (i, j, w) will be yielded if there is a + data value for coordinates (i, j) in the matrix, even if that value + is 0. + + Yields + ------ + i, j, w : (int, int, float) tuples + Each value `w` in the matrix along with its coordinates (i, j). + + Examples + -------- + + >>> dense = np.eye(2, dtype=float) + >>> csr = sparse.csr_array(dense) + >>> edges = _edge_generator_from_csr(csr) + >>> list(edges) + [(0, 0, 1.0), (1, 1, 1.0)] + """ + nrows = csr_array.shape[0] + values = csr_array.data + indptr = csr_array.indptr + col_indices = csr_array.indices + for i in range(nrows): + for j in range(indptr[i], indptr[i + 1]): + yield i, col_indices[j], values[j] + + +def min_weight(graph, src, dst, n): + """Callback to handle merging nodes by choosing minimum weight. + + Returns a dictionary with `"weight"` set as either the weight between + (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when + both exist. + + Parameters + ---------- + graph : RAG + The graph under consideration. + src, dst : int + The verices in `graph` to be merged. + n : int + A neighbor of `src` or `dst` or both. + + Returns + ------- + data : dict + A dict with the `"weight"` attribute set the weight between + (`src`, `n`) or (`dst`, `n`) in `graph` or the minimum of the two when + both exist. + + """ + + # cover the cases where n only has edge to either `src` or `dst` + default = {'weight': np.inf} + w1 = graph[n].get(src, default)['weight'] + w2 = graph[n].get(dst, default)['weight'] + return {'weight': min(w1, w2)} + + +def _add_edge_filter(values, graph): + """Create edge in `graph` between central element of `values` and the rest. + + Add an edge between the middle element in `values` and + all other elements of `values` into `graph`. ``values[len(values) // 2]`` + is expected to be the central value of the footprint used. + + Parameters + ---------- + values : array + The array to process. + graph : RAG + The graph to add edges in. + + Returns + ------- + 0 : float + Always returns 0. The return value is required so that `generic_filter` + can put it in the output array, but it is ignored by this filter. + """ + values = values.astype(int) + center = values[len(values) // 2] + for value in values: + if value != center and not graph.has_edge(center, value): + graph.add_edge(center, value) + return 0.0 + + +class RAG(nx.Graph): + """The Region Adjacency Graph (RAG) of an image, subclasses :obj:`networkx.Graph`. + + Parameters + ---------- + label_image : array of int + An initial segmentation, with each region labeled as a different + integer. Every unique value in ``label_image`` will correspond to + a node in the graph. + connectivity : int in {1, ..., ``label_image.ndim``}, optional + The connectivity between pixels in ``label_image``. For a 2D image, + a connectivity of 1 corresponds to immediate neighbors up, down, + left, and right, while a connectivity of 2 also includes diagonal + neighbors. See :func:`scipy.ndimage.generate_binary_structure`. + data : :obj:`networkx.Graph` specification, optional + Initial or additional edges to pass to :obj:`networkx.Graph` + constructor. Valid edge specifications include edge list (list of tuples), + NumPy arrays, and SciPy sparse matrices. + **attr : keyword arguments, optional + Additional attributes to add to the graph. + """ + + def __init__(self, label_image=None, connectivity=1, data=None, **attr): + super().__init__(data, **attr) + if self.number_of_nodes() == 0: + self.max_id = 0 + else: + self.max_id = max(self.nodes()) + + if label_image is not None: + fp = ndi.generate_binary_structure(label_image.ndim, connectivity) + # In the next ``ndi.generic_filter`` function, the kwarg + # ``output`` is used to provide a strided array with a single + # 64-bit floating point number, to which the function repeatedly + # writes. This is done because even if we don't care about the + # output, without this, a float array of the same shape as the + # input image will be created and that could be expensive in + # memory consumption. + output = np.broadcast_to(1.0, label_image.shape) + output.setflags(write=True) + ndi.generic_filter( + label_image, + function=_add_edge_filter, + footprint=fp, + mode='nearest', + output=output, + extra_arguments=(self,), + ) + + def merge_nodes( + self, + src, + dst, + weight_func=min_weight, + in_place=True, + extra_arguments=None, + extra_keywords=None, + ): + """Merge node `src` and `dst`. + + The new combined node is adjacent to all the neighbors of `src` + and `dst`. `weight_func` is called to decide the weight of edges + incident on the new node. + + Parameters + ---------- + src, dst : int + Nodes to be merged. + weight_func : callable, optional + Function to decide the attributes of edges incident on the new + node. For each neighbor `n` for `src` and `dst`, `weight_func` will + be called as follows: `weight_func(src, dst, n, *extra_arguments, + **extra_keywords)`. `src`, `dst` and `n` are IDs of vertices in the + RAG object which is in turn a subclass of :obj:`networkx.Graph`. It is + expected to return a dict of attributes of the resulting edge. + in_place : bool, optional + If set to `True`, the merged node has the id `dst`, else merged + node has a new id which is returned. + extra_arguments : sequence, optional + The sequence of extra positional arguments passed to + `weight_func`. + extra_keywords : dictionary, optional + The dict of keyword arguments passed to the `weight_func`. + + Returns + ------- + id : int + The id of the new node. + + Notes + ----- + If `in_place` is `False` the resulting node has a new id, rather than + `dst`. + """ + if extra_arguments is None: + extra_arguments = [] + if extra_keywords is None: + extra_keywords = {} + + src_nbrs = set(self.neighbors(src)) + dst_nbrs = set(self.neighbors(dst)) + neighbors = (src_nbrs | dst_nbrs) - {src, dst} + + if in_place: + new = dst + else: + new = self.next_id() + self.add_node(new) + + for neighbor in neighbors: + data = weight_func( + self, src, dst, neighbor, *extra_arguments, **extra_keywords + ) + self.add_edge(neighbor, new, attr_dict=data) + + self.nodes[new]['labels'] = ( + self.nodes[src]['labels'] + self.nodes[dst]['labels'] + ) + self.remove_node(src) + + if not in_place: + self.remove_node(dst) + + return new + + def add_node(self, n, attr_dict=None, **attr): + """Add node `n` while updating the maximum node id. + + .. seealso:: :obj:`networkx.Graph.add_node`.""" + if attr_dict is None: # compatibility with old networkx + attr_dict = attr + else: + attr_dict.update(attr) + super().add_node(n, **attr_dict) + self.max_id = max(n, self.max_id) + + def add_edge(self, u, v, attr_dict=None, **attr): + """Add an edge between `u` and `v` while updating max node id. + + .. seealso:: :obj:`networkx.Graph.add_edge`.""" + if attr_dict is None: # compatibility with old networkx + attr_dict = attr + else: + attr_dict.update(attr) + super().add_edge(u, v, **attr_dict) + self.max_id = max(u, v, self.max_id) + + def copy(self): + """Copy the graph with its max node id. + + .. seealso:: :obj:`networkx.Graph.copy`.""" + g = super().copy() + g.max_id = self.max_id + return g + + def fresh_copy(self): + """Return a fresh copy graph with the same data structure. + + A fresh copy has no nodes, edges or graph attributes. It is + the same data structure as the current graph. This method is + typically used to create an empty version of the graph. + + This is required when subclassing Graph with networkx v2 and + does not cause problems for v1. Here is more detail from + the network migrating from 1.x to 2.x document:: + + With the new GraphViews (SubGraph, ReversedGraph, etc) + you can't assume that ``G.__class__()`` will create a new + instance of the same graph type as ``G``. In fact, the + call signature for ``__class__`` differs depending on + whether ``G`` is a view or a base class. For v2.x you + should use ``G.fresh_copy()`` to create a null graph of + the correct type---ready to fill with nodes and edges. + + """ + return RAG() + + def next_id(self): + """Returns the `id` for the new node to be inserted. + + The current implementation returns one more than the maximum `id`. + + Returns + ------- + id : int + The `id` of the new node to be inserted. + """ + return self.max_id + 1 + + def _add_node_silent(self, n): + """Add node `n` without updating the maximum node id. + + This is a convenience method used internally. + + .. seealso:: :obj:`networkx.Graph.add_node`.""" + super().add_node(n) + + +def rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0): + """Compute the Region Adjacency Graph using mean colors. + + Given an image and its initial segmentation, this method constructs the + corresponding Region Adjacency Graph (RAG). Each node in the RAG + represents a set of pixels within `image` with the same label in `labels`. + The weight between two adjacent regions represents how similar or + dissimilar two regions are depending on the `mode` parameter. + + Parameters + ---------- + image : ndarray, shape(M, N[, ..., P], 3) + Input image. + labels : ndarray, shape(M, N[, ..., P]) + The labelled image. This should have one dimension less than + `image`. If `image` has dimensions `(M, N, 3)` `labels` should have + dimensions `(M, N)`. + connectivity : int, optional + Pixels with a squared distance less than `connectivity` from each other + are considered adjacent. It can range from 1 to `labels.ndim`. Its + behavior is the same as `connectivity` parameter in + ``scipy.ndimage.generate_binary_structure``. + mode : {'distance', 'similarity'}, optional + The strategy to assign edge weights. + + 'distance' : The weight between two adjacent regions is the + :math:`|c_1 - c_2|`, where :math:`c_1` and :math:`c_2` are the mean + colors of the two regions. It represents the Euclidean distance in + their average color. + + 'similarity' : The weight between two adjacent is + :math:`e^{-d^2/sigma}` where :math:`d=|c_1 - c_2|`, where + :math:`c_1` and :math:`c_2` are the mean colors of the two regions. + It represents how similar two regions are. + sigma : float, optional + Used for computation when `mode` is "similarity". It governs how + close to each other two colors should be, for their corresponding edge + weight to be significant. A very large value of `sigma` could make + any two colors behave as though they were similar. + + Returns + ------- + out : RAG + The region adjacency graph. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> img = data.astronaut() + >>> labels = segmentation.slic(img) + >>> rag = graph.rag_mean_color(img, labels) + + References + ---------- + .. [1] Alain Tremeau and Philippe Colantoni + "Regions Adjacency Graph Applied To Color Image Segmentation" + :DOI:`10.1109/83.841950` + """ + graph = RAG(labels, connectivity=connectivity) + + for n in graph: + graph.nodes[n].update( + { + 'labels': [n], + 'pixel count': 0, + 'total color': np.array([0, 0, 0], dtype=np.float64), + } + ) + + for index in np.ndindex(labels.shape): + current = labels[index] + graph.nodes[current]['pixel count'] += 1 + graph.nodes[current]['total color'] += image[index] + + for n in graph: + graph.nodes[n]['mean color'] = ( + graph.nodes[n]['total color'] / graph.nodes[n]['pixel count'] + ) + + for x, y, d in graph.edges(data=True): + diff = graph.nodes[x]['mean color'] - graph.nodes[y]['mean color'] + diff = np.linalg.norm(diff) + if mode == 'similarity': + d['weight'] = math.e ** (-(diff**2) / sigma) + elif mode == 'distance': + d['weight'] = diff + else: + raise ValueError(f"The mode '{mode}' is not recognised") + + return graph + + +def rag_boundary(labels, edge_map, connectivity=2): + """Comouter RAG based on region boundaries + + Given an image's initial segmentation and its edge map this method + constructs the corresponding Region Adjacency Graph (RAG). Each node in the + RAG represents a set of pixels within the image with the same label in + `labels`. The weight between two adjacent regions is the average value + in `edge_map` along their boundary. + + labels : ndarray + The labelled image. + edge_map : ndarray + This should have the same shape as that of `labels`. For all pixels + along the boundary between 2 adjacent regions, the average value of the + corresponding pixels in `edge_map` is the edge weight between them. + connectivity : int, optional + Pixels with a squared distance less than `connectivity` from each other + are considered adjacent. It can range from 1 to `labels.ndim`. Its + behavior is the same as `connectivity` parameter in + `scipy.ndimage.generate_binary_structure`. + + Examples + -------- + >>> from skimage import data, segmentation, filters, color, graph + >>> img = data.chelsea() + >>> labels = segmentation.slic(img) + >>> edge_map = filters.sobel(color.rgb2gray(img)) + >>> rag = graph.rag_boundary(labels, edge_map) + + """ + + conn = ndi.generate_binary_structure(labels.ndim, connectivity) + eroded = ndi.grey_erosion(labels, footprint=conn) + dilated = ndi.grey_dilation(labels, footprint=conn) + boundaries0 = eroded != labels + boundaries1 = dilated != labels + labels_small = np.concatenate((eroded[boundaries0], labels[boundaries1])) + labels_large = np.concatenate((labels[boundaries0], dilated[boundaries1])) + n = np.max(labels_large) + 1 + + # use a dummy broadcast array as data for RAG + ones = np.broadcast_to(1.0, labels_small.shape) + count_matrix = sparse.csr_array( + (ones, (labels_small, labels_large)), dtype=int, shape=(n, n) + ) + data = np.concatenate((edge_map[boundaries0], edge_map[boundaries1])) + + graph_matrix = sparse.csr_array((data, (labels_small, labels_large))) + graph_matrix.data /= count_matrix.data + + rag = RAG() + rag.add_weighted_edges_from(_edge_generator_from_csr(graph_matrix), weight='weight') + rag.add_weighted_edges_from(_edge_generator_from_csr(count_matrix), weight='count') + + for n in rag.nodes(): + rag.nodes[n].update({'labels': [n]}) + + return rag + + +@require("matplotlib", ">=3.3") +def show_rag( + labels, + rag, + image, + border_color='black', + edge_width=1.5, + edge_cmap='magma', + img_cmap='bone', + in_place=True, + ax=None, +): + """Show a Region Adjacency Graph on an image. + + Given a labelled image and its corresponding RAG, show the nodes and edges + of the RAG on the image with the specified colors. Edges are displayed between + the centroid of the 2 adjacent regions in the image. + + Parameters + ---------- + labels : ndarray, shape (M, N) + The labelled image. + rag : RAG + The Region Adjacency Graph. + image : ndarray, shape (M, N[, 3]) + Input image. If `colormap` is `None`, the image should be in RGB + format. + border_color : color spec, optional + Color with which the borders between regions are drawn. + edge_width : float, optional + The thickness with which the RAG edges are drawn. + edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional + Any matplotlib colormap with which the edges are drawn. + img_cmap : :py:class:`matplotlib.colors.Colormap`, optional + Any matplotlib colormap with which the image is draw. If set to `None` + the image is drawn as it is. + in_place : bool, optional + If set, the RAG is modified in place. For each node `n` the function + will set a new attribute ``rag.nodes[n]['centroid']``. + ax : :py:class:`matplotlib.axes.Axes`, optional + The axes to draw on. If not specified, new axes are created and drawn + on. + + Returns + ------- + lc : :py:class:`matplotlib.collections.LineCollection` + A collection of lines that represent the edges of the graph. It can be + passed to the :meth:`matplotlib.figure.Figure.colorbar` function. + + Examples + -------- + >>> from skimage import data, segmentation, graph + >>> import matplotlib.pyplot as plt + >>> + >>> img = data.coffee() + >>> labels = segmentation.slic(img) + >>> g = graph.rag_mean_color(img, labels) + >>> lc = graph.show_rag(labels, g, img) + >>> cbar = plt.colorbar(lc) + """ + from matplotlib import colors + from matplotlib import pyplot as plt + from matplotlib.collections import LineCollection + + if not in_place: + rag = rag.copy() + + if ax is None: + fig, ax = plt.subplots() + out = util.img_as_float(image, force_copy=True) + + if img_cmap is None: + if image.ndim < 3 or image.shape[2] not in [3, 4]: + msg = 'If colormap is `None`, an RGB or RGBA image should be given' + raise ValueError(msg) + # Ignore the alpha channel + out = image[:, :, :3] + else: + img_cmap = plt.get_cmap(img_cmap) + out = color.rgb2gray(image) + # Ignore the alpha channel + out = img_cmap(out)[:, :, :3] + + edge_cmap = plt.get_cmap(edge_cmap) + + # Handling the case where one node has multiple labels + # offset is 1 so that regionprops does not ignore 0 + offset = 1 + map_array = np.arange(labels.max() + 1) + for n, d in rag.nodes(data=True): + for label in d['labels']: + map_array[label] = offset + offset += 1 + + rag_labels = map_array[labels] + regions = measure.regionprops(rag_labels) + + for (n, data), region in zip(rag.nodes(data=True), regions): + data['centroid'] = tuple(map(int, region['centroid'])) + + cc = colors.ColorConverter() + if border_color is not None: + border_color = cc.to_rgb(border_color) + out = segmentation.mark_boundaries(out, rag_labels, color=border_color) + + ax.imshow(out) + + # Defining the end points of the edges + # The tuple[::-1] syntax reverses a tuple as matplotlib uses (x,y) + # convention while skimage uses (row, column) + lines = [ + [rag.nodes[n1]['centroid'][::-1], rag.nodes[n2]['centroid'][::-1]] + for (n1, n2) in rag.edges() + ] + + lc = LineCollection(lines, linewidths=edge_width, cmap=edge_cmap) + edge_weights = [d['weight'] for x, y, d in rag.edges(data=True)] + lc.set_array(np.array(edge_weights)) + ax.add_collection(lc) + + return lc diff --git a/envs/kitoverlay/skimage/graph/mcp.py b/envs/kitoverlay/skimage/graph/mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1669ebfe7b88c5b824747479df9771ed280b8b --- /dev/null +++ b/envs/kitoverlay/skimage/graph/mcp.py @@ -0,0 +1,88 @@ +from ._mcp import MCP, MCP_Geometric, MCP_Connect, MCP_Flexible # noqa: F401 + + +def route_through_array(array, start, end, fully_connected=True, geometric=True): + """Simple example of how to use the MCP and MCP_Geometric classes. + + See the MCP and MCP_Geometric class documentation for explanation of the + path-finding algorithm. + + Parameters + ---------- + array : ndarray + Array of costs. + start : iterable + n-d index into `array` defining the starting point + end : iterable + n-d index into `array` defining the end point + fully_connected : bool (optional) + If True, diagonal moves are permitted, if False, only axial moves. + geometric : bool (optional) + If True, the MCP_Geometric class is used to calculate costs, if False, + the MCP base class is used. See the class documentation for + an explanation of the differences between MCP and MCP_Geometric. + + Returns + ------- + path : list + List of n-d index tuples defining the path from `start` to `end`. + cost : float + Cost of the path. If `geometric` is False, the cost of the path is + the sum of the values of `array` along the path. If `geometric` is + True, a finer computation is made (see the documentation of the + MCP_Geometric class). + + See Also + -------- + MCP, MCP_Geometric + + Examples + -------- + >>> import numpy as np + >>> from skimage.graph import route_through_array + >>> + >>> image = np.array([[1, 3], [10, 12]]) + >>> image + array([[ 1, 3], + [10, 12]]) + >>> # Forbid diagonal steps + >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False) + ([(0, 0), (0, 1), (1, 1)], 9.5) + >>> # Now allow diagonal steps: the path goes directly from start to end + >>> route_through_array(image, [0, 0], [1, 1]) + ([(0, 0), (1, 1)], 9.19238815542512) + >>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12) + >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False, + ... geometric=False) + ([(0, 0), (0, 1), (1, 1)], 16.0) + >>> # Larger array where we display the path that is selected + >>> image = np.arange((36)).reshape((6, 6)) + >>> image + array([[ 0, 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10, 11], + [12, 13, 14, 15, 16, 17], + [18, 19, 20, 21, 22, 23], + [24, 25, 26, 27, 28, 29], + [30, 31, 32, 33, 34, 35]]) + >>> # Find the path with lowest cost + >>> indices, weight = route_through_array(image, (0, 0), (5, 5)) + >>> indices = np.stack(indices, axis=-1) + >>> path = np.zeros_like(image) + >>> path[indices[0], indices[1]] = 1 + >>> path + array([[1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1]]) + + """ + start, end = tuple(start), tuple(end) + if geometric: + mcp_class = MCP_Geometric + else: + mcp_class = MCP + m = mcp_class(array, fully_connected=fully_connected) + costs, traceback_array = m.find_costs([start], [end]) + return m.traceback(end), costs[end] diff --git a/envs/kitoverlay/skimage/graph/spath.py b/envs/kitoverlay/skimage/graph/spath.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0d8da405b4fabac90ba95873c28565dde25766 --- /dev/null +++ b/envs/kitoverlay/skimage/graph/spath.py @@ -0,0 +1,83 @@ +import numpy as np +from . import _spath + + +def shortest_path(arr, reach=1, axis=-1, output_indexlist=False): + """Find the shortest path through an n-d array from one side to another. + + Parameters + ---------- + arr : ndarray of float64 + reach : int, optional + By default (``reach = 1``), the shortest path can only move + one row up or down for every step it moves forward (i.e., + the path gradient is limited to 1). `reach` defines the + number of elements that can be skipped along each non-axis + dimension at each step. + axis : int, optional + The axis along which the path must always move forward (default -1) + output_indexlist : bool, optional + See return value `p` for explanation. + + Returns + ------- + p : iterable of int + For each step along `axis`, the coordinate of the shortest path. + If `output_indexlist` is True, then the path is returned as a list of + n-d tuples that index into `arr`. If False, then the path is returned + as an array listing the coordinates of the path along the non-axis + dimensions for each step along the axis dimension. That is, + `p.shape == (arr.shape[axis], arr.ndim-1)` except that p is squeezed + before returning so if `arr.ndim == 2`, then + `p.shape == (arr.shape[axis],)` + cost : float + Cost of path. This is the absolute sum of all the + differences along the path. + + """ + # First: calculate the valid moves from any given position. Basically, + # always move +1 along the given axis, and then can move anywhere within + # a grid defined by the reach. + if axis < 0: + axis += arr.ndim + offset_ind_shape = (2 * reach + 1,) * (arr.ndim - 1) + offset_indices = np.indices(offset_ind_shape) - reach + offset_indices = np.insert(offset_indices, axis, np.ones(offset_ind_shape), axis=0) + offset_size = np.multiply.reduce(offset_ind_shape) + offsets = np.reshape(offset_indices, (arr.ndim, offset_size), order='F').T + + # Valid starting positions are anywhere on the hyperplane defined by + # position 0 on the given axis. Ending positions are anywhere on the + # hyperplane at position -1 along the same. + non_axis_shape = arr.shape[:axis] + arr.shape[axis + 1 :] + non_axis_indices = np.indices(non_axis_shape) + non_axis_size = np.multiply.reduce(non_axis_shape) + start_indices = np.insert(non_axis_indices, axis, np.zeros(non_axis_shape), axis=0) + starts = np.reshape(start_indices, (arr.ndim, non_axis_size), order='F').T + end_indices = np.insert( + non_axis_indices, + axis, + np.full(non_axis_shape, -1, dtype=non_axis_indices.dtype), + axis=0, + ) + ends = np.reshape(end_indices, (arr.ndim, non_axis_size), order='F').T + + # Find the minimum-cost path to one of the end-points + m = _spath.MCP_Diff(arr, offsets=offsets) + costs, traceback = m.find_costs(starts, ends, find_all_ends=False) + + # Figure out which end-point was found + for end in ends: + cost = costs[tuple(end)] + if cost != np.inf: + break + traceback = m.traceback(end) + + if not output_indexlist: + traceback = np.array(traceback) + traceback = np.concatenate( + [traceback[:, :axis], traceback[:, axis + 1 :]], axis=1 + ) + traceback = np.squeeze(traceback) + + return traceback, cost diff --git a/envs/kitoverlay/skimage/registration/__init__.py b/envs/kitoverlay/skimage/registration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8691f90519adedffb3a80eff78b24307ac8949cb --- /dev/null +++ b/envs/kitoverlay/skimage/registration/__init__.py @@ -0,0 +1,5 @@ +"""Image registration algorithms, e.g., optical flow or phase cross correlation.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/registration/__init__.pyi b/envs/kitoverlay/skimage/registration/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bf941f9a362bb804e6cd58af5b5cdbe26abd9925 --- /dev/null +++ b/envs/kitoverlay/skimage/registration/__init__.pyi @@ -0,0 +1,8 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = ['optical_flow_ilk', 'optical_flow_tvl1', 'phase_cross_correlation'] + +from ._optical_flow import optical_flow_tvl1, optical_flow_ilk +from ._phase_cross_correlation import phase_cross_correlation diff --git a/envs/kitoverlay/skimage/registration/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/registration/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44836082be947cc30b5415ee4a01f3d0bea0f257 Binary files /dev/null and b/envs/kitoverlay/skimage/registration/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/registration/__pycache__/_masked_phase_cross_correlation.cpython-311.pyc b/envs/kitoverlay/skimage/registration/__pycache__/_masked_phase_cross_correlation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddab2bf3c9e5d27073eeee4ad1380ef97a66b7ff Binary files /dev/null and b/envs/kitoverlay/skimage/registration/__pycache__/_masked_phase_cross_correlation.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow.cpython-311.pyc b/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82414d930aba7d2c0081985d669c9bd24815d319 Binary files /dev/null and b/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow_utils.cpython-311.pyc b/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..021071440bb037cb4f23ec5ff1fab043406c12a7 Binary files /dev/null and b/envs/kitoverlay/skimage/registration/__pycache__/_optical_flow_utils.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/registration/__pycache__/_phase_cross_correlation.cpython-311.pyc b/envs/kitoverlay/skimage/registration/__pycache__/_phase_cross_correlation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75d75073061c912e22ab6a3c49a626ddc3de4aaf Binary files /dev/null and b/envs/kitoverlay/skimage/registration/__pycache__/_phase_cross_correlation.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/registration/_masked_phase_cross_correlation.py b/envs/kitoverlay/skimage/registration/_masked_phase_cross_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..a37e8789b5b98604a7513287d4fc8472d30dfac2 --- /dev/null +++ b/envs/kitoverlay/skimage/registration/_masked_phase_cross_correlation.py @@ -0,0 +1,306 @@ +""" +Implementation of the masked normalized cross-correlation. + +Based on the following publication: +D. Padfield. Masked object registration in the Fourier domain. +IEEE Transactions on Image Processing (2012) + +and the author's original MATLAB implementation, available on this website: +http://www.dirkpadfield.com/ +""" + +from functools import partial + +import numpy as np +import scipy.fft as fftmodule +from scipy.fft import next_fast_len + +from .._shared.utils import _supported_float_type + + +def _masked_phase_cross_correlation( + reference_image, moving_image, reference_mask, moving_mask=None, overlap_ratio=0.3 +): + """Masked image translation registration by masked normalized + cross-correlation. + + Parameters + ---------- + reference_image : ndarray + Reference image. + moving_image : ndarray + Image to register. Must be same dimensionality as ``reference_image``, + but not necessarily the same size. + reference_mask : ndarray + Boolean mask for ``reference_image``. The mask should evaluate + to ``True`` (or 1) on valid pixels. ``reference_mask`` should + have the same shape as ``reference_image``. + moving_mask : ndarray or None, optional + Boolean mask for ``moving_image``. The mask should evaluate to ``True`` + (or 1) on valid pixels. ``moving_mask`` should have the same shape + as ``moving_image``. If ``None``, ``reference_mask`` will be used. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. + + Returns + ------- + shifts : ndarray + Shift vector (in pixels) required to register ``moving_image`` + with ``reference_image``. Axis ordering is consistent with numpy. + + References + ---------- + .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + + """ + if moving_mask is None: + if reference_image.shape != moving_image.shape: + raise ValueError( + "Input images have different shapes, moving_mask must " + "be explicitly set." + ) + moving_mask = reference_mask.astype(bool) + + # We need masks to be of the same size as their respective images + for im, mask in [(reference_image, reference_mask), (moving_image, moving_mask)]: + if im.shape != mask.shape: + raise ValueError("Image sizes must match their respective mask sizes.") + + xcorr = cross_correlate_masked( + moving_image, + reference_image, + moving_mask, + reference_mask, + axes=tuple(range(moving_image.ndim)), + mode='full', + overlap_ratio=overlap_ratio, + ) + + # Generalize to the average of multiple equal maxima + maxima = np.stack(np.nonzero(xcorr == xcorr.max()), axis=1) + center = np.mean(maxima, axis=0) + shifts = center - np.array(reference_image.shape) + 1 + + # The mismatch in size will impact the center location of the + # cross-correlation + size_mismatch = np.array(moving_image.shape) - np.array(reference_image.shape) + + return -shifts + (size_mismatch / 2) + + +def cross_correlate_masked( + arr1, arr2, m1, m2, mode='full', axes=(-2, -1), overlap_ratio=0.3 +): + """ + Masked normalized cross-correlation between arrays. + + Parameters + ---------- + arr1 : ndarray + First array. + arr2 : ndarray + Seconds array. The dimensions of `arr2` along axes that are not + transformed should be equal to that of `arr1`. + m1 : ndarray + Mask of `arr1`. The mask should evaluate to `True` + (or 1) on valid pixels. `m1` should have the same shape as `arr1`. + m2 : ndarray + Mask of `arr2`. The mask should evaluate to `True` + (or 1) on valid pixels. `m2` should have the same shape as `arr2`. + mode : {'full', 'same'}, optional + 'full': + This returns the convolution at each point of overlap. At + the end-points of the convolution, the signals do not overlap + completely, and boundary effects may be seen. + 'same': + The output is the same size as `arr1`, centered with respect + to the `‘full’` output. Boundary effects are less prominent. + axes : tuple of ints, optional + Axes along which to compute the cross-correlation. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. + + Returns + ------- + out : ndarray + Masked normalized cross-correlation. + + Raises + ------ + ValueError : if correlation `mode` is not valid, or array dimensions along + non-transformation axes are not equal. + + References + ---------- + .. [1] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [2] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + """ + if mode not in {'full', 'same'}: + raise ValueError(f"Correlation mode '{mode}' is not valid.") + + fixed_image = np.asarray(arr1) + moving_image = np.asarray(arr2) + float_dtype = _supported_float_type((fixed_image.dtype, moving_image.dtype)) + if float_dtype.kind == 'c': + raise ValueError("complex-valued arr1, arr2 are not supported") + + fixed_image = fixed_image.astype(float_dtype) + fixed_mask = np.array(m1, dtype=bool) + moving_image = moving_image.astype(float_dtype) + moving_mask = np.array(m2, dtype=bool) + eps = np.finfo(float_dtype).eps + + # Array dimensions along non-transformation axes should be equal. + all_axes = set(range(fixed_image.ndim)) + for axis in all_axes - set(axes): + if fixed_image.shape[axis] != moving_image.shape[axis]: + raise ValueError( + f'Array shapes along non-transformation axes should be ' + f'equal, but dimensions along axis {axis} are not.' + ) + + # Determine final size along transformation axes + # Note that it might be faster to compute Fourier transform in a slightly + # larger shape (`fast_shape`). Then, after all fourier transforms are done, + # we slice back to`final_shape` using `final_slice`. + final_shape = list(arr1.shape) + for axis in axes: + final_shape[axis] = fixed_image.shape[axis] + moving_image.shape[axis] - 1 + final_shape = tuple(final_shape) + final_slice = tuple([slice(0, int(sz)) for sz in final_shape]) + + # Extent transform axes to the next fast length (i.e. multiple of 3, 5, or + # 7) + fast_shape = tuple([next_fast_len(final_shape[ax]) for ax in axes]) + + # We use the new scipy.fft because they allow leaving the transform axes + # unchanged which was not possible with scipy.fftpack's + # fftn/ifftn in older versions of SciPy. + # E.g. arr shape (2, 3, 7), transform along axes (0, 1) with shape (4, 4) + # results in arr_fft shape (4, 4, 7) + fft = partial(fftmodule.fftn, s=fast_shape, axes=axes) + _ifft = partial(fftmodule.ifftn, s=fast_shape, axes=axes) + + def ifft(x): + return _ifft(x).real + + fixed_image[np.logical_not(fixed_mask)] = 0.0 + moving_image[np.logical_not(moving_mask)] = 0.0 + + # N-dimensional analog to rotation by 180deg is flip over all relevant axes. + # See [1] for discussion. + rotated_moving_image = _flip(moving_image, axes=axes) + rotated_moving_mask = _flip(moving_mask, axes=axes) + + fixed_fft = fft(fixed_image) + rotated_moving_fft = fft(rotated_moving_image) + fixed_mask_fft = fft(fixed_mask.astype(float_dtype)) + rotated_moving_mask_fft = fft(rotated_moving_mask.astype(float_dtype)) + + # Calculate overlap of masks at every point in the convolution. + # Locations with high overlap should not be taken into account. + number_overlap_masked_px = ifft(rotated_moving_mask_fft * fixed_mask_fft) + number_overlap_masked_px[:] = np.round(number_overlap_masked_px) + number_overlap_masked_px[:] = np.fmax(number_overlap_masked_px, eps) + masked_correlated_fixed_fft = ifft(rotated_moving_mask_fft * fixed_fft) + masked_correlated_rotated_moving_fft = ifft(fixed_mask_fft * rotated_moving_fft) + + numerator = ifft(rotated_moving_fft * fixed_fft) + numerator -= ( + masked_correlated_fixed_fft + * masked_correlated_rotated_moving_fft + / number_overlap_masked_px + ) + + fixed_squared_fft = fft(np.square(fixed_image)) + fixed_denom = ifft(rotated_moving_mask_fft * fixed_squared_fft) + fixed_denom -= np.square(masked_correlated_fixed_fft) / number_overlap_masked_px + fixed_denom[:] = np.fmax(fixed_denom, 0.0) + + rotated_moving_squared_fft = fft(np.square(rotated_moving_image)) + moving_denom = ifft(fixed_mask_fft * rotated_moving_squared_fft) + moving_denom -= ( + np.square(masked_correlated_rotated_moving_fft) / number_overlap_masked_px + ) + moving_denom[:] = np.fmax(moving_denom, 0.0) + + denom = np.sqrt(fixed_denom * moving_denom) + + # Slice back to expected convolution shape. + numerator = numerator[final_slice] + denom = denom[final_slice] + number_overlap_masked_px = number_overlap_masked_px[final_slice] + + if mode == 'same': + _centering = partial(_centered, newshape=fixed_image.shape, axes=axes) + denom = _centering(denom) + numerator = _centering(numerator) + number_overlap_masked_px = _centering(number_overlap_masked_px) + + # Pixels where `denom` is very small will introduce large + # numbers after division. To get around this problem, + # we zero-out problematic pixels. + tol = 1e3 * eps * np.max(np.abs(denom), axis=axes, keepdims=True) + nonzero_indices = denom > tol + + # explicitly set out dtype for compatibility with SciPy < 1.4, where + # fftmodule will be numpy.fft which always uses float64 dtype. + out = np.zeros_like(denom, dtype=float_dtype) + out[nonzero_indices] = numerator[nonzero_indices] / denom[nonzero_indices] + np.clip(out, a_min=-1, a_max=1, out=out) + + # Apply overlap ratio threshold + number_px_threshold = overlap_ratio * np.max( + number_overlap_masked_px, axis=axes, keepdims=True + ) + out[number_overlap_masked_px < number_px_threshold] = 0.0 + + return out + + +def _centered(arr, newshape, axes): + """Return the center `newshape` portion of `arr`, leaving axes not + in `axes` untouched.""" + newshape = np.asarray(newshape) + currshape = np.array(arr.shape) + + slices = [slice(None, None)] * arr.ndim + + for ax in axes: + startind = (currshape[ax] - newshape[ax]) // 2 + endind = startind + newshape[ax] + slices[ax] = slice(startind, endind) + + return arr[tuple(slices)] + + +def _flip(arr, axes=None): + """Reverse array over many axes. Generalization of arr[::-1] for many + dimensions. If `axes` is `None`, flip along all axes.""" + if axes is None: + reverse = [slice(None, None, -1)] * arr.ndim + else: + reverse = [slice(None, None, None)] * arr.ndim + for axis in axes: + reverse[axis] = slice(None, None, -1) + + return arr[tuple(reverse)] diff --git a/envs/kitoverlay/skimage/registration/_optical_flow.py b/envs/kitoverlay/skimage/registration/_optical_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b11f363a8ceb1e9806c4621871656c10871f8a --- /dev/null +++ b/envs/kitoverlay/skimage/registration/_optical_flow.py @@ -0,0 +1,429 @@ +"""TV-L1 optical flow algorithm implementation.""" + +from functools import partial +from itertools import combinations_with_replacement + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.filters import gaussian as gaussian_filter +from .._shared.utils import _supported_float_type +from ..transform import warp +from ._optical_flow_utils import _coarse_to_fine, _get_warp_points + + +def _tvl1( + reference_image, + moving_image, + flow0, + attachment, + tightness, + num_warp, + num_iter, + tol, + prefilter, +): + """TV-L1 solver for optical flow estimation. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + flow0 : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + Initialization for the vector field. + attachment : float + Attachment parameter. The smaller this parameter is, + the smoother is the solutions. + tightness : float + Tightness parameter. It should have a small value in order to + maintain attachment and regularization parts in + correspondence. + num_warp : int + Number of times moving_image is warped. + num_iter : int + Number of fixed point iteration. + tol : float + Tolerance used as stopping criterion based on the L² distance + between two consecutive values of (u, v). + prefilter : bool + Whether to prefilter the estimated optical flow before each + image warp. + + Returns + ------- + flow : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + """ + + dtype = reference_image.dtype + grid = np.meshgrid( + *[np.arange(n, dtype=dtype) for n in reference_image.shape], + indexing='ij', + sparse=True, + ) + + # dt corresponds to tau in [3]_, i.e. the time step + dt = 0.5 / reference_image.ndim + reg_num_iter = 2 + f0 = attachment * tightness + f1 = dt / tightness + tol *= reference_image.size + + flow_current = flow_previous = flow0 + + g = np.zeros((reference_image.ndim,) + reference_image.shape, dtype=dtype) + proj = np.zeros( + ( + reference_image.ndim, + reference_image.ndim, + ) + + reference_image.shape, + dtype=dtype, + ) + + s_g = [ + slice(None), + ] * g.ndim + s_p = [ + slice(None), + ] * proj.ndim + s_d = [ + slice(None), + ] * (proj.ndim - 2) + + for _ in range(num_warp): + if prefilter: + flow_current = ndi.median_filter( + flow_current, [1] + reference_image.ndim * [3] + ) + + image1_warp = warp( + moving_image, _get_warp_points(grid, flow_current), mode='edge' + ) + grad = np.array(np.gradient(image1_warp)) + NI = (grad * grad).sum(0) + NI[NI == 0] = 1 + + rho_0 = image1_warp - reference_image - (grad * flow_current).sum(0) + + for _ in range(num_iter): + # Data term + + rho = rho_0 + (grad * flow_current).sum(0) + + idx = abs(rho) <= f0 * NI + + flow_auxiliary = flow_current + + flow_auxiliary[:, idx] -= rho[idx] * grad[:, idx] / NI[idx] + + idx = ~idx + srho = f0 * np.sign(rho[idx]) + flow_auxiliary[:, idx] -= srho * grad[:, idx] + + # Regularization term + flow_current = flow_auxiliary.copy() + + for idx in range(reference_image.ndim): + s_p[0] = idx + for _ in range(reg_num_iter): + for ax in range(reference_image.ndim): + s_g[0] = ax + s_g[ax + 1] = slice(0, -1) + g[tuple(s_g)] = np.diff(flow_current[idx], axis=ax) + s_g[ax + 1] = slice(None) + + norm = np.sqrt((g**2).sum(0))[np.newaxis, ...] + norm *= f1 + norm += 1.0 + proj[idx] -= dt * g + proj[idx] /= norm + + # d will be the (negative) divergence of proj[idx] + d = -proj[idx].sum(0) + for ax in range(reference_image.ndim): + s_p[1] = ax + s_p[ax + 2] = slice(0, -1) + s_d[ax] = slice(1, None) + d[tuple(s_d)] += proj[tuple(s_p)] + s_p[ax + 2] = slice(None) + s_d[ax] = slice(None) + + flow_current[idx] = flow_auxiliary[idx] + d + + flow_previous -= flow_current # The difference as stopping criteria + if (flow_previous * flow_previous).sum() < tol: + break + + flow_previous = flow_current + + return flow_current + + +def optical_flow_tvl1( + reference_image, + moving_image, + *, + attachment=15, + tightness=0.3, + num_warp=5, + num_iter=10, + tol=1e-4, + prefilter=False, + dtype=np.float32, +): + r"""Coarse to fine optical flow estimator. + + The TV-L1 solver is applied at each level of the image + pyramid. TV-L1 is a popular algorithm for optical flow estimation + introduced by Zack et al. [1]_, improved in [2]_ and detailed in [3]_. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + attachment : float, optional + Attachment parameter (:math:`\lambda` in [1]_). The smaller + this parameter is, the smoother the returned result will be. + tightness : float, optional + Tightness parameter (:math:`\theta` in [1]_). It should have + a small value in order to maintain attachment and + regularization parts in correspondence. + num_warp : int, optional + Number of times moving_image is warped. + num_iter : int, optional + Number of fixed point iteration. + tol : float, optional + Tolerance used as stopping criterion based on the L² distance + between two consecutive values of (u, v). + prefilter : bool, optional + Whether to prefilter the estimated optical flow before each + image warp. When True, a median filter with window size 3 + along each axis is applied. This helps to remove potential + outliers. + dtype : dtype, optional + Output data type: must be floating point. Single precision + provides good results and saves memory usage and computation + time compared to double precision. + + Returns + ------- + flow : ndarray, shape (image0.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + Notes + ----- + Color images are not supported. + + References + ---------- + .. [1] Zach, C., Pock, T., & Bischof, H. (2007, September). A + duality based approach for realtime TV-L 1 optical flow. In Joint + pattern recognition symposium (pp. 214-223). Springer, Berlin, + Heidelberg. :DOI:`10.1007/978-3-540-74936-3_22` + .. [2] Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, + D. (2009). An improved algorithm for TV-L 1 optical flow. In + Statistical and geometrical approaches to visual motion analysis + (pp. 23-45). Springer, Berlin, Heidelberg. + :DOI:`10.1007/978-3-642-03061-1_2` + .. [3] Pérez, J. S., Meinhardt-Llopis, E., & Facciolo, + G. (2013). TV-L1 optical flow estimation. Image Processing On + Line, 2013, 137-150. :DOI:`10.5201/ipol.2013.26` + + Examples + -------- + >>> from skimage.color import rgb2gray + >>> from skimage.data import stereo_motorcycle + >>> from skimage.registration import optical_flow_tvl1 + >>> image0, image1, disp = stereo_motorcycle() + >>> # --- Convert the images to gray level: color is not supported. + >>> image0 = rgb2gray(image0) + >>> image1 = rgb2gray(image1) + >>> flow = optical_flow_tvl1(image1, image0) + + """ + + solver = partial( + _tvl1, + attachment=attachment, + tightness=tightness, + num_warp=num_warp, + num_iter=num_iter, + tol=tol, + prefilter=prefilter, + ) + + if np.dtype(dtype) != _supported_float_type(dtype): + msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'" + raise ValueError(msg) + + return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype) + + +def _ilk(reference_image, moving_image, flow0, radius, num_warp, gaussian, prefilter): + """Iterative Lucas-Kanade (iLK) solver for optical flow estimation. + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + flow0 : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + Initialization for the vector field. + radius : int + Radius of the window considered around each pixel. + num_warp : int + Number of times moving_image is warped. + gaussian : bool + if True, a gaussian kernel is used for the local + integration. Otherwise, a uniform kernel is used. + prefilter : bool + Whether to prefilter the estimated optical flow before each + image warp. This helps to remove potential outliers. + + Returns + ------- + flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + """ + dtype = reference_image.dtype + ndim = reference_image.ndim + size = 2 * radius + 1 + + if gaussian: + sigma = ndim * (size / 4,) + filter_func = partial(gaussian_filter, sigma=sigma, mode='mirror') + else: + filter_func = partial(ndi.uniform_filter, size=ndim * (size,), mode='mirror') + + flow = flow0 + # For each pixel location (i, j), the optical flow X = flow[:, i, j] + # is the solution of the ndim x ndim linear system + # A[i, j] * X = b[i, j] + A = np.zeros(reference_image.shape + (ndim, ndim), dtype=dtype) + b = np.zeros(reference_image.shape + (ndim, 1), dtype=dtype) + + grid = np.meshgrid( + *[np.arange(n, dtype=dtype) for n in reference_image.shape], + indexing='ij', + sparse=True, + ) + + for _ in range(num_warp): + if prefilter: + flow = ndi.median_filter(flow, (1,) + ndim * (3,)) + + moving_image_warp = warp( + moving_image, _get_warp_points(grid, flow), mode='edge' + ) + grad = np.stack(np.gradient(moving_image_warp), axis=0) + error_image = (grad * flow).sum(axis=0) + reference_image - moving_image_warp + + # Local linear systems creation + for i, j in combinations_with_replacement(range(ndim), 2): + A[..., i, j] = A[..., j, i] = filter_func(grad[i] * grad[j]) + + for i in range(ndim): + b[..., i, 0] = filter_func(grad[i] * error_image) + + # Don't consider badly conditioned linear systems + idx = abs(np.linalg.det(A)) < 1e-14 + A[idx] = np.eye(ndim, dtype=dtype) + b[idx] = 0 + + # Solve the local linear systems + flow = np.moveaxis(np.linalg.solve(A, b)[..., 0], ndim, 0) + + return flow + + +def optical_flow_ilk( + reference_image, + moving_image, + *, + radius=7, + num_warp=10, + gaussian=False, + prefilter=False, + dtype=np.float32, +): + """Coarse to fine optical flow estimator. + + The iterative Lucas-Kanade (iLK) solver is applied at each level + of the image pyramid. iLK [1]_ is a fast and robust alternative to + TVL1 algorithm although less accurate for rendering flat surfaces + and object boundaries (see [2]_). + + Parameters + ---------- + reference_image : ndarray, shape (M, N[, P[, ...]]) + The first grayscale image of the sequence. + moving_image : ndarray, shape (M, N[, P[, ...]]) + The second grayscale image of the sequence. + radius : int, optional + Radius of the window considered around each pixel. + num_warp : int, optional + Number of times moving_image is warped. + gaussian : bool, optional + If True, a Gaussian kernel is used for the local + integration. Otherwise, a uniform kernel is used. + prefilter : bool, optional + Whether to prefilter the estimated optical flow before each + image warp. When True, a median filter with window size 3 + along each axis is applied. This helps to remove potential + outliers. + dtype : dtype, optional + Output data type: must be floating point. Single precision + provides good results and saves memory usage and computation + time compared to double precision. + + Returns + ------- + flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]]) + The estimated optical flow components for each axis. + + Notes + ----- + - The implemented algorithm is described in **Table2** of [1]_. + - Color images are not supported. + + References + ---------- + .. [1] Le Besnerais, G., & Champagnat, F. (2005, September). Dense + optical flow by iterative local window registration. In IEEE + International Conference on Image Processing 2005 (Vol. 1, + pp. I-137). IEEE. :DOI:`10.1109/ICIP.2005.1529706` + .. [2] Plyer, A., Le Besnerais, G., & Champagnat, + F. (2016). Massively parallel Lucas Kanade optical flow for + real-time video processing applications. Journal of Real-Time + Image Processing, 11(4), 713-730. :DOI:`10.1007/s11554-014-0423-0` + + Examples + -------- + >>> from skimage.color import rgb2gray + >>> from skimage.data import stereo_motorcycle + >>> from skimage.registration import optical_flow_ilk + >>> reference_image, moving_image, disp = stereo_motorcycle() + >>> # --- Convert the images to gray level: color is not supported. + >>> reference_image = rgb2gray(reference_image) + >>> moving_image = rgb2gray(moving_image) + >>> flow = optical_flow_ilk(moving_image, reference_image) + + """ + + solver = partial( + _ilk, radius=radius, num_warp=num_warp, gaussian=gaussian, prefilter=prefilter + ) + + if np.dtype(dtype) != _supported_float_type(dtype): + msg = f"dtype={dtype} is not supported. Try 'float32' or 'float64.'" + raise ValueError(msg) + + return _coarse_to_fine(reference_image, moving_image, solver, dtype=dtype) diff --git a/envs/kitoverlay/skimage/registration/_optical_flow_utils.py b/envs/kitoverlay/skimage/registration/_optical_flow_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..51821b48d4c28a54b7e13a2980a845f20d9d2cc4 --- /dev/null +++ b/envs/kitoverlay/skimage/registration/_optical_flow_utils.py @@ -0,0 +1,150 @@ +"""Common tools to optical flow algorithms.""" + +import numpy as np +from scipy import ndimage as ndi + +from ..transform import pyramid_reduce +from ..util.dtype import _convert + + +def _get_warp_points(grid, flow): + """Compute warp point coordinates. + + Parameters + ---------- + grid : iterable + The sparse grid to be warped (obtained using + ``np.meshgrid(..., sparse=True)).``) + flow : ndarray + The warping motion field. + + Returns + ------- + out : ndarray + The warp point coordinates. + + """ + out = flow.copy() + for idx, g in enumerate(grid): + out[idx, ...] += g + return out + + +def _resize_flow(flow, shape): + """Rescale the values of the vector field (u, v) to the desired shape. + + The values of the output vector field are scaled to the new + resolution. + + Parameters + ---------- + flow : ndarray + The motion field to be processed. + shape : iterable + Couple of integers representing the output shape. + + Returns + ------- + rflow : ndarray + The resized and rescaled motion field. + + """ + + scale = [n / o for n, o in zip(shape, flow.shape[1:])] + scale_factor = np.array(scale, dtype=flow.dtype) + + for _ in shape: + scale_factor = scale_factor[..., np.newaxis] + + rflow = scale_factor * ndi.zoom( + flow, [1] + scale, order=0, mode='nearest', prefilter=False + ) + + return rflow + + +def _get_pyramid(I, downscale=2.0, nlevel=10, min_size=16): + """Construct image pyramid. + + Parameters + ---------- + I : ndarray + The image to be preprocessed (Grayscale or RGB). + downscale : float + The pyramid downscale factor. + nlevel : int + The maximum number of pyramid levels. + min_size : int + The minimum size for any dimension of the pyramid levels. + + Returns + ------- + pyramid : list[ndarray] + The coarse to fine images pyramid. + + """ + + pyramid = [I] + size = min(I.shape) + count = 1 + + while (count < nlevel) and (size > downscale * min_size): + J = pyramid_reduce(pyramid[-1], downscale, channel_axis=None) + pyramid.append(J) + size = min(J.shape) + count += 1 + + return pyramid[::-1] + + +def _coarse_to_fine( + I0, I1, solver, downscale=2, nlevel=10, min_size=16, dtype=np.float32 +): + """Generic coarse to fine solver. + + Parameters + ---------- + I0 : ndarray + The first grayscale image of the sequence. + I1 : ndarray + The second grayscale image of the sequence. + solver : callable + The solver applied at each pyramid level. + downscale : float + The pyramid downscale factor. + nlevel : int + The maximum number of pyramid levels. + min_size : int + The minimum size for any dimension of the pyramid levels. + dtype : dtype + Output data type. + + Returns + ------- + flow : ndarray + The estimated optical flow components for each axis. + + """ + + if I0.shape != I1.shape: + raise ValueError("Input images should have the same shape") + + if np.dtype(dtype).char not in 'efdg': + raise ValueError("Only floating point data type are valid" " for optical flow") + + pyramid = list( + zip( + _get_pyramid(_convert(I0, dtype), downscale, nlevel, min_size), + _get_pyramid(_convert(I1, dtype), downscale, nlevel, min_size), + ) + ) + + # Initialization to 0 at coarsest level. + flow = np.zeros((pyramid[0][0].ndim,) + pyramid[0][0].shape, dtype=dtype) + + flow = solver(pyramid[0][0], pyramid[0][1], flow) + + for J0, J1 in pyramid[1:]: + flow = solver(J0, J1, _resize_flow(flow, J0.shape)) + + return flow diff --git a/envs/kitoverlay/skimage/registration/_phase_cross_correlation.py b/envs/kitoverlay/skimage/registration/_phase_cross_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..a1c382694e68289c4f6756a40b433655980ebcf7 --- /dev/null +++ b/envs/kitoverlay/skimage/registration/_phase_cross_correlation.py @@ -0,0 +1,420 @@ +""" +Port of Manuel Guizar's code from: +http://www.mathworks.com/matlabcentral/fileexchange/18401-efficient-subpixel-image-registration-by-cross-correlation +""" + +import itertools +import warnings + +import numpy as np +from scipy.fft import fftn, ifftn, fftfreq +from scipy import ndimage as ndi + +from ._masked_phase_cross_correlation import _masked_phase_cross_correlation + + +def _upsampled_dft(data, upsampled_region_size, upsample_factor=1, axis_offsets=None): + """ + Upsampled DFT by matrix multiplication. + + This code is intended to provide the same result as if the following + operations were performed: + - Embed the array "data" in an array that is ``upsample_factor`` times + larger in each dimension. ifftshift to bring the center of the + image to (1,1). + - Take the FFT of the larger array. + - Extract an ``[upsampled_region_size]`` region of the result, starting + with the ``[axis_offsets+1]`` element. + + It achieves this result by computing the DFT in the output array without + the need to zeropad. Much faster and memory efficient than the zero-padded + FFT approach if ``upsampled_region_size`` is much smaller than + ``data.size * upsample_factor``. + + Parameters + ---------- + data : array + The input data array (DFT of original data) to upsample. + upsampled_region_size : integer or tuple of integers, optional + The size of the region to be sampled. If one integer is provided, it + is duplicated up to the dimensionality of ``data``. + upsample_factor : integer, optional + The upsampling factor. Defaults to 1. + axis_offsets : tuple of integers, optional + The offsets of the region to be sampled. Defaults to None (uses + image center) + + Returns + ------- + output : ndarray + The upsampled DFT of the specified region. + """ + # if people pass in an integer, expand it to a list of equal-sized sections + if not hasattr(upsampled_region_size, "__iter__"): + upsampled_region_size = [ + upsampled_region_size, + ] * data.ndim + else: + if len(upsampled_region_size) != data.ndim: + raise ValueError( + "shape of upsampled region sizes must be equal " + "to input data's number of dimensions." + ) + + if axis_offsets is None: + axis_offsets = [ + 0, + ] * data.ndim + else: + if len(axis_offsets) != data.ndim: + raise ValueError( + "number of axis offsets must be equal to input " + "data's number of dimensions." + ) + + im2pi = 1j * 2 * np.pi + + dim_properties = list(zip(data.shape, upsampled_region_size, axis_offsets)) + + for n_items, ups_size, ax_offset in dim_properties[::-1]: + kernel = (np.arange(ups_size) - ax_offset)[:, None] * fftfreq( + n_items, upsample_factor + ) + kernel = np.exp(-im2pi * kernel) + # use kernel with same precision as the data + kernel = kernel.astype(data.dtype, copy=False) + + # Equivalent to: + # data[i, j, k] = kernel[i, :] @ data[j, k].T + data = np.tensordot(kernel, data, axes=(1, -1)) + return data + + +def _compute_phasediff(cross_correlation_max): + """ + Compute global phase difference between the two images (should be + zero if images are non-negative). + + Parameters + ---------- + cross_correlation_max : complex + The complex value of the cross correlation at its maximum point. + """ + return np.arctan2(cross_correlation_max.imag, cross_correlation_max.real) + + +def _compute_error(cross_correlation_max, src_amp, target_amp): + """ + Compute RMS error metric between ``src_image`` and ``target_image``. + + Parameters + ---------- + cross_correlation_max : complex + The complex value of the cross correlation at its maximum point. + src_amp : float + The normalized average image intensity of the source image + target_amp : float + The normalized average image intensity of the target image + """ + amp = src_amp * target_amp + if amp == 0: + warnings.warn( + "Could not determine RMS error between images with the normalized " + f"average intensities {src_amp!r} and {target_amp!r}. Either the " + "reference or moving image may be empty.", + UserWarning, + stacklevel=3, + ) + with np.errstate(invalid="ignore"): + error = 1.0 - cross_correlation_max * cross_correlation_max.conj() / amp + return np.sqrt(np.abs(error)) + + +def _disambiguate_shift(reference_image, moving_image, shift): + """Determine the correct real-space shift based on periodic shift. + + When determining a translation shift from phase cross-correlation in + Fourier space, the shift is only correct to within a period of the image + size along each axis, resulting in $2^n$ possible shifts, where $n$ is the + number of dimensions of the image. This function checks the + cross-correlation in real space for each of those shifts, and returns the + one with the highest cross-correlation. + + The strategy we use is to perform the shift on the moving image *using the + 'grid-wrap' mode* in `scipy.ndimage`. The moving image's original borders + then define $2^n$ quadrants, which we cross-correlate with the reference + image in turn using slicing. The entire operation is thus $O(2^n + m)$, + where $m$ is the number of pixels in the image (and typically dominates). + + Parameters + ---------- + reference_image : numpy array + The reference (non-moving) image. + moving_image : numpy array + The moving image: applying the shift to this image overlays it on the + reference image. Must be the same shape as the reference image. + shift : ndarray + The shift to apply to each axis of the moving image, *modulo* image + size. The length of ``shift`` must be equal to ``moving_image.ndim``. + + Returns + ------- + real_shift : ndarray + The shift disambiguated in real space. + """ + shape = reference_image.shape + positive_shift = [shift_i % s for shift_i, s in zip(shift, shape)] + negative_shift = [shift_i - s for shift_i, s in zip(positive_shift, shape)] + subpixel = np.any(np.array(shift) % 1 != 0) + interp_order = 3 if subpixel else 0 + shifted = ndi.shift(moving_image, shift, mode='grid-wrap', order=interp_order) + indices = np.round(positive_shift).astype(int) + splits_per_dim = [(slice(0, i), slice(i, None)) for i in indices] + max_corr = -1.0 + max_slice = None + for test_slice in itertools.product(*splits_per_dim): + reference_tile = np.reshape(reference_image[test_slice], -1) + moving_tile = np.reshape(shifted[test_slice], -1) + corr = -1.0 + if reference_tile.size > 2: + # In the case of zero std, np.corrcoef returns NaN and warns + # about division by zero. This is expected and handled below. + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=RuntimeWarning) + corr = np.corrcoef(reference_tile, moving_tile)[0, 1] + if corr > max_corr: + max_corr = corr + max_slice = test_slice + if max_slice is None: + warnings.warn( + f"Could not determine real-space shift for periodic shift {shift!r} " + f"as requested by `disambiguate=True` (disambiguation is degenerate).", + stacklevel=3, + ) + return shift + real_shift_acc = [] + for sl, pos_shift, neg_shift in zip(max_slice, positive_shift, negative_shift): + real_shift_acc.append(pos_shift if sl.stop is None else neg_shift) + + return np.array(real_shift_acc) + + +def phase_cross_correlation( + reference_image, + moving_image, + *, + upsample_factor=1, + space="real", + disambiguate=False, + reference_mask=None, + moving_mask=None, + overlap_ratio=0.3, + normalization="phase", +): + """Efficient subpixel image translation registration by cross-correlation. + + This code gives the same precision as the FFT upsampled cross-correlation + in a fraction of the computation time and with reduced memory requirements. + It obtains an initial estimate of the cross-correlation peak by an FFT and + then refines the shift estimation by upsampling the DFT only in a small + neighborhood of that estimate by means of a matrix-multiply DFT [1]_. + + Parameters + ---------- + reference_image : array + Reference image. + moving_image : array + Image to register. Must be same dimensionality as + ``reference_image``. + upsample_factor : int, optional + Upsampling factor. Images will be registered to within + ``1 / upsample_factor`` of a pixel. For example + ``upsample_factor == 20`` means the images will be registered + within 1/20th of a pixel. Default is 1 (no upsampling). + Not used if any of ``reference_mask`` or ``moving_mask`` is not None. + space : string, one of "real" or "fourier", optional + Defines how the algorithm interprets input data. "real" means + data will be FFT'd to compute the correlation, while "fourier" + data will bypass FFT of input data. Case insensitive. Not + used if any of ``reference_mask`` or ``moving_mask`` is not + None. + disambiguate : bool + The shift returned by this function is only accurate *modulo* the + image shape, due to the periodic nature of the Fourier transform. If + this parameter is set to ``True``, the *real* space cross-correlation + is computed for each possible shift, and the shift with the highest + cross-correlation within the overlapping area is returned. + reference_mask : ndarray + Boolean mask for ``reference_image``. The mask should evaluate + to ``True`` (or 1) on valid pixels. ``reference_mask`` should + have the same shape as ``reference_image``. + moving_mask : ndarray or None, optional + Boolean mask for ``moving_image``. The mask should evaluate to ``True`` + (or 1) on valid pixels. ``moving_mask`` should have the same shape + as ``moving_image``. If ``None``, ``reference_mask`` will be used. + overlap_ratio : float, optional + Minimum allowed overlap ratio between images. The correlation for + translations corresponding with an overlap ratio lower than this + threshold will be ignored. A lower `overlap_ratio` leads to smaller + maximum translation, while a higher `overlap_ratio` leads to greater + robustness against spurious matches due to small overlap between + masked images. Used only if one of ``reference_mask`` or + ``moving_mask`` is not None. + normalization : {"phase", None} + The type of normalization to apply to the cross-correlation. This + parameter is unused when masks (`reference_mask` and `moving_mask`) are + supplied. + + Returns + ------- + shift : ndarray + Shift vector (in pixels) required to register ``moving_image`` + with ``reference_image``. Axis ordering is consistent with + the axis order of the input array. + error : float + Translation invariant normalized RMS error between + ``reference_image`` and ``moving_image``. For masked cross-correlation + this error is not available and NaN is returned. + phasediff : float + Global phase difference between the two images (should be + zero if images are non-negative). For masked cross-correlation + this phase difference is not available and NaN is returned. + + Notes + ----- + The use of cross-correlation to estimate image translation has a long + history dating back to at least [2]_. The "phase correlation" + method (selected by ``normalization="phase"``) was first proposed in [3]_. + Publications [1]_ and [2]_ use an unnormalized cross-correlation + (``normalization=None``). Which form of normalization is better is + application-dependent. For example, the phase correlation method works + well in registering images under different illumination, but is not very + robust to noise. In a high noise scenario, the unnormalized method may be + preferable. + + When masks are provided, a masked normalized cross-correlation algorithm is + used [5]_, [6]_. + + References + ---------- + .. [1] Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, + "Efficient subpixel image registration algorithms," + Optics Letters 33, 156-158 (2008). :DOI:`10.1364/OL.33.000156` + .. [2] P. Anuta, Spatial registration of multispectral and multitemporal + digital imagery using fast Fourier transform techniques, IEEE Trans. + Geosci. Electron., vol. 8, no. 4, pp. 353–368, Oct. 1970. + :DOI:`10.1109/TGE.1970.271435`. + .. [3] C. D. Kuglin D. C. Hines. The phase correlation image alignment + method, Proceeding of IEEE International Conference on Cybernetics + and Society, pp. 163-165, New York, NY, USA, 1975, pp. 163–165. + .. [4] James R. Fienup, "Invariant error metrics for image reconstruction" + Optics Letters 36, 8352-8357 (1997). :DOI:`10.1364/AO.36.008352` + .. [5] Dirk Padfield. Masked Object Registration in the Fourier Domain. + IEEE Transactions on Image Processing, vol. 21(5), + pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402` + .. [6] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and + Pattern Recognition, pp. 2918-2925 (2010). + :DOI:`10.1109/CVPR.2010.5540032` + """ + if (reference_mask is not None) or (moving_mask is not None): + shift = _masked_phase_cross_correlation( + reference_image, moving_image, reference_mask, moving_mask, overlap_ratio + ) + return shift, np.nan, np.nan + + # images must be the same shape + if reference_image.shape != moving_image.shape: + raise ValueError("images must be same shape") + + # assume complex data is already in Fourier space + if space.lower() == 'fourier': + src_freq = reference_image + target_freq = moving_image + # real data needs to be fft'd. + elif space.lower() == 'real': + src_freq = fftn(reference_image) + target_freq = fftn(moving_image) + else: + raise ValueError('space argument must be "real" of "fourier"') + + # Whole-pixel shift - Compute cross-correlation by an IFFT + shape = src_freq.shape + image_product = src_freq * target_freq.conj() + if normalization == "phase": + eps = np.finfo(image_product.real.dtype).eps + image_product /= np.maximum(np.abs(image_product), 100 * eps) + elif normalization is not None: + raise ValueError("normalization must be either phase or None") + cross_correlation = ifftn(image_product) + + # Locate maximum + maxima = np.unravel_index( + np.argmax(np.abs(cross_correlation)), cross_correlation.shape + ) + midpoint = np.array([np.trunc(axis_size / 2) for axis_size in shape]) + + float_dtype = image_product.real.dtype + + shift = np.stack(maxima).astype(float_dtype, copy=False) + shift[shift > midpoint] -= np.array(shape)[shift > midpoint] + + if upsample_factor == 1: + src_amp = np.sum(np.real(src_freq * src_freq.conj())) + src_amp /= src_freq.size + target_amp = np.sum(np.real(target_freq * target_freq.conj())) + target_amp /= target_freq.size + CCmax = cross_correlation[maxima] + # If upsampling > 1, then refine estimate with matrix multiply DFT + else: + # Initial shift estimate in upsampled grid + upsample_factor = np.array(upsample_factor, dtype=float_dtype) + shift = np.round(shift * upsample_factor) / upsample_factor + upsampled_region_size = np.ceil(upsample_factor * 1.5) + # Center of output array at dftshift + 1 + dftshift = np.trunc(upsampled_region_size / 2.0) + # Matrix multiply DFT around the current shift estimate + sample_region_offset = dftshift - shift * upsample_factor + cross_correlation = _upsampled_dft( + image_product.conj(), + upsampled_region_size, + upsample_factor, + sample_region_offset, + ).conj() + # Locate maximum and map back to original pixel grid + maxima = np.unravel_index( + np.argmax(np.abs(cross_correlation)), cross_correlation.shape + ) + CCmax = cross_correlation[maxima] + + maxima = np.stack(maxima).astype(float_dtype, copy=False) + maxima -= dftshift + + shift += maxima / upsample_factor + + src_amp = np.sum(np.real(src_freq * src_freq.conj())) + target_amp = np.sum(np.real(target_freq * target_freq.conj())) + + # If its only one row or column the shift along that dimension has no + # effect. We set to zero. + for dim in range(src_freq.ndim): + if shape[dim] == 1: + shift[dim] = 0 + + if disambiguate: + if space.lower() != 'real': + reference_image = ifftn(reference_image) + moving_image = ifftn(moving_image) + shift = _disambiguate_shift(reference_image, moving_image, shift) + + # Redirect user to masked_phase_cross_correlation if NaNs are observed + if np.isnan(CCmax) or np.isnan(src_amp) or np.isnan(target_amp): + raise ValueError( + "NaN values found, please remove NaNs from your " + "input data or use the `reference_mask`/`moving_mask` " + "keywords, eg: " + "phase_cross_correlation(reference_image, moving_image, " + "reference_mask=~np.isnan(reference_image), " + "moving_mask=~np.isnan(moving_image))" + ) + + return shift, _compute_error(CCmax, src_amp, target_amp), _compute_phasediff(CCmax) diff --git a/envs/kitoverlay/skimage/segmentation/_chan_vese.py b/envs/kitoverlay/skimage/segmentation/_chan_vese.py new file mode 100644 index 0000000000000000000000000000000000000000..31c3f1e72af455fd3ba5405d768075b02212e4ff --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_chan_vese.py @@ -0,0 +1,365 @@ +import numpy as np +from scipy.ndimage import distance_transform_edt as distance + +from .._shared.utils import _supported_float_type + + +def _cv_calculate_variation(image, phi, mu, lambda1, lambda2, dt): + """Returns the variation of level set 'phi' based on algorithm parameters. + + This corresponds to equation (22) of the paper by Pascal Getreuer, + which computes the next iteration of the level set based on a current + level set. + + A full explanation regarding all the terms is beyond the scope of the + present description, but there is one difference of particular import. + In the original algorithm, convergence is accelerated, and required + memory is reduced, by using a single array. This array, therefore, is a + combination of non-updated and updated values. If this were to be + implemented in python, this would require a double loop, where the + benefits of having fewer iterations would be outweided by massively + increasing the time required to perform each individual iteration. A + similar approach is used by Rami Cohen, and it is from there that the + C1-4 notation is taken. + """ + eta = 1e-16 + P = np.pad(phi, 1, mode='edge') + + phixp = P[1:-1, 2:] - P[1:-1, 1:-1] + phixn = P[1:-1, 1:-1] - P[1:-1, :-2] + phix0 = (P[1:-1, 2:] - P[1:-1, :-2]) / 2.0 + + phiyp = P[2:, 1:-1] - P[1:-1, 1:-1] + phiyn = P[1:-1, 1:-1] - P[:-2, 1:-1] + phiy0 = (P[2:, 1:-1] - P[:-2, 1:-1]) / 2.0 + + C1 = 1.0 / np.sqrt(eta + phixp**2 + phiy0**2) + C2 = 1.0 / np.sqrt(eta + phixn**2 + phiy0**2) + C3 = 1.0 / np.sqrt(eta + phix0**2 + phiyp**2) + C4 = 1.0 / np.sqrt(eta + phix0**2 + phiyn**2) + + K = P[1:-1, 2:] * C1 + P[1:-1, :-2] * C2 + P[2:, 1:-1] * C3 + P[:-2, 1:-1] * C4 + + Hphi = (phi > 0).astype(image.dtype) + (c1, c2) = _cv_calculate_averages(image, Hphi) + + difference_from_average_term = ( + -lambda1 * (image - c1) ** 2 + lambda2 * (image - c2) ** 2 + ) + new_phi = phi + (dt * _cv_delta(phi)) * (mu * K + difference_from_average_term) + return new_phi / (1 + mu * dt * _cv_delta(phi) * (C1 + C2 + C3 + C4)) + + +def _cv_heavyside(x, eps=1.0): + """Returns the result of a regularised heavyside function of the + input value(s). + """ + return 0.5 * (1.0 + (2.0 / np.pi) * np.arctan(x / eps)) + + +def _cv_delta(x, eps=1.0): + """Returns the result of a regularised dirac function of the + input value(s). + """ + return eps / (eps**2 + x**2) + + +def _cv_calculate_averages(image, Hphi): + """Returns the average values 'inside' and 'outside'.""" + H = Hphi + Hinv = 1.0 - H + Hsum = np.sum(H) + Hinvsum = np.sum(Hinv) + avg_inside = np.sum(image * H) + avg_oustide = np.sum(image * Hinv) + if Hsum != 0: + avg_inside /= Hsum + if Hinvsum != 0: + avg_oustide /= Hinvsum + return (avg_inside, avg_oustide) + + +def _cv_difference_from_average_term(image, Hphi, lambda_pos, lambda_neg): + """Returns the 'energy' contribution due to the difference from + the average value within a region at each point. + """ + (c1, c2) = _cv_calculate_averages(image, Hphi) + Hinv = 1.0 - Hphi + return lambda_pos * (image - c1) ** 2 * Hphi + lambda_neg * (image - c2) ** 2 * Hinv + + +def _cv_edge_length_term(phi, mu): + """Returns the 'energy' contribution due to the length of the + edge between regions at each point, multiplied by a factor 'mu'. + """ + P = np.pad(phi, 1, mode='edge') + fy = (P[2:, 1:-1] - P[:-2, 1:-1]) / 2.0 + fx = (P[1:-1, 2:] - P[1:-1, :-2]) / 2.0 + return mu * _cv_delta(phi) * np.sqrt(fx**2 + fy**2) + + +def _cv_energy(image, phi, mu, lambda1, lambda2): + """Returns the total 'energy' of the current level set function. + + This corresponds to equation (7) of the paper by Pascal Getreuer, + which is the weighted sum of the following: + (A) the length of the contour produced by the zero values of the + level set, + (B) the area of the "foreground" (area of the image where the + level set is positive), + (C) the variance of the image inside the foreground, + (D) the variance of the image outside of the foreground + + Each value is computed for each pixel, and then summed. The weight + of (B) is set to 0 in this implementation. + """ + H = _cv_heavyside(phi) + avgenergy = _cv_difference_from_average_term(image, H, lambda1, lambda2) + lenenergy = _cv_edge_length_term(phi, mu) + return np.sum(avgenergy) + np.sum(lenenergy) + + +def _cv_reset_level_set(phi): + """This is a placeholder function as resetting the level set is not + strictly necessary, and has not been done for this implementation. + """ + return phi + + +def _cv_checkerboard(image_size, square_size, dtype=np.float64): + """Generates a checkerboard level set function. + + According to Pascal Getreuer, such a level set function has fast + convergence. + """ + yv = np.arange(image_size[0], dtype=dtype).reshape(image_size[0], 1) + xv = np.arange(image_size[1], dtype=dtype) + sf = np.pi / square_size + xv *= sf + yv *= sf + return np.sin(yv) * np.sin(xv) + + +def _cv_large_disk(image_size): + """Generates a disk level set function. + + The disk covers the whole image along its smallest dimension. + """ + res = np.ones(image_size) + centerY = int((image_size[0] - 1) / 2) + centerX = int((image_size[1] - 1) / 2) + res[centerY, centerX] = 0.0 + radius = float(min(centerX, centerY)) + return (radius - distance(res)) / radius + + +def _cv_small_disk(image_size): + """Generates a disk level set function. + + The disk covers half of the image along its smallest dimension. + """ + res = np.ones(image_size) + centerY = int((image_size[0] - 1) / 2) + centerX = int((image_size[1] - 1) / 2) + res[centerY, centerX] = 0.0 + radius = float(min(centerX, centerY)) / 2.0 + return (radius - distance(res)) / (radius * 3) + + +def _cv_init_level_set(init_level_set, image_shape, dtype=np.float64): + """Generates an initial level set function conditional on input arguments.""" + if isinstance(init_level_set, str): + if init_level_set == 'checkerboard': + res = _cv_checkerboard(image_shape, 5, dtype) + elif init_level_set == 'disk': + res = _cv_large_disk(image_shape) + elif init_level_set == 'small disk': + res = _cv_small_disk(image_shape) + else: + raise ValueError("Incorrect name for starting level set preset.") + else: + res = init_level_set + return res.astype(dtype, copy=False) + + +def chan_vese( + image, + mu=0.25, + lambda1=1.0, + lambda2=1.0, + tol=1e-3, + max_num_iter=500, + dt=0.5, + init_level_set='checkerboard', + extended_output=False, +): + """Chan-Vese segmentation algorithm. + + Active contour model by evolving a level set. Can be used to + segment objects without clearly defined boundaries. + + Parameters + ---------- + image : (M, N) ndarray + Grayscale image to be segmented. + mu : float, optional + 'edge length' weight parameter. Higher `mu` values will + produce a 'round' edge, while values closer to zero will + detect smaller objects. + lambda1 : float, optional + 'difference from average' weight parameter for the output + region with value 'True'. If it is lower than `lambda2`, this + region will have a larger range of values than the other. + lambda2 : float, optional + 'difference from average' weight parameter for the output + region with value 'False'. If it is lower than `lambda1`, this + region will have a larger range of values than the other. + tol : float, positive, optional + Level set variation tolerance between iterations. If the + L2 norm difference between the level sets of successive + iterations normalized by the area of the image is below this + value, the algorithm will assume that the solution was + reached. + max_num_iter : uint, optional + Maximum number of iterations allowed before the algorithm + interrupts itself. + dt : float, optional + A multiplication factor applied at calculations for each step, + serves to accelerate the algorithm. While higher values may + speed up the algorithm, they may also lead to convergence + problems. + init_level_set : str or (M, N) ndarray, optional + Defines the starting level set used by the algorithm. + If a string is inputted, a level set that matches the image + size will automatically be generated. Alternatively, it is + possible to define a custom level set, which should be an + array of float values, with the same shape as 'image'. + Accepted string values are as follows. + + 'checkerboard' + the starting level set is defined as + sin(x/5*pi)*sin(y/5*pi), where x and y are pixel + coordinates. This level set has fast convergence, but may + fail to detect implicit edges. + 'disk' + the starting level set is defined as the opposite + of the distance from the center of the image minus half of + the minimum value between image width and image height. + This is somewhat slower, but is more likely to properly + detect implicit edges. + 'small disk' + the starting level set is defined as the + opposite of the distance from the center of the image + minus a quarter of the minimum value between image width + and image height. + extended_output : bool, optional + If set to True, the return value will be a tuple containing + the three return values (see below). If set to False which + is the default value, only the 'segmentation' array will be + returned. + + Returns + ------- + segmentation : (M, N) ndarray, bool + Segmentation produced by the algorithm. + phi : (M, N) ndarray of floats + Final level set computed by the algorithm. + energies : list of floats + Shows the evolution of the 'energy' for each step of the + algorithm. This should allow to check whether the algorithm + converged. + + Notes + ----- + The Chan-Vese Algorithm is designed to segment objects without + clearly defined boundaries. This algorithm is based on level sets + that are evolved iteratively to minimize an energy, which is + defined by weighted values corresponding to the sum of differences + intensity from the average value outside the segmented region, the + sum of differences from the average value inside the segmented + region, and a term which is dependent on the length of the + boundary of the segmented region. + + This algorithm was first proposed by Tony Chan and Luminita Vese, + in a publication entitled "An Active Contour Model Without Edges" + [1]_. + + This implementation of the algorithm is somewhat simplified in the + sense that the area factor 'nu' described in the original paper is + not implemented, and is only suitable for grayscale images. + + Typical values for `lambda1` and `lambda2` are 1. If the + 'background' is very different from the segmented object in terms + of distribution (for example, a uniform black image with figures + of varying intensity), then these values should be different from + each other. + + Typical values for mu are between 0 and 1, though higher values + can be used when dealing with shapes with very ill-defined + contours. + + The 'energy' which this algorithm tries to minimize is defined + as the sum of the differences from the average within the region + squared and weighed by the 'lambda' factors to which is added the + length of the contour multiplied by the 'mu' factor. + + Supports 2D grayscale images only, and does not implement the area + term described in the original article. + + References + ---------- + .. [1] An Active Contour Model without Edges, Tony Chan and + Luminita Vese, Scale-Space Theories in Computer Vision, + 1999, :DOI:`10.1007/3-540-48236-9_13` + .. [2] Chan-Vese Segmentation, Pascal Getreuer Image Processing On + Line, 2 (2012), pp. 214-224, + :DOI:`10.5201/ipol.2012.g-cv` + .. [3] The Chan-Vese Algorithm - Project Report, Rami Cohen, 2011 + :arXiv:`1107.2782` + """ + if len(image.shape) != 2: + raise ValueError("Input image should be a 2D array.") + + float_dtype = _supported_float_type(image.dtype) + phi = _cv_init_level_set(init_level_set, image.shape, dtype=float_dtype) + + if type(phi) != np.ndarray or phi.shape != image.shape: + raise ValueError( + "The dimensions of initial level set do not " + "match the dimensions of image." + ) + + image = image.astype(float_dtype, copy=False) + image = image - np.min(image) + if np.max(image) != 0: + image = image / np.max(image) + + i = 0 + old_energy = _cv_energy(image, phi, mu, lambda1, lambda2) + energies = [] + phivar = tol + 1 + segmentation = phi > 0 + + while phivar > tol and i < max_num_iter: + # Save old level set values + oldphi = phi + + # Calculate new level set + phi = _cv_calculate_variation(image, phi, mu, lambda1, lambda2, dt) + phi = _cv_reset_level_set(phi) + phivar = np.sqrt(((phi - oldphi) ** 2).mean()) + + # Extract energy and compare to previous level set and + # segmentation to see if continuing is necessary + segmentation = phi > 0 + new_energy = _cv_energy(image, phi, mu, lambda1, lambda2) + + # Save old energy values + energies.append(old_energy) + old_energy = new_energy + i += 1 + + if extended_output: + return (segmentation, phi, energies) + else: + return segmentation diff --git a/envs/kitoverlay/skimage/segmentation/_felzenszwalb.py b/envs/kitoverlay/skimage/segmentation/_felzenszwalb.py new file mode 100644 index 0000000000000000000000000000000000000000..74b482941ed00114871869d48e9ae90ee894c4e6 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_felzenszwalb.py @@ -0,0 +1,69 @@ +import numpy as np + +from ._felzenszwalb_cy import _felzenszwalb_cython +from .._shared import utils + + +@utils.channel_as_last_axis(multichannel_output=False) +def felzenszwalb(image, scale=1, sigma=0.8, min_size=20, *, channel_axis=-1): + """Computes Felsenszwalb's efficient graph based image segmentation. + + Produces an oversegmentation of a multichannel (i.e. RGB) image + using a fast, minimum spanning tree based clustering on the image grid. + The parameter ``scale`` sets an observation level. Higher scale means + less and larger segments. ``sigma`` is the diameter of a Gaussian kernel, + used for smoothing the image prior to segmentation. + + The number of produced segments as well as their size can only be + controlled indirectly through ``scale``. Segment size within an image can + vary greatly depending on local contrast. + + For RGB images, the algorithm uses the euclidean distance between pixels in + color space. + + Parameters + ---------- + image : (M, N[, 3]) ndarray + Input image. + scale : float + Free parameter. Higher means larger clusters. + sigma : float + Width (standard deviation) of Gaussian kernel used in preprocessing. + min_size : int + Minimum component size. Enforced using postprocessing. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + segment_mask : (M, N) ndarray + Integer mask indicating segment labels. + + References + ---------- + .. [1] Efficient graph-based image segmentation, Felzenszwalb, P.F. and + Huttenlocher, D.P. International Journal of Computer Vision, 2004 + + Notes + ----- + The `k` parameter used in the original paper renamed to `scale` here. + + Examples + -------- + >>> from skimage.segmentation import felzenszwalb + >>> from skimage.data import coffee + >>> img = coffee() + >>> segments = felzenszwalb(img, scale=3.0, sigma=0.95, min_size=5) + """ + if channel_axis is None and image.ndim > 2: + raise ValueError( + "This algorithm works only on single or " "multi-channel 2d images. " + ) + + image = np.atleast_3d(image) + return _felzenszwalb_cython(image, scale=scale, sigma=sigma, min_size=min_size) diff --git a/envs/kitoverlay/skimage/segmentation/_join.py b/envs/kitoverlay/skimage/segmentation/_join.py new file mode 100644 index 0000000000000000000000000000000000000000..b976f7b0364c471e07cb03bf73a70acfc1ce7092 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_join.py @@ -0,0 +1,184 @@ +import numpy as np + +from ..util._map_array import map_array, ArrayMap + + +def join_segmentations(s1, s2, return_mapping: bool = False): + """Return the join of the two input segmentations. + + The join J of S1 and S2 is defined as the segmentation in which two + voxels are in the same segment if and only if they are in the same + segment in *both* S1 and S2. + + Parameters + ---------- + s1, s2 : numpy arrays + s1 and s2 are label fields of the same shape. + return_mapping : bool, optional + If true, return mappings for joined segmentation labels to the original labels. + + Returns + ------- + j : numpy array + The join segmentation of s1 and s2. + map_j_to_s1 : ArrayMap, optional + Mapping from labels of the joined segmentation j to labels of s1. + map_j_to_s2 : ArrayMap, optional + Mapping from labels of the joined segmentation j to labels of s2. + + Examples + -------- + >>> from skimage.segmentation import join_segmentations + >>> s1 = np.array([[0, 0, 1, 1], + ... [0, 2, 1, 1], + ... [2, 2, 2, 1]]) + >>> s2 = np.array([[0, 1, 1, 0], + ... [0, 1, 1, 0], + ... [0, 1, 1, 1]]) + >>> join_segmentations(s1, s2) + array([[0, 1, 3, 2], + [0, 5, 3, 2], + [4, 5, 5, 3]]) + >>> j, m1, m2 = join_segmentations(s1, s2, return_mapping=True) + >>> m1 + ArrayMap(array([0, 1, 2, 3, 4, 5]), array([0, 0, 1, 1, 2, 2])) + >>> np.all(m1[j] == s1) + True + >>> np.all(m2[j] == s2) + True + """ + if s1.shape != s2.shape: + raise ValueError( + "Cannot join segmentations of different shape. " + f"s1.shape: {s1.shape}, s2.shape: {s2.shape}" + ) + # Reindex input label images + s1_relabeled, _, backward_map1 = relabel_sequential(s1) + s2_relabeled, _, backward_map2 = relabel_sequential(s2) + # Create joined label image + factor = s2.max() + np.uint8(1) + j_initial = factor * s1_relabeled + s2_relabeled + j, _, map_j_to_j_initial = relabel_sequential(j_initial) + if not return_mapping: + return j + # Determine label mapping + labels_j = np.unique(j_initial) + labels_s1_relabeled, labels_s2_relabeled = np.divmod(labels_j, factor) + map_j_to_s1 = ArrayMap( + map_j_to_j_initial.in_values, backward_map1[labels_s1_relabeled] + ) + map_j_to_s2 = ArrayMap( + map_j_to_j_initial.in_values, backward_map2[labels_s2_relabeled] + ) + return j, map_j_to_s1, map_j_to_s2 + + +def relabel_sequential(label_field, offset=1): + """Relabel arbitrary labels to {`offset`, ... `offset` + number_of_labels}. + + This function also returns the forward map (mapping the original labels to + the reduced labels) and the inverse map (mapping the reduced labels back + to the original ones). + + Parameters + ---------- + label_field : numpy array of int, arbitrary shape + An array of labels, which must be non-negative integers. + offset : int, optional + The return labels will start at `offset`, which should be + strictly positive. + + Returns + ------- + relabeled : numpy array of int, same shape as `label_field` + The input label field with labels mapped to + {offset, ..., number_of_labels + offset - 1}. + The data type will be the same as `label_field`, except when + offset + number_of_labels causes overflow of the current data type. + forward_map : ArrayMap + The map from the original label space to the returned label + space. Can be used to re-apply the same mapping. See examples + for usage. The output data type will be the same as `relabeled`. + inverse_map : ArrayMap + The map from the new label space to the original space. This + can be used to reconstruct the original label field from the + relabeled one. The output data type will be the same as `label_field`. + + Notes + ----- + The label 0 is assumed to denote the background and is never remapped. + + The forward map can be extremely big for some inputs, since its + length is given by the maximum of the label field. However, in most + situations, ``label_field.max()`` is much smaller than + ``label_field.size``, and in these cases the forward map is + guaranteed to be smaller than either the input or output images. + + Examples + -------- + >>> from skimage.segmentation import relabel_sequential + >>> label_field = np.array([1, 1, 5, 5, 8, 99, 42]) + >>> relab, fw, inv = relabel_sequential(label_field) + >>> relab + array([1, 1, 2, 2, 3, 5, 4]) + >>> print(fw) + ArrayMap: + 1 → 1 + 5 → 2 + 8 → 3 + 42 → 4 + 99 → 5 + >>> np.array(fw) + array([0, 1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]) + >>> np.array(inv) + array([ 0, 1, 5, 8, 42, 99]) + >>> (fw[label_field] == relab).all() + True + >>> (inv[relab] == label_field).all() + True + >>> relab, fw, inv = relabel_sequential(label_field, offset=5) + >>> relab + array([5, 5, 6, 6, 7, 9, 8]) + """ + if offset <= 0: + raise ValueError("Offset must be strictly positive.") + if np.min(label_field) < 0: + raise ValueError("Cannot relabel array that contains negative values.") + offset = int(offset) + in_vals = np.unique(label_field) + if in_vals[0] == 0: + # always map 0 to 0 + out_vals = np.concatenate([[0], np.arange(offset, offset + len(in_vals) - 1)]) + else: + out_vals = np.arange(offset, offset + len(in_vals)) + input_type = label_field.dtype + if input_type.kind not in "iu": + raise TypeError("label_field must have an integer dtype") + + # Some logic to determine the output type: + # - we don't want to return a smaller output type than the input type, + # ie if we get uint32 as labels input, don't return a uint8 array. + # - but, in some cases, using the input type could result in overflow. The + # input type could be a signed integer (e.g. int32) but + # `np.min_scalar_type` will always return an unsigned type. We check for + # that by casting the largest output value to the input type. If it is + # unchanged, we use the input type, else we use the unsigned minimum + # required type + required_type = np.min_scalar_type(out_vals[-1]) + if input_type.itemsize < required_type.itemsize: + output_type = required_type + else: + if out_vals[-1] < np.iinfo(input_type).max: + output_type = input_type + else: + output_type = required_type + out_array = np.empty(label_field.shape, dtype=output_type) + out_vals = out_vals.astype(output_type) + map_array(label_field, in_vals, out_vals, out=out_array) + fw_map = ArrayMap(in_vals, out_vals) + inv_map = ArrayMap(out_vals, in_vals) + return out_array, fw_map, inv_map diff --git a/envs/kitoverlay/skimage/segmentation/_quickshift.py b/envs/kitoverlay/skimage/segmentation/_quickshift.py new file mode 100644 index 0000000000000000000000000000000000000000..e627bdef36647df89299ebbc8a2a618f64d7d398 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_quickshift.py @@ -0,0 +1,104 @@ +import numpy as np + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type +from ..color import rgb2lab +from ..util import img_as_float +from ._quickshift_cy import _quickshift_cython + + +def quickshift( + image, + ratio=1.0, + kernel_size=5, + max_dist=10, + return_tree=False, + sigma=0, + convert2lab=True, + rng=42, + *, + channel_axis=-1, +): + """Segment image using quickshift clustering in Color-(x,y) space. + + Produces an oversegmentation of the image using the quickshift mode-seeking + algorithm. + + Parameters + ---------- + image : (M, N, C) ndarray + Input image. The axis corresponding to color channels can be specified + via the `channel_axis` argument. + ratio : float, optional, between 0 and 1 + Balances color-space proximity and image-space proximity. + Higher values give more weight to color-space. + kernel_size : float, optional + Width of Gaussian kernel used in smoothing the + sample density. Higher means fewer clusters. + max_dist : float, optional + Cut-off point for data distances. + Higher means fewer clusters. + return_tree : bool, optional + Whether to return the full segmentation hierarchy tree and distances. + sigma : float, optional + Width for Gaussian smoothing as preprocessing. Zero means no smoothing. + convert2lab : bool, optional + Whether the input should be converted to Lab colorspace prior to + segmentation. For this purpose, the input is assumed to be RGB. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG is used to break ties, and is seeded with 42 by default. + channel_axis : int, optional + The axis of `image` corresponding to color channels. Defaults to the + last axis. + + Returns + ------- + segment_mask : (M, N) ndarray + Integer mask indicating segment labels. + + Notes + ----- + The authors advocate to convert the image to Lab color space prior to + segmentation, though this is not strictly necessary. For this to work, the + image must be given in RGB format. + + References + ---------- + .. [1] Quick shift and kernel methods for mode seeking, + Vedaldi, A. and Soatto, S. + European Conference on Computer Vision, 2008 + """ + + image = img_as_float(np.atleast_3d(image)) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if image.ndim > 3: + raise ValueError("Only 2D color images are supported") + + # move channels to last position as expected by the Cython code + image = np.moveaxis(image, source=channel_axis, destination=-1) + + if convert2lab: + if image.shape[-1] != 3: + raise ValueError("Only RGB images can be converted to Lab space.") + image = rgb2lab(image) + + if kernel_size < 1: + raise ValueError("`kernel_size` should be >= 1.") + + image = gaussian(image, sigma=[sigma, sigma, 0], mode='reflect', channel_axis=-1) + image = np.ascontiguousarray(image * ratio) + + segment_mask = _quickshift_cython( + image, + kernel_size=kernel_size, + max_dist=max_dist, + return_tree=return_tree, + rng=rng, + ) + return segment_mask diff --git a/envs/kitoverlay/skimage/segmentation/_watershed.py b/envs/kitoverlay/skimage/segmentation/_watershed.py new file mode 100644 index 0000000000000000000000000000000000000000..d41306f3c2d019f4c0a7e1c2fd725d9cd1089c69 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_watershed.py @@ -0,0 +1,243 @@ +"""watershed.py - watershed algorithm + +This module implements a watershed algorithm that apportions pixels into +marked basins. The algorithm uses a priority queue to hold the pixels +with the metric for the priority queue being pixel value, then the time +of entry into the queue - this settles ties in favor of the closest marker. + +Some ideas taken from +Soille, "Automated Basin Delineation from Digital Elevation Models Using +Mathematical Morphology", Signal Processing 20 (1990) 171-182. + +The most important insight in the paper is that entry time onto the queue +solves two problems: a pixel should be assigned to the neighbor with the +largest gradient or, if there is no gradient, pixels on a plateau should +be split between markers on opposite sides. +""" + +import numpy as np +from scipy import ndimage as ndi + +from . import _watershed_cy +from ..morphology import flood, flood_fill # noqa: F401 +from ..morphology.extrema import local_minima +from ..morphology._util import _validate_connectivity, _offsets_to_raveled_neighbors +from ..util import crop, regular_seeds + + +def _validate_inputs(image, markers, mask, connectivity): + """Ensure that all inputs to watershed have matching shapes and types. + + Parameters + ---------- + image : array + The input image. + markers : int or array of int + The marker image. + mask : array, or None + A boolean mask, True where we want to compute the watershed. + connectivity : int in {1, ..., image.ndim} + The connectivity of the neighborhood of a pixel. + + Returns + ------- + image, markers, mask : arrays + The validated and formatted arrays. Image will have dtype float64, + markers int32, and mask int8. If ``None`` was given for the mask, + it is a volume of all 1s. + + Raises + ------ + ValueError + If the shapes of the given arrays don't match. + """ + n_pixels = image.size + if mask is None: + # Use a complete `True` mask if none is provided + mask = np.ones(image.shape, bool) + else: + mask = np.asanyarray(mask, dtype=bool) + n_pixels = np.sum(mask) + if mask.shape != image.shape: + message = ( + f'`mask` (shape {mask.shape}) must have same shape ' + f'as `image` (shape {image.shape})' + ) + raise ValueError(message) + if markers is None: + markers_bool = local_minima(image, connectivity=connectivity) * mask + footprint = ndi.generate_binary_structure(markers_bool.ndim, connectivity) + markers = ndi.label(markers_bool, structure=footprint)[0] + elif not isinstance(markers, (np.ndarray, list, tuple)): + # not array-like, assume int + # given int, assume that number of markers *within mask*. + markers = regular_seeds(image.shape, int(markers / (n_pixels / image.size))) + markers *= mask + else: + markers = np.asanyarray(markers) * mask + if markers.shape != image.shape: + message = ( + f'`markers` (shape {markers.shape}) must have same ' + f'shape as `image` (shape {image.shape})' + ) + raise ValueError(message) + return (image.astype(np.float64), markers, mask.astype(np.int8)) + + +def watershed( + image, + markers=None, + connectivity=1, + offset=None, + mask=None, + compactness=0, + watershed_line=False, +): + """Find watershed basins in an image flooded from given markers. + + Parameters + ---------- + image : (M, N[, ...]) ndarray + Data array where the lowest value points are labeled first. + markers : int, or (M, N[, ...]) ndarray of int, optional + The desired number of basins, or an array marking the basins with the + values to be assigned in the label matrix. Zero means not a marker. If + None, the (default) markers are determined as the local minima of + `image`. Specifically, the computation is equivalent to applying + :func:`skimage.morphology.local_minima` onto `image`, followed by + :func:`skimage.measure.label` onto the result (with the same given + `connectivity`). Generally speaking, users are encouraged to pass + markers explicitly. + connectivity : int or ndarray, optional + The neighborhood connectivity. An integer is interpreted as in + ``scipy.ndimage.generate_binary_structure``, as the maximum number + of orthogonal steps to reach a neighbor. An array is directly + interpreted as a footprint (structuring element). Default value is 1. + In 2D, 1 gives a 4-neighborhood while 2 gives an 8-neighborhood. + offset : array_like of shape image.ndim, optional + The coordinates of the center of the footprint. + mask : (M, N[, ...]) ndarray of bools or 0's and 1's, optional + Array of same shape as `image`. Only points at which mask == True + will be labeled. + compactness : float, optional + Use compact watershed [1]_ with given compactness parameter. + Higher values result in more regularly-shaped watershed basins. + watershed_line : bool, optional + If True, a one-pixel wide line separates the regions + obtained by the watershed algorithm. The line has the label 0. + Note that the method used for adding this line expects that + marker regions are not adjacent; the watershed line may not catch + borders between adjacent marker regions. + + Returns + ------- + out : ndarray + A labeled matrix of the same type and shape as `markers`. + + See Also + -------- + skimage.segmentation.random_walker + A segmentation algorithm based on anisotropic diffusion, usually + slower than the watershed but with good results on noisy data and + boundaries with holes. + + Notes + ----- + This function implements a watershed algorithm [2]_ [3]_ that apportions + pixels into marked basins. The algorithm uses a priority queue to hold + the pixels with the metric for the priority queue being pixel value, then + the time of entry into the queue -- this settles ties in favor of the + closest marker. + + Some ideas are taken from [4]_. + The most important insight in the paper is that entry time onto the queue + solves two problems: a pixel should be assigned to the neighbor with the + largest gradient or, if there is no gradient, pixels on a plateau should + be split between markers on opposite sides. + + This implementation converts all arguments to specific, lowest common + denominator types, then passes these to a C algorithm. + + Markers can be determined manually, or automatically using for example + the local minima of the gradient of the image, or the local maxima of the + distance function to the background for separating overlapping objects + (see example). + + References + ---------- + .. [1] P. Neubert and P. Protzel, "Compact Watershed and Preemptive SLIC: + On Improving Trade-offs of Superpixel Segmentation Algorithms," + 2014 22nd International Conference on Pattern Recognition, + Stockholm, Sweden, 2014, pp. 996-1001, :DOI:`10.1109/ICPR.2014.181` + https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf + + .. [2] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29 + + .. [3] https://web.archive.org/web/20180702213110/http://cmm.ensmp.fr/~beucher/wtshed.html + + .. [4] P. J. Soille and M. M. Ansoult, "Automated basin delineation from + digital elevation models using mathematical morphology," Signal + Processing, 20(2):171-182, :DOI:`10.1016/0165-1684(90)90127-K` + + Examples + -------- + The watershed algorithm is useful to separate overlapping objects. + + We first generate an initial image with two overlapping circles: + + >>> x, y = np.indices((80, 80)) + >>> x1, y1, x2, y2 = 28, 28, 44, 52 + >>> r1, r2 = 16, 20 + >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 + >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 + >>> image = np.logical_or(mask_circle1, mask_circle2) + + Next, we want to separate the two circles. We generate markers at the + maxima of the distance to the background: + + >>> from scipy import ndimage as ndi + >>> distance = ndi.distance_transform_edt(image) + >>> from skimage.feature import peak_local_max + >>> max_coords = peak_local_max(distance, labels=image, + ... footprint=np.ones((3, 3))) + >>> local_maxima = np.zeros_like(image, dtype=bool) + >>> local_maxima[tuple(max_coords.T)] = True + >>> markers = ndi.label(local_maxima)[0] + + Finally, we run the watershed on the image and markers: + + >>> labels = watershed(-distance, markers, mask=image) + + The algorithm works also for 3D images, and can be used for example to + separate overlapping spheres. + """ + image, markers, mask = _validate_inputs(image, markers, mask, connectivity) + connectivity, offset = _validate_connectivity(image.ndim, connectivity, offset) + + # pad the image, markers, and mask so that we can use the mask to + # keep from running off the edges + pad_width = [(p, p) for p in offset] + image = np.pad(image, pad_width, mode='constant') + mask = np.pad(mask, pad_width, mode='constant').ravel() + output = np.pad(markers, pad_width, mode='constant') + + flat_neighborhood = _offsets_to_raveled_neighbors( + image.shape, connectivity, center=offset + ) + marker_locations = np.flatnonzero(output) + image_strides = np.array(image.strides, dtype=np.intp) // image.itemsize + + _watershed_cy.watershed_raveled( + image.ravel(), + marker_locations, + flat_neighborhood, + mask, + image_strides, + compactness, + output.ravel(), + watershed_line, + ) + + output = crop(output, pad_width, copy=True) + + return output diff --git a/envs/kitoverlay/skimage/segmentation/random_walker_segmentation.py b/envs/kitoverlay/skimage/segmentation/random_walker_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..ca74f83270d32b02ac59e68ac56cc61043841da3 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/random_walker_segmentation.py @@ -0,0 +1,593 @@ +""" +Random walker segmentation algorithm + +from *Random walks for image segmentation*, Leo Grady, IEEE Trans +Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83. + +Installing pyamg and using the 'cg_mg' mode of random_walker improves +significantly the performance. +""" + +import numpy as np +from scipy import sparse, ndimage as ndi + +from .._shared import utils +from .._shared.utils import warn +from .._shared.compat import SCIPY_CG_TOL_PARAM_NAME + +# executive summary for next code block: try to import umfpack from +# scipy, but make sure not to raise a fuss if it fails since it's only +# needed to speed up a few cases. +# See discussions at: +# https://groups.google.com/d/msg/scikit-image/FrM5IGP6wh4/1hp-FtVZmfcJ +# https://stackoverflow.com/questions/13977970/ignore-exceptions-printed-to-stderr-in-del/13977992?noredirect=1#comment28386412_13977992 +try: + from scipy.sparse.linalg.dsolve.linsolve import umfpack + + old_del = umfpack.UmfpackContext.__del__ + + def new_del(self): + try: + old_del(self) + except AttributeError: + pass + + umfpack.UmfpackContext.__del__ = new_del + UmfpackContext = umfpack.UmfpackContext() +except ImportError: + UmfpackContext = None + +try: + from pyamg import ruge_stuben_solver + + amg_loaded = True +except ImportError: + amg_loaded = False + +from ..util import img_as_float + +from scipy.sparse.linalg import cg, spsolve + + +def _make_graph_edges_3d(n_x, n_y, n_z): + """Returns a list of edges for a 3D image. + + Parameters + ---------- + n_x : integer + The size of the grid in the x direction. + n_y : integer + The size of the grid in the y direction + n_z : integer + The size of the grid in the z direction + + Returns + ------- + edges : (2, N) ndarray + with the total number of edges:: + + N = n_x * n_y * (nz - 1) + + n_x * (n_y - 1) * nz + + (n_x - 1) * n_y * nz + + Graph edges with each column describing a node-id pair. + """ + vertices = np.arange(n_x * n_y * n_z).reshape((n_x, n_y, n_z)) + edges_deep = np.vstack((vertices[..., :-1].ravel(), vertices[..., 1:].ravel())) + edges_right = np.vstack((vertices[:, :-1].ravel(), vertices[:, 1:].ravel())) + edges_down = np.vstack((vertices[:-1].ravel(), vertices[1:].ravel())) + edges = np.hstack((edges_deep, edges_right, edges_down)) + return edges + + +def _compute_weights_3d(data, spacing, beta, eps, multichannel): + # Weight calculation is main difference in multispectral version + # Original gradient**2 replaced with sum of gradients ** 2 + gradients = ( + np.concatenate( + [ + np.diff(data[..., 0], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + for channel in range(1, data.shape[-1]): + gradients += ( + np.concatenate( + [ + np.diff(data[..., channel], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + + # All channels considered together in this standard deviation + scale_factor = -beta / (10 * data.std()) + if multichannel: + # New final term in beta to give == results in trivial case where + # multiple identical spectra are passed. + scale_factor /= np.sqrt(data.shape[-1]) + weights = np.exp(scale_factor * gradients) + weights += eps + return -weights + + +def _build_laplacian(data, spacing, mask, beta, multichannel): + l_x, l_y, l_z = data.shape[:3] + edges = _make_graph_edges_3d(l_x, l_y, l_z) + weights = _compute_weights_3d( + data, spacing, beta=beta, eps=1.0e-10, multichannel=multichannel + ) + if mask is not None: + # Remove edges of the graph connected to masked nodes, as well + # as corresponding weights of the edges. + mask0 = np.hstack( + [mask[..., :-1].ravel(), mask[:, :-1].ravel(), mask[:-1].ravel()] + ) + mask1 = np.hstack( + [mask[..., 1:].ravel(), mask[:, 1:].ravel(), mask[1:].ravel()] + ) + ind_mask = np.logical_and(mask0, mask1) + edges, weights = edges[:, ind_mask], weights[ind_mask] + + # Reassign edges labels to 0, 1, ... edges_number - 1 + _, inv_idx = np.unique(edges, return_inverse=True) + edges = inv_idx.reshape(edges.shape) + + # Build the sparse linear system + pixel_nb = l_x * l_y * l_z + i_indices = edges.ravel() + j_indices = edges[::-1].ravel() + data = np.hstack((weights, weights)) + lap = sparse.csr_array((data, (i_indices, j_indices)), shape=(pixel_nb, pixel_nb)) + lap.setdiag(-np.ravel(lap.sum(axis=0))) + return lap + + +def _build_linear_system(data, spacing, labels, nlabels, mask, beta, multichannel): + """ + Build the matrix A and rhs B of the linear system to solve. + A and B are two block of the laplacian of the image graph. + """ + if mask is None: + labels = labels.ravel() + else: + labels = labels[mask] + + indices = np.arange(labels.size) + seeds_mask = labels > 0 + unlabeled_indices = indices[~seeds_mask] + seeds_indices = indices[seeds_mask] + + lap_sparse = _build_laplacian( + data, spacing, mask=mask, beta=beta, multichannel=multichannel + ) + + rows = lap_sparse[unlabeled_indices, :] + lap_sparse = rows[:, unlabeled_indices] + B = -rows[:, seeds_indices] + + seeds = labels[seeds_mask] + seeds_mask = sparse.csc_array( + np.hstack([np.atleast_2d(seeds == lab).T for lab in range(1, nlabels + 1)]) + ) + rhs = B @ seeds_mask + + return lap_sparse, rhs + + +def _solve_linear_system(lap_sparse, B, tol, mode): + if mode is None: + mode = 'cg_j' + + if mode == 'cg_mg' and not amg_loaded: + warn( + '"cg_mg" not available, it requires pyamg to be installed. ' + 'The "cg_j" mode will be used instead.', + stacklevel=2, + ) + mode = 'cg_j' + + if mode == 'bf': + X = spsolve(lap_sparse, B.toarray()).T + else: + maxiter = None + if mode == 'cg': + if UmfpackContext is None: + warn( + '"cg" mode may be slow because UMFPACK is not available. ' + 'Consider building Scipy with UMFPACK or use a ' + 'preconditioned version of CG ("cg_j" or "cg_mg" modes).', + stacklevel=2, + ) + M = None + elif mode == 'cg_j': + n = lap_sparse.shape[-1] + M = sparse.dia_array((1.0 / lap_sparse.diagonal(), 0), shape=(n, n)) + else: + # mode == 'cg_mg' + lap_sparse.indices, lap_sparse.indptr = _safe_downcast_indices( + lap_sparse, np.int32, "index values too large for int32 mode 'cg_mg'" + ) + ml = ruge_stuben_solver(lap_sparse, coarse_solver='pinv') + M = ml.aspreconditioner(cycle='V') + maxiter = 30 + rtol = {SCIPY_CG_TOL_PARAM_NAME: tol} + cg_out = [ + cg(lap_sparse, B[:, [i]].toarray(), **rtol, atol=0, M=M, maxiter=maxiter) + for i in range(B.shape[1]) + ] + if np.any([info > 0 for _, info in cg_out]): + warn( + "Conjugate gradient convergence to tolerance not achieved. " + "Consider decreasing beta to improve system conditionning.", + stacklevel=2, + ) + X = np.asarray([x for x, _ in cg_out]) + + return X + + +def _safe_downcast_indices(A, itype, msg): + # check for safe downcasting + max_value = np.iinfo(itype).max + + if A.indptr[-1] > max_value: # indptr[-1] is max b/c indptr always sorted + raise ValueError(msg) + + if max(*A.shape) > max_value: # only check large enough arrays + if np.any(A.indices > max_value): + raise ValueError(msg) + + indices = A.indices.astype(itype, copy=False) + indptr = A.indptr.astype(itype, copy=False) + return indices, indptr + + +def _preprocess(labels): + label_values, inv_idx = np.unique(labels, return_inverse=True) + if max(label_values) <= 0: + raise ValueError( + 'No seeds provided in label image: please ensure ' + 'it contains at least one positive value' + ) + + if not (label_values == 0).any(): + warn( + 'Random walker only segments unlabeled areas, where ' + 'labels == 0. No zero valued areas in labels were ' + 'found. Returning provided labels.', + stacklevel=2, + ) + + return labels, None, None, None, None + + # If some labeled pixels are isolated inside pruned zones, prune them + # as well and keep the labels for the final output + + null_mask = labels == 0 + pos_mask = labels > 0 + mask = labels >= 0 + + fill = ndi.binary_propagation(null_mask, mask=mask) + isolated = np.logical_and(pos_mask, np.logical_not(fill)) + + pos_mask[isolated] = False + + # If the array has pruned zones, be sure that no isolated pixels + # exist between pruned zones (they could not be determined) + if label_values[0] < 0 or np.any(isolated): + isolated = np.logical_and( + np.logical_not(ndi.binary_propagation(pos_mask, mask=mask)), null_mask + ) + + labels[isolated] = -1 + if np.all(isolated[null_mask]): + warn( + 'All unlabeled pixels are isolated, they could not be ' + 'determined by the random walker algorithm.', + stacklevel=2, + ) + return labels, None, None, None, None + + mask[isolated] = False + mask = np.atleast_3d(mask) + else: + mask = None + + # Reorder label values to have consecutive integers (no gaps) + zero_idx = np.searchsorted(label_values, 0) + labels = np.atleast_3d(inv_idx.reshape(labels.shape) - zero_idx) + + nlabels = label_values[zero_idx + 1 :].shape[0] + + inds_isolated_seeds = np.nonzero(isolated) + isolated_values = labels[inds_isolated_seeds] + + return labels, nlabels, mask, inds_isolated_seeds, isolated_values + + +@utils.channel_as_last_axis(multichannel_output=False) +def random_walker( + data, + labels, + beta=130, + mode='cg_j', + tol=1.0e-3, + copy=True, + return_full_prob=False, + spacing=None, + *, + prob_tol=1e-3, + channel_axis=None, +): + """Random walker algorithm for segmentation from markers. + + Random walker algorithm is implemented for gray-level or multichannel + images. + + Parameters + ---------- + data : (M, N[, P][, C]) ndarray + Image to be segmented in phases. Gray-level `data` can be two- or + three-dimensional; multichannel data can be three- or four- + dimensional with `channel_axis` specifying the dimension containing + channels. Data spacing is assumed isotropic unless the `spacing` + keyword argument is used. + labels : (M, N[, P]) array of ints + Array of seed markers labeled with different positive integers + for different phases. Zero-labeled pixels are unlabeled pixels. + Negative labels correspond to inactive pixels that are not taken + into account (they are removed from the graph). If labels are not + consecutive integers, the labels array will be transformed so that + labels are consecutive. In the multichannel case, `labels` should have + the same shape as a single channel of `data`, i.e. without the final + dimension denoting channels. + beta : float, optional + Penalization coefficient for the random walker motion + (the greater `beta`, the more difficult the diffusion). + mode : string, available options {'cg', 'cg_j', 'cg_mg', 'bf'} + Mode for solving the linear system in the random walker algorithm. + + - 'bf' (brute force): an LU factorization of the Laplacian is + computed. This is fast for small images (<1024x1024), but very slow + and memory-intensive for large images (e.g., 3-D volumes). + - 'cg' (conjugate gradient): the linear system is solved iteratively + using the Conjugate Gradient method from scipy.sparse.linalg. This is + less memory-consuming than the brute force method for large images, + but it is quite slow. + - 'cg_j' (conjugate gradient with Jacobi preconditionner): the + Jacobi preconditionner is applied during the Conjugate + gradient method iterations. This may accelerate the + convergence of the 'cg' method. + - 'cg_mg' (conjugate gradient with multigrid preconditioner): a + preconditioner is computed using a multigrid solver, then the + solution is computed with the Conjugate Gradient method. This mode + requires that the pyamg module is installed. + tol : float, optional + Tolerance to achieve when solving the linear system using + the conjugate gradient based modes ('cg', 'cg_j' and 'cg_mg'). + copy : bool, optional + If copy is False, the `labels` array will be overwritten with + the result of the segmentation. Use copy=False if you want to + save on memory. + return_full_prob : bool, optional + If True, the probability that a pixel belongs to each of the + labels will be returned, instead of only the most likely + label. + spacing : iterable of floats, optional + Spacing between voxels in each spatial dimension. If `None`, then + the spacing between pixels/voxels in each dimension is assumed 1. + prob_tol : float, optional + Tolerance on the resulting probability to be in the interval [0, 1]. + If the tolerance is not satisfied, a warning is displayed. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + output : ndarray + * If `return_full_prob` is False, array of ints of same shape + and data type as `labels`, in which each pixel has been + labeled according to the marker that reached the pixel first + by anisotropic diffusion. + * If `return_full_prob` is True, array of floats of shape + `(nlabels, labels.shape)`. `output[label_nb, i, j]` is the + probability that label `label_nb` reaches the pixel `(i, j)` + first. + + See Also + -------- + skimage.segmentation.watershed + A segmentation algorithm based on mathematical morphology + and "flooding" of regions from markers. + + Notes + ----- + Multichannel inputs are scaled with all channel data combined. Ensure all + channels are separately normalized prior to running this algorithm. + + The `spacing` argument is specifically for anisotropic datasets, where + data points are spaced differently in one or more spatial dimensions. + Anisotropic data is commonly encountered in medical imaging. + + The algorithm was first proposed in [1]_. + + The algorithm solves the diffusion equation at infinite times for + sources placed on markers of each phase in turn. A pixel is labeled with + the phase that has the greatest probability to diffuse first to the pixel. + + The diffusion equation is solved by minimizing x.T L x for each phase, + where L is the Laplacian of the weighted graph of the image, and x is + the probability that a marker of the given phase arrives first at a pixel + by diffusion (x=1 on markers of the phase, x=0 on the other markers, and + the other coefficients are looked for). Each pixel is attributed the label + for which it has a maximal value of x. The Laplacian L of the image + is defined as: + + - L_ii = d_i, the number of neighbors of pixel i (the degree of i) + - L_ij = -w_ij if i and j are adjacent pixels + + The weight w_ij is a decreasing function of the norm of the local gradient. + This ensures that diffusion is easier between pixels of similar values. + + When the Laplacian is decomposed into blocks of marked and unmarked + pixels:: + + L = M B.T + B A + + with first indices corresponding to marked pixels, and then to unmarked + pixels, minimizing x.T L x for one phase amount to solving:: + + A x = - B x_m + + where x_m = 1 on markers of the given phase, and 0 on other markers. + This linear system is solved in the algorithm using a direct method for + small images, and an iterative method for larger images. + + References + ---------- + .. [1] Leo Grady, Random walks for image segmentation, IEEE Trans Pattern + Anal Mach Intell. 2006 Nov;28(11):1768-83. + :DOI:`10.1109/TPAMI.2006.233`. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> a = np.zeros((10, 10)) + 0.2 * rng.random((10, 10)) + >>> a[5:8, 5:8] += 1 + >>> b = np.zeros_like(a, dtype=np.int32) + >>> b[3, 3] = 1 # Marker for first phase + >>> b[6, 6] = 2 # Marker for second phase + >>> random_walker(a, b) # doctest: +SKIP + array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32) + + """ + # Parse input data + if mode not in ('cg_mg', 'cg', 'bf', 'cg_j', None): + raise ValueError( + f"{mode} is not a valid mode. Valid modes are 'cg_mg', " + f"'cg', 'cg_j', 'bf', and None" + ) + + if data.dtype == np.float16: + # SciPy sparse, which is used later on, doesn't officially support float16 + # This led to failures when testing with NumPy 1.26 (see gh-7635). + data = data.astype(np.float32, casting="safe") + + # Spacing kwarg checks + if spacing is None: + spacing = np.ones(3) + elif len(spacing) == labels.ndim: + if len(spacing) == 2: + # Need a dummy spacing for singleton 3rd dim + spacing = np.r_[spacing, 1.0] + spacing = np.asarray(spacing) + else: + raise ValueError( + 'Input argument `spacing` incorrect, should be an ' + 'iterable with one number per spatial dimension.' + ) + + # This algorithm expects 4-D arrays of floats, where the first three + # dimensions are spatial and the final denotes channels. 2-D images have + # a singleton placeholder dimension added for the third spatial dimension, + # and single channel images likewise have a singleton added for channels. + # The following block ensures valid input and coerces it to the correct + # form. + multichannel = channel_axis is not None + if not multichannel: + if data.ndim not in (2, 3): + raise ValueError( + 'For non-multichannel input, data must be of ' 'dimension 2 or 3.' + ) + if data.shape != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = np.atleast_3d(img_as_float(data))[..., np.newaxis] + else: + if data.ndim not in (3, 4): + raise ValueError( + 'For multichannel input, data must have 3 or 4 ' 'dimensions.' + ) + if data.shape[:-1] != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = img_as_float(data) + if data.ndim == 3: # 2D multispectral, needs singleton in 3rd axis + data = data[:, :, np.newaxis, :] + + labels_shape = labels.shape + labels_dtype = labels.dtype + + if copy: + labels = np.copy(labels) + + (labels, nlabels, mask, inds_isolated_seeds, isolated_values) = _preprocess(labels) + + if isolated_values is None: + # No non isolated zero valued areas in labels were + # found. Returning provided labels. + if return_full_prob: + # Return the concatenation of the masks of each unique label + return np.concatenate( + [np.atleast_3d(labels == lab) for lab in np.unique(labels) if lab > 0], + axis=-1, + ) + return labels + + # Build the linear system (lap_sparse, B) + lap_sparse, B = _build_linear_system( + data, spacing, labels, nlabels, mask, beta, multichannel + ) + + # Solve the linear system lap_sparse X = B + # where X[i, j] is the probability that a marker of label i arrives + # first at pixel j by anisotropic diffusion. + X = _solve_linear_system(lap_sparse, B, tol, mode) + + if X.min() < -prob_tol or X.max() > 1 + prob_tol: + warn( + 'The probability range is outside [0, 1] given the tolerance ' + '`prob_tol`. Consider decreasing `beta` and/or decreasing ' + '`tol`.' + ) + + # Build the output according to return_full_prob value + # Put back labels of isolated seeds + labels[inds_isolated_seeds] = isolated_values + labels = labels.reshape(labels_shape) + + mask = labels == 0 + mask[inds_isolated_seeds] = False + + if return_full_prob: + out = np.zeros((nlabels,) + labels_shape) + for lab, (label_prob, prob) in enumerate(zip(out, X), start=1): + label_prob[mask] = prob + label_prob[labels == lab] = 1 + else: + X = np.argmax(X, axis=0) + 1 + out = labels.astype(labels_dtype) + out[mask] = X + + return out diff --git a/envs/kitoverlay/skimage/transform/__init__.py b/envs/kitoverlay/skimage/transform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a928f82c267c5deaf7097f0606c56dd4bd4786f --- /dev/null +++ b/envs/kitoverlay/skimage/transform/__init__.py @@ -0,0 +1,37 @@ +"""Geometric and other transformations, e.g., rotations, Radon transform. + +- Geometric transformation: + These transforms change the shape or position of an image. + They are useful for tasks such as image registration, + alignment, and geometric correction. + Examples: :class:`~skimage.transform.AffineTransform`, + :class:`~skimage.transform.ProjectiveTransform`, + :class:`~skimage.transform.EuclideanTransform`. + +- Image resizing and rescaling: + These transforms change the size or resolution of an image. + They are useful for tasks such as down-sampling an image to + reduce its size or up-sampling an image to increase its resolution. + Examples: :func:`~skimage.transform.resize`, + :func:`~skimage.transform.rescale`. + +- Feature detection and extraction: + These transforms identify and extract specific features or + patterns in an image. They are useful for tasks such as object + detection, image segmentation, and feature matching. + Examples: :func:`~skimage.transform.hough_circle`, + :func:`~skimage.transform.pyramid_expand`, + :func:`~skimage.transform.radon`. + +- Image transformation: + These transforms change the appearance of an image without changing its + content. They are useful for tasks such a creating image mosaics, + applying artistic effects, and visualizing image data. + Examples: :func:`~skimage.transform.warp`, + :func:`~skimage.transform.iradon`. + +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/transform/__init__.pyi b/envs/kitoverlay/skimage/transform/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7e6f44eb0c392cffc74bb7049adf630259ebd7c3 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/__init__.pyi @@ -0,0 +1,86 @@ +# Explicitly setting `__all__` is necessary for type inference engines +# to know which symbols are exported. See +# https://peps.python.org/pep-0484/#stub-files + +__all__ = [ + 'hough_circle', + 'hough_ellipse', + 'hough_line', + 'probabilistic_hough_line', + 'hough_circle_peaks', + 'hough_line_peaks', + 'radon', + 'iradon', + 'iradon_sart', + 'order_angles_golden_ratio', + 'frt2', + 'ifrt2', + 'integral_image', + 'integrate', + 'warp', + 'warp_coords', + 'warp_polar', + 'estimate_transform', + 'matrix_transform', + 'EuclideanTransform', + 'SimilarityTransform', + 'AffineTransform', + 'ProjectiveTransform', + 'EssentialMatrixTransform', + 'FundamentalMatrixTransform', + 'PolynomialTransform', + 'PiecewiseAffineTransform', + 'ThinPlateSplineTransform', + 'swirl', + 'resize', + 'resize_local_mean', + 'rotate', + 'rescale', + 'downscale_local_mean', + 'pyramid_reduce', + 'pyramid_expand', + 'pyramid_gaussian', + 'pyramid_laplacian', +] + +from .hough_transform import ( + hough_line, + hough_line_peaks, + probabilistic_hough_line, + hough_circle, + hough_circle_peaks, + hough_ellipse, +) +from .radon_transform import radon, iradon, iradon_sart, order_angles_golden_ratio +from .finite_radon_transform import frt2, ifrt2 +from .integral import integral_image, integrate +from ._geometric import ( + estimate_transform, + matrix_transform, + EuclideanTransform, + SimilarityTransform, + AffineTransform, + ProjectiveTransform, + FundamentalMatrixTransform, + EssentialMatrixTransform, + PolynomialTransform, + PiecewiseAffineTransform, +) +from ._thin_plate_splines import ThinPlateSplineTransform +from ._warps import ( + swirl, + resize, + rotate, + rescale, + downscale_local_mean, + warp, + warp_coords, + warp_polar, + resize_local_mean, +) +from .pyramids import ( + pyramid_reduce, + pyramid_expand, + pyramid_gaussian, + pyramid_laplacian, +) diff --git a/envs/kitoverlay/skimage/transform/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc272f28e6f90fd14eaaa442a2aeb3b6eb417acb Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/_warps.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/_warps.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc3ae82a1d4590a6b3798109acde4ad34b0cf110 Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/_warps.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/finite_radon_transform.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/finite_radon_transform.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a0b343b5ca0e0adf50ba747c308b331b2db8c5a Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/finite_radon_transform.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/hough_transform.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/hough_transform.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7711b3f6adea30dc25a2081b733bb8ab9d45bdf1 Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/hough_transform.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/integral.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/integral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ebc95d872c0a204ea19b15371f07ca42e6760aa Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/integral.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/pyramids.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/pyramids.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87ae694b6a4e00e512b14333a5e1bf6371be19c7 Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/pyramids.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/__pycache__/radon_transform.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/radon_transform.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afe0e01a378f3908a53f888ad9c9e52ab7f9d8d8 Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/radon_transform.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/transform/_geometric.py b/envs/kitoverlay/skimage/transform/_geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..f9bc2c1fd766a5cd81eae99a8d2f715677c08b6a --- /dev/null +++ b/envs/kitoverlay/skimage/transform/_geometric.py @@ -0,0 +1,2692 @@ +from copy import copy +import math +import textwrap +from abc import ABC, abstractmethod +from typing import Self +import warnings + +import numpy as np +from scipy import spatial + +from .._shared.utils import ( + safe_as_int, + _deprecate_estimate, + _update_from_estimate_docstring, + _deprecate_inherited_estimate, + FailedEstimation, +) +from .._shared.compat import NP_COPY_IF_NEEDED + + +def _affine_matrix_from_vector(v): + """Affine matrix from linearized (d, d + 1) matrix entries.""" + nparam = v.size + # solve for d in: d * (d + 1) = nparam + d = (1 + np.sqrt(1 + 4 * nparam)) / 2 - 1 + dimensionality = int(np.round(d)) # round to prevent approx errors + if d != dimensionality: + raise ValueError( + 'Invalid number of elements for ' f'linearized matrix: {nparam}' + ) + matrix = np.eye(dimensionality + 1) + matrix[:-1, :] = np.reshape(v, (dimensionality, dimensionality + 1)) + return matrix + + +def _calc_center_normalize(points, scaling='rms'): + """Calculate transformation `matrix` to center and normalize image points. + + Points are an array of shape (N, D). + + For `scaling` of 'raw', transformation returned `matrix` will be ``np.eye(D + + 1)``. For other values of `scaling`, `matrix` expresses a two-step + translation and scaling procedure. Points transformed with this `matrix` + usually give better conditioning for fundamental matrix estimation than the + original `points` [1]_. + + The two steps of transformation, for `scaling` other than 'raw', are: + + * Center the image points, such that the new coordinate system has its + origin at the centroid of the image points. + * Normalize the image points, such that the mean coordinate value of the + centered points is 1 (`scaling` == 'rms') or such that the + mean distance from the points to the origin of the coordinate system is + ``sqrt(D)`` (`scaling` == 'mrs'). + + If `scaling` != 'raw' and the points are all identical, the returned + `matrix` will be all ``np.nan``. + + The 'mrs' scaling corresponds to the isotropic transformation + algorithm in [1]_. 'rms' is the default, and gives very similar + conditioning. + + Parameters + ---------- + points : (N, D) array + The coordinates of the image points. + scaling : {'rms', 'mrs', 'raw'}, optional + Scaling algorithm adjusting for magnitude of `points` after applying + calculated translation. See above for explanation. + + Returns + ------- + matrix : (D+1, D+1) array_like + The transformation matrix to obtain the new points. + + References + ---------- + .. [1] Hartley, Richard I. "In defense of the eight-point algorithm." + Pattern Analysis and Machine Intelligence, IEEE Transactions on 19.6 + (1997): 580-593. + + """ + n, d = points.shape + scaling = scaling.lower() + matrix = np.eye(d + 1) + if scaling == 'raw': + return matrix + centroid = np.mean(points, axis=0) + centered = points - centroid + if scaling == 'rms': + divisor = np.sqrt(np.mean(centered**2)) + elif scaling == 'mrs': + divisor = np.mean(np.sqrt(np.sum(centered**2, axis=1))) / np.sqrt(d) + else: + raise ValueError(f'Unexpected "scaling" of "{scaling}"') + + # if all the points are the same, the transformation matrix cannot be + # created. We return an equivalent matrix with np.nans as sentinel values. + # This obviates the need for try/except blocks in functions calling this + # one, and those are only needed when actual 0 is reached, rather than some + # small value; ie, we don't need to worry about numerical stability here, + # only actual 0. + if divisor == 0: + return matrix + np.nan + + matrix[:d, d] = -centroid + matrix[:d, :] /= divisor + return matrix + + +def _center_and_normalize_points(points, scaling='rms'): + """Convenience function to calculate and apply scaling + + See: :func:`_calc_center_normalize` for details of the algorithm. + """ + matrix = _calc_center_normalize(points, scaling) + if not np.all(np.isfinite(matrix)): + return matrix + np.nan, np.full_like(points, np.nan) + return matrix, _apply_homogeneous(matrix, points) + + +def _apply_homogeneous(matrix, points): + """Transform (N, D) `points` array with homogeneous (D+1, D+1) `matrix`. + + Parameters + ---------- + matrix : (D+1, D+1) array_like + The transformation matrix to obtain the new points. Note that any + object with an `__array__` method [1]_ that returns a matrix with the + correct dimensions can be used as input here. This includes all + subclasses of :class:`ProjectiveTransform`, for example. + points : (N, D) array + The coordinates of the image points. + + Returns + ------- + new_points : (N, D) array + The transformed image points. + + References + ---------- + .. [1]: + https://numpy.org/doc/stable/user/basics.interoperability.html#using-arbitrary-objects-in-numpy + """ + points = np.array(points, copy=NP_COPY_IF_NEEDED, ndmin=2) + points_h = _append_homogeneous_dim(points) + new_points_h = points_h @ matrix.T + # We divide by the last dimension of the homogeneous + # coordinate matrix. In order to avoid division by zero, + # we replace exact zeros in this column with a very small number. + divs = new_points_h[:, -1] + divs = np.where(divs == 0, np.finfo(float).eps, divs) + return new_points_h[:, :-1] / divs[:, None] + + +def _append_homogeneous_dim(points): + """Append a column of ones to the right of `points`. + + This creates the representation of the points in the homogeneous coordinate + space used by homogeneous matrix transforms. + + Parameters + ---------- + points : array, shape (N, D) + The input coordinates, where N is the number of points and D is the + dimension of the coordinate space. + + Returns + ------- + points_h : array, shape (N, D+1) + The same points as homogeneous coordinates. + """ + return np.hstack((points, np.ones((len(points), 1)))) + + +def _umeyama(src, dst, estimate_scale): + """Estimate N-D similarity transformation with or without scaling. + + Parameters + ---------- + src : (M, N) array_like + Source coordinates. + dst : (M, N) array_like + Destination coordinates. + estimate_scale : bool + Whether to estimate scaling factor. + + Returns + ------- + T : (N + 1, N + 1) + The homogeneous similarity transformation matrix. The matrix contains + NaN values only if the problem is not well-conditioned. + + References + ---------- + .. [1] "Least-squares estimation of transformation parameters between two + point patterns", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573` + + """ + src = np.asarray(src) + dst = np.asarray(dst) + + num = src.shape[0] + dim = src.shape[1] + + # Compute mean of src and dst. + src_mean = src.mean(axis=0) + dst_mean = dst.mean(axis=0) + + # Subtract mean from src and dst. + src_demean = src - src_mean + dst_demean = dst - dst_mean + + # Eq. (38). + A = dst_demean.T @ src_demean / num + + # Eq. (39). + d = np.ones((dim,), dtype=np.float64) + if np.linalg.det(A) < 0: + d[dim - 1] = -1 + + T = np.eye(dim + 1, dtype=np.float64) + + U, S, V = np.linalg.svd(A) + + # Eq. (40) and (43). + # Matrix rank calculation from SVD (see numpy.linalg._linalg::matrix_rank code). + # (this does SVD to check for small singular values, replicated here). + tol = S.max() * np.max(A.shape) * np.finfo(float).eps + rank = np.count_nonzero(S > tol) + if rank == 0: + return np.nan * T + elif rank == dim - 1: + if np.linalg.det(U) * np.linalg.det(V) > 0: + T[:dim, :dim] = U @ V + else: + s = d[dim - 1] + d[dim - 1] = -1 + T[:dim, :dim] = U @ np.diag(d) @ V + d[dim - 1] = s + else: + T[:dim, :dim] = U @ np.diag(d) @ V + + if estimate_scale: + # Eq. (41) and (42). + scale = 1.0 / src_demean.var(axis=0).sum() * (S @ d) + else: + scale = 1.0 + + T[:dim, dim] = dst_mean - scale * (T[:dim, :dim] @ src_mean.T) + T[:dim, :dim] *= scale + + return T + + +class _GeometricTransform(ABC): + """Abstract base class for geometric transformations.""" + + @abstractmethod + def __call__(self, coords): + """Apply forward transformation. + + Parameters + ---------- + coords : (N, 2) array_like + Source coordinates. + + Returns + ------- + coords : (N, 2) array + Destination coordinates. + + """ + + @property + @abstractmethod + def inverse(self): + """Return a transform object representing the inverse.""" + + def residuals(self, src, dst): + """Determine residuals of transformed destination coordinates. + + For each transformed source coordinate the Euclidean distance to the + respective destination coordinate is determined. + + Parameters + ---------- + src : (N, 2) array + Source coordinates. + dst : (N, 2) array + Destination coordinates. + + Returns + ------- + residuals : (N,) array + Residual for coordinate. + + """ + return np.sqrt(np.sum((self(src) - dst) ** 2, axis=1)) + + @classmethod + @abstractmethod + def identity(cls, dimensionality=None): + """Identity transform + + Parameters + ---------- + dimensionality : {None, 2}, optional + This transform only allows dimensionality of 2, where None + corresponds to 2. The parameter exists for compatibility with other + transforms. + + Returns + ------- + tform : transform + Transform such that ``np.all(tform(pts) == pts)``. + """ + + @classmethod + def _prepare_estimation(cls, src, dst): + """Create identity transform and make sure points are arrays.""" + src = np.asarray(src) + dst = np.asarray(dst) + return cls.identity(src.shape[1]), src, dst + + @classmethod + def from_estimate(cls, src, dst, *args, **kwargs) -> Self | FailedEstimation: + r"""Estimate transform. + + Parameters + ---------- + src : (N, M) array_like + Source coordinates. + dst : (N, M) array_like + Destination coordinates. + \*args : sequence + Any other positional arguments. + \*\*kwargs : dict + Any other keyword arguments. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = TransformClass.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + """ + return _from_estimate(cls, src, dst, *args, **kwargs) + + +def _from_estimate(cls, src, dst, *args, **kwargs): + """Detached function for from_estimate base implementation.""" + tf, src, dst = cls._prepare_estimation(src, dst) + msg = tf._estimate(src, dst, *args, **kwargs) + return tf if msg is None else FailedEstimation(f'{cls.__name__}: {msg}') + + +class _HMatrixTransform(_GeometricTransform): + """Transform accepting homogeneous matrix as input.""" + + def __init__(self, matrix=None, *, dimensionality=None): + if matrix is None: + d = 2 if dimensionality is None else dimensionality + matrix = np.eye(d + 1) + else: + matrix = np.asarray(matrix) + self._check_matrix(matrix, dimensionality) + self._check_dims(matrix.shape[0] - 1) + self.params = matrix + + def _check_matrix(self, matrix, dimensionality): + if dimensionality is not None: + if dimensionality != matrix.shape[0] - 1: + raise ValueError( + f'Dimensionality {dimensionality} does not match matrix ' + f'{matrix}' + ) + m = matrix.shape[0] + if matrix.shape != (m, m): + raise ValueError("Invalid shape of transformation matrix") + + def _check_dims(self, d): + if d == 2: + return + raise NotImplementedError( + f'Input for {type(self)} should result in 2D transform' + ) + + @classmethod + def identity(cls, dimensionality=None): + """Identity transform + + Parameters + ---------- + dimensionality : {None, 2}, optional + This transform only allows dimensionality of 2, where None + corresponds to 2. The parameter exists for compatibility with other + transforms. + + Returns + ------- + tform : transform + Transform such that ``np.all(tform(pts) == pts)``. + """ + d = 2 if dimensionality is None else dimensionality + return cls(matrix=np.eye(d + 1)) + + @property + def dimensionality(self): + return self.matrix.shape[0] - 1 + + +class FundamentalMatrixTransform(_HMatrixTransform): + """Fundamental matrix transformation. + + The fundamental matrix relates corresponding points between a pair of + uncalibrated images. The matrix transforms homogeneous image points in one + image to epipolar lines in the other image. + + The fundamental matrix is only defined for a pair of moving images. In the + case of pure rotation or planar scenes, the homography describes the + geometric relation between two images (`ProjectiveTransform`). If the + intrinsic calibration of the images is known, the essential matrix describes + the metric relation between the two images (`EssentialMatrixTransform`). + + Notes + ----- + See [1]_ and [2]_ for details of the estimation procedure. [2]_ is a good + place to start. + + References + ---------- + .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in + computer vision. Cambridge university press, 2003. + .. [2] Zhang, Zhengyou. "Determining the epipolar geometry and its + uncertainty: A review." International journal of computer vision 27 + (1998): 161-195. + :DOI:`10.1023/A:1007941100561` + https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/RR-2927.pdf + + Parameters + ---------- + matrix : (3, 3) array_like, optional + Fundamental matrix. + dimensionality : int, optional + Fallback number of dimensions when `matrix` not specified, in which + case, must equal 2 (the default). + + Attributes + ---------- + params : (3, 3) array + Fundamental matrix. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define source and destination points: + + >>> src = np.array([1.839035, 1.924743, + ... 0.543582, 0.375221, + ... 0.473240, 0.142522, + ... 0.964910, 0.598376, + ... 0.102388, 0.140092, + ... 15.994343, 9.622164, + ... 0.285901, 0.430055, + ... 0.091150, 0.254594]).reshape(-1, 2) + >>> dst = np.array([1.002114, 1.129644, + ... 1.521742, 1.846002, + ... 1.084332, 0.275134, + ... 0.293328, 0.588992, + ... 0.839509, 0.087290, + ... 1.779735, 1.116857, + ... 0.878616, 0.602447, + ... 0.642616, 1.028681]).reshape(-1, 2) + + Estimate the transformation matrix: + + >>> tform = ski.transform.FundamentalMatrixTransform.from_estimate( + ... src, dst) + >>> tform.params + array([[-0.21785884, 0.41928191, -0.03430748], + [-0.07179414, 0.04516432, 0.02160726], + [ 0.24806211, -0.42947814, 0.02210191]]) + + Compute the Sampson distance: + + >>> tform.residuals(src, dst) + array([0.0053886 , 0.00526101, 0.08689701, 0.01850534, 0.09418259, + 0.00185967, 0.06160489, 0.02655136]) + + Apply inverse transformation: + + >>> tform.inverse(dst) + array([[-0.0513591 , 0.04170974, 0.01213043], + [-0.21599496, 0.29193419, 0.00978184], + [-0.0079222 , 0.03758889, -0.00915389], + [ 0.14187184, -0.27988959, 0.02476507], + [ 0.05890075, -0.07354481, -0.00481342], + [-0.21985267, 0.36717464, -0.01482408], + [ 0.01339569, -0.03388123, 0.00497605], + [ 0.03420927, -0.1135812 , 0.02228236]]) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((8, 2)) + >>> bad_tform = ski.transform.FundamentalMatrixTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + + """ + + scaling = 'rms' + + def __call__(self, coords): + """Apply forward transformation. + + Parameters + ---------- + coords : (N, 2) array_like + Source coordinates. + + Returns + ------- + coords : (N, 3) array + Epipolar lines in the destination image. + + """ + return _append_homogeneous_dim(coords) @ self.params.T + + @property + def inverse(self): + """Return a transform object representing the inverse. + + See Hartley & Zisserman, Ch. 8: Epipolar Geometry and the Fundamental + Matrix, for an explanation of why F.T gives the inverse. + + """ + return type(self)(matrix=self.params.T) + + def _setup_constraint_matrix(self, src, dst): + """Setup and solve the homogeneous epipolar constraint matrix:: + + dst' * F * src = 0. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + F_normalized : (3, 3) array + The normalized solution to the homogeneous system. If the system + is not well-conditioned, this matrix contains NaNs. + src_matrix : (3, 3) array + The transformation matrix to obtain the normalized source + coordinates. + dst_matrix : (3, 3) array + The transformation matrix to obtain the normalized destination + coordinates. + + """ + src = np.asarray(src) + dst = np.asarray(dst) + if src.shape != dst.shape: + raise ValueError('src and dst shapes must be identical.') + if src.shape[0] < 8: + raise ValueError('src.shape[0] must be equal or larger than 8.') + + # Center and normalize image points for better numerical stability. + src_matrix = _calc_center_normalize(src, self.scaling) + dst_matrix = _calc_center_normalize(dst, self.scaling) + if np.any(np.isnan(src_matrix + dst_matrix)): + self.params = np.full((3, 3), np.nan) + return 3 * [np.full((3, 3), np.nan)] + src_h = _append_homogeneous_dim(_apply_homogeneous(src_matrix, src)) + dst_h = _append_homogeneous_dim(_apply_homogeneous(dst_matrix, dst)) + + # Setup homogeneous linear equation as dst' * F * src = 0. + # Hartley notation u -> src[:, 0], v -> src[:, 1], + # u' -> dst[:, 0], v' -> dst[:, 1]. Required output cols are: + # uu', vu', u', uv', vv', v', u, v, 1 + cols = [(d_v * s_v) for d_v in dst_h.T for s_v in src_h.T] + A = np.stack(cols, axis=1) + + # Solve for the nullspace of the constraint matrix. + _, _, V = np.linalg.svd(A) + F_normalized = V[-1, :].reshape(3, 3) + + return F_normalized, src_matrix, dst_matrix + + @classmethod + def from_estimate(cls, src, dst): + """Estimate fundamental matrix using 8-point algorithm. + + The 8-point algorithm requires at least 8 corresponding point pairs. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = FundamentalMatrixTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + Raises + ------ + ValueError + If `src` has fewer than 8 rows. + """ + return super().from_estimate(src, dst) + + def _estimate(self, src, dst): + F_normalized, src_matrix, dst_matrix = self._setup_constraint_matrix(src, dst) + if np.any(np.isnan(F_normalized + src_matrix + dst_matrix)): + return 'Scaling failed for input points' + + # Enforcing the internal constraint that two singular values must be + # non-zero and one must be zero (rank 2). + U, S, V = np.linalg.svd(F_normalized) + S[2] = 0 + F = U @ np.diag(S) @ V + + self.params = dst_matrix.T @ F @ src_matrix + + return None + + def residuals(self, src, dst): + """Compute the Sampson distance. + + The Sampson distance is the first approximation to the geometric error. + + Parameters + ---------- + src : (N, 2) array + Source coordinates. + dst : (N, 2) array + Destination coordinates. + + Returns + ------- + residuals : (N,) array + Sampson distance. + + """ + src_homogeneous = _append_homogeneous_dim(src) + dst_homogeneous = _append_homogeneous_dim(dst) + + F_src = self.params @ src_homogeneous.T + Ft_dst = self.params.T @ dst_homogeneous.T + + dst_F_src = np.sum(dst_homogeneous * F_src.T, axis=1) + + return np.abs(dst_F_src) / np.sqrt( + F_src[0] ** 2 + F_src[1] ** 2 + Ft_dst[0] ** 2 + Ft_dst[1] ** 2 + ) + + @_deprecate_estimate + def estimate(self, src, dst): + """Estimate fundamental matrix using 8-point algorithm. + + The 8-point algorithm requires at least 8 corresponding point pairs for + a well-conditioned solution, otherwise the over-determined solution is + estimated. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(src, dst) is None + + +class EssentialMatrixTransform(FundamentalMatrixTransform): + """Essential matrix transformation. + + The essential matrix relates corresponding points between a pair of + calibrated images. The matrix transforms normalized, homogeneous image + points in one image to epipolar lines in the other image. + + The essential matrix is only defined for a pair of moving images capturing a + non-planar scene. In the case of pure rotation or planar scenes, the + homography describes the geometric relation between two images + (`ProjectiveTransform`). If the intrinsic calibration of the images is + unknown, the fundamental matrix describes the projective relation between + the two images (`FundamentalMatrixTransform`). + + References + ---------- + .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in + computer vision. Cambridge university press, 2003. + + Parameters + ---------- + rotation : (3, 3) array_like, optional + Rotation matrix of the relative camera motion. + translation : (3, 1) array_like, optional + Translation vector of the relative camera motion. The vector must + have unit length. + matrix : (3, 3) array_like, optional + Essential matrix. + dimensionality : int, optional + Fallback number of dimensions when `matrix` not specified, in which + case, must equal 2 (the default). + + Attributes + ---------- + params : (3, 3) array + Essential matrix. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + >>> + >>> tform = ski.transform.EssentialMatrixTransform( + ... rotation=np.eye(3), translation=np.array([0, 0, 1]) + ... ) + >>> tform.params + array([[ 0., -1., 0.], + [ 1., 0., 0.], + [ 0., 0., 0.]]) + >>> src = np.array([[ 1.839035, 1.924743], + ... [ 0.543582, 0.375221], + ... [ 0.47324 , 0.142522], + ... [ 0.96491 , 0.598376], + ... [ 0.102388, 0.140092], + ... [15.994343, 9.622164], + ... [ 0.285901, 0.430055], + ... [ 0.09115 , 0.254594]]) + >>> dst = np.array([[1.002114, 1.129644], + ... [1.521742, 1.846002], + ... [1.084332, 0.275134], + ... [0.293328, 0.588992], + ... [0.839509, 0.08729 ], + ... [1.779735, 1.116857], + ... [0.878616, 0.602447], + ... [0.642616, 1.028681]]) + >>> tform = ski.transform.EssentialMatrixTransform.from_estimate(src, dst) + >>> tform.residuals(src, dst) + array([0.42455187, 0.01460448, 0.13847034, 0.12140951, 0.27759346, + 0.32453118, 0.00210776, 0.26512283]) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((8, 2)) + >>> bad_tform = ski.transform.EssentialMatrixTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + """ + + # Threshold for determinant of rotation matrix. + _rot_det_tol = 1e-6 + + # Threshold for difference of translation vector from unit length. + _trans_len_tol = 1e-6 + + def __init__( + self, *, rotation=None, translation=None, matrix=None, dimensionality=None + ): + n_rt_none = sum(p is None for p in (rotation, translation)) + if n_rt_none == 1: + raise ValueError( + "Both rotation and translation required when one is specified." + ) + elif n_rt_none == 0: + if matrix is not None: + raise ValueError( + "Do not specify rotation or translation when " + "matrix is specified." + ) + matrix = self._rt2matrix(rotation, translation) + super().__init__(matrix=matrix, dimensionality=dimensionality) + + def _rt2matrix(self, rotation, translation): + rotation = np.asarray(rotation) + translation = np.asarray(translation) + if rotation.shape != (3, 3): + raise ValueError("Invalid shape of rotation matrix") + if abs(np.linalg.det(rotation) - 1) > self._rot_det_tol: + raise ValueError("Rotation matrix must have unit determinant") + if translation.size != 3: + raise ValueError("Invalid shape of translation vector") + if abs(np.linalg.norm(translation) - 1) > self._trans_len_tol: + raise ValueError("Translation vector must have unit length") + # Matrix representation of the cross product for t. + t0, t1, t2 = translation + t_arr = np.array([[0, -t2, t1], [t2, 0, -t0], [-t1, t0, 0]], dtype=float) + return t_arr @ rotation + + @classmethod + def from_estimate(cls, src, dst): + """Estimate essential matrix using 8-point algorithm. + + The 8-point algorithm requires at least 8 corresponding point pairs for + a well-conditioned solution, otherwise the over-determined solution is + estimated. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = EssentialMatrixTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + Raises + ------ + ValueError + If `src` has fewer than 8 rows. + + """ + return super().from_estimate(src, dst) + + def _estimate(self, src, dst): + E_normalized, src_matrix, dst_matrix = self._setup_constraint_matrix(src, dst) + if np.any(np.isnan(E_normalized + src_matrix + dst_matrix)): + return 'Scaling failed for input points' + + # Enforcing the internal constraint that two singular values must be + # equal and one must be zero. + U, S, V = np.linalg.svd(E_normalized) + S[0] = (S[0] + S[1]) / 2.0 + S[1] = S[0] + S[2] = 0 + E = U @ np.diag(S) @ V + + self.params = dst_matrix.T @ E @ src_matrix + + return None + + @_deprecate_estimate + def estimate(self, src, dst): + """Estimate essential matrix using 8-point algorithm. + + The 8-point algorithm requires at least 8 corresponding point pairs for + a well-conditioned solution, otherwise the over-determined solution is + estimated. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(src, dst) is None + + +class ProjectiveTransform(_HMatrixTransform): + r"""Projective transformation. + + Apply a projective transformation (homography) on coordinates. + + For each homogeneous coordinate :math:`\mathbf{x} = [x, y, 1]^T`, its + target position is calculated by multiplying with the given matrix, + :math:`H`, to give :math:`H \mathbf{x}`:: + + [[a0 a1 a2] + [b0 b1 b2] + [c0 c1 1 ]]. + + E.g., to rotate by theta degrees clockwise, the matrix should be:: + + [[cos(theta) -sin(theta) 0] + [sin(theta) cos(theta) 0] + [0 0 1]] + + or, to translate x by 10 and y by 20:: + + [[1 0 10] + [0 1 20] + [0 0 1 ]]. + + Parameters + ---------- + matrix : (D+1, D+1) array_like, optional + Homogeneous transformation matrix. + dimensionality : int, optional + Fallback number of dimensions when `matrix` not specified. + + Attributes + ---------- + params : (D+1, D+1) array + Homogeneous transformation matrix. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transform with an homogeneous transformation matrix: + + >>> tform = ski.transform.ProjectiveTransform(np.diag([2., 3., 1.])) + >>> tform.params + array([[2., 0., 0.], + [0., 3., 0.], + [0., 0., 1.]]) + + You can estimate a transformation to map between source and destination + points: + + >>> src = np.array([[150, 150], + ... [250, 100], + ... [150, 200]]) + >>> dst = np.array([[200, 200], + ... [300, 150], + ... [150, 400]]) + >>> tform = ski.transform.ProjectiveTransform.from_estimate(src, dst) + >>> np.allclose(tform.params, [[ -16.56, 5.82, 895.81], + ... [ -10.31, -8.29, 2075.43], + ... [ -0.05, 0.02, 1. ]], atol=0.01) + True + + Apply the transformation to some image data. + + >>> img = ski.data.astronaut() + >>> warped = ski.transform.warp(img, inverse_map=tform.inverse) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((3, 2)) + >>> bad_tform = ski.transform.ProjectiveTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + """ + + scaling = 'rms' + + @property + def _coeff_inds(self): + """Indices into flat ``self.params`` with coefficients to estimate""" + return range(self.params.size - 1) + + def _check_dims(self, d): + if d >= 2: + return + raise NotImplementedError( + f'Input for {type(self)} should result in transform of >=2D' + ) + + @property + def _inv_matrix(self): + return np.linalg.inv(self.params) + + def __array__(self, dtype=None, copy=None): + return self.params if dtype is None else self.params.astype(dtype) + + def __call__(self, coords): + """Apply forward transformation. + + Parameters + ---------- + coords : (N, D) array_like + Source coordinates. + + Returns + ------- + coords_out : (N, D) array + Destination coordinates. + + """ + return _apply_homogeneous(self.params, coords) + + @property + def inverse(self): + """Return a transform object representing the inverse.""" + return type(self)(matrix=self._inv_matrix) + + @classmethod + def from_estimate(cls, src, dst, weights=None): + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + The transformation is defined as:: + + X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1) + Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1) + + These equations can be transformed to the following form:: + + 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X + 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y + + which exist for each set of corresponding points, so we have a set of + N * 2 equations. The coefficients appear linearly so we can write + A x = 0, where:: + + A = [[x y 1 0 0 0 -x*X -y*X -X] + [0 0 0 x y 1 -x*Y -y*Y -Y] + ... + ... + ] + x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3] + + In case of total least-squares the solution of this homogeneous system + of equations is the right singular vector of A which corresponds to the + smallest singular value normed by the coefficient c3. + + Weights can be applied to each pair of corresponding points to + indicate, particularly in an overdetermined system, if point pairs have + higher or lower confidence or uncertainties associated with them. From + the matrix treatment of least squares problems, these weight values are + normalized, square-rooted, then built into a diagonal matrix, by which + A is multiplied. + + In case of the affine transformation the coefficients c0 and c1 are 0. + Thus the system of equations is:: + + A = [[x y 1 0 0 0 -X] + [0 0 0 x y 1 -Y] + ... + ... + ] + x.T = [a0 a1 a2 b0 b1 b2 c3] + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + weights : (N,) array_like, optional + Relative weight values for each pair of points. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = ProjectiveTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + """ + return super().from_estimate(src, dst, weights) + + def _estimate(self, src, dst, weights=None): + src = np.asarray(src) + dst = np.asarray(dst) + n, d = src.shape + fail_matrix = np.full((d + 1, d + 1), np.nan) + + src_matrix, src = _center_and_normalize_points(src) + dst_matrix, dst = _center_and_normalize_points(dst) + if not np.all(np.isfinite(src_matrix + dst_matrix)): + self.params = fail_matrix + return 'Scaling generated NaN values' + + # params: a0, a1, a2, b0, b1, b2, c0, c1 + A = np.zeros((n * d, (d + 1) ** 2)) + # fill the A matrix with the appropriate block matrices; see docstring + # for 2D example — this can be generalised to more blocks in the 3D and + # higher-dimensional cases. + for ddim in range(d): + A[ddim * n : (ddim + 1) * n, ddim * (d + 1) : ddim * (d + 1) + d] = src + A[ddim * n : (ddim + 1) * n, ddim * (d + 1) + d] = 1 + A[ddim * n : (ddim + 1) * n, -d - 1 : -1] = src + A[ddim * n : (ddim + 1) * n, -1] = -1 + A[ddim * n : (ddim + 1) * n, -d - 1 :] *= -dst[:, ddim : (ddim + 1)] + + # Select relevant columns, depending on params + A = A[:, list(self._coeff_inds) + [-1]] + + # Get the vectors that correspond to singular values, also applying + # the weighting if provided + if weights is None: + _, _, V = np.linalg.svd(A) + else: + weights = np.asarray(weights) + W = np.diag(np.tile(np.sqrt(weights / np.max(weights)), d)) + _, _, V = np.linalg.svd(W @ A) + + H = np.zeros((d + 1, d + 1)) + # Solution is right singular vector that corresponds to smallest + # singular value. + if np.isclose(V[-1, -1], 0): + self.params = fail_matrix + return 'Right singular vector has 0 final element' + + H.flat[list(self._coeff_inds) + [-1]] = -V[-1, :-1] / V[-1, -1] + H[d, d] = 1 + + # De-center and de-normalize + H = np.linalg.inv(dst_matrix) @ H @ src_matrix + + # Small errors can creep in if points are not exact, causing the last + # element of H to deviate from unity. Correct for that here. + H /= H[-1, -1] + + self.params = H + + return None + + def __add__(self, other): + """Combine this transformation with another.""" + if isinstance(other, ProjectiveTransform): + # combination of the same types result in a transformation of this + # type again, otherwise use general projective transformation + if type(self) == type(other): + tform = self.__class__ + else: + tform = ProjectiveTransform + return tform(other.params @ self.params) + else: + raise TypeError("Cannot combine transformations of differing " "types.") + + def __nice__(self): + """common 'paramstr' used by __str__ and __repr__""" + if not hasattr(self, 'params'): + return '' + npstring = np.array2string(self.params, separator=', ') + return 'matrix=\n' + textwrap.indent(npstring, ' ') + + def __repr__(self): + """Add standard repr formatting around a __nice__ string""" + return f'<{type(self).__name__}({self.__nice__()}) at {hex(id(self))}>' + + def __str__(self): + """Add standard str formatting around a __nice__ string""" + return f'<{type(self).__name__}({self.__nice__()})>' + + @property + def dimensionality(self): + """The dimensionality of the transformation.""" + return self.params.shape[0] - 1 + + @classmethod + def identity(cls, dimensionality=None): + """Identity transform + + Parameters + ---------- + dimensionality : {None, int}, optional + Dimensionality of identity transform. + + Returns + ------- + tform : transform + Transform such that ``np.all(tform(pts) == pts)``. + """ + return super().identity(dimensionality=dimensionality) + + @_deprecate_estimate + def estimate(self, src, dst, weights=None): + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + The transformation is defined as:: + + X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1) + Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1) + + These equations can be transformed to the following form:: + + 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X + 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y + + which exist for each set of corresponding points, so we have a set of + N * 2 equations. The coefficients appear linearly so we can write + A x = 0, where:: + + A = [[x y 1 0 0 0 -x*X -y*X -X] + [0 0 0 x y 1 -x*Y -y*Y -Y] + ... + ... + ] + x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3] + + In case of total least-squares the solution of this homogeneous system + of equations is the right singular vector of A which corresponds to the + smallest singular value normed by the coefficient c3. + + Weights can be applied to each pair of corresponding points to + indicate, particularly in an overdetermined system, if point pairs have + higher or lower confidence or uncertainties associated with them. From + the matrix treatment of least squares problems, these weight values are + normalized, square-rooted, then built into a diagonal matrix, by which + A is multiplied. + + In case of the affine transformation the coefficients c0 and c1 are 0. + Thus the system of equations is:: + + A = [[x y 1 0 0 0 -X] + [0 0 0 x y 1 -Y] + ... + ... + ] + x.T = [a0 a1 a2 b0 b1 b2 c3] + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + weights : (N,) array_like, optional + Relative weight values for each pair of points. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(src, dst, weights) is None + + +@_update_from_estimate_docstring +@_deprecate_inherited_estimate +class AffineTransform(ProjectiveTransform): + """Affine transformation. + + Has the following form:: + + X = a0 * x + a1 * y + a2 + = sx * x * [cos(rotation) + tan(shear_y) * sin(rotation)] + - sy * y * [tan(shear_x) * cos(rotation) + sin(rotation)] + + translation_x + + Y = b0 * x + b1 * y + b2 + = sx * x * [sin(rotation) - tan(shear_y) * cos(rotation)] + - sy * y * [tan(shear_x) * sin(rotation) - cos(rotation)] + + translation_y + + where ``sx`` and ``sy`` are scale factors in the x and y directions. + + This is equivalent to applying the operations in the following order: + + 1. Scale + 2. Shear + 3. Rotate + 4. Translate + + The homogeneous transformation matrix is:: + + [[a0 a1 a2] + [b0 b1 b2] + [0 0 1]] + + In 2D, the transformation parameters can be given as the homogeneous + transformation matrix, above, or as the implicit parameters, scale, + rotation, shear, and translation in x (a2) and y (b2). For 3D and higher, + only the matrix form is allowed. + + In narrower transforms, such as the Euclidean (only rotation and + translation) or Similarity (rotation, translation, and a global scale + factor) transforms, it is possible to specify 3D transforms using implicit + parameters also. + + Parameters + ---------- + matrix : (D+1, D+1) array_like, optional + Homogeneous transformation matrix. If this matrix is provided, it is an + error to provide any of scale, rotation, shear, or translation. + scale : {s as float or (sx, sy) as array, list or tuple}, optional + Scale factor(s). If a single value, it will be assigned to both + sx and sy. Only available for 2D. + + .. versionadded:: 0.17 + Added support for supplying a single scalar value. + shear : float or 2-tuple of float, optional + The x and y shear angles, clockwise, by which these axes are + rotated around the origin [2]. + If a single value is given, take that to be the x shear angle, with + the y angle remaining 0. Only available in 2D. + rotation : float, optional + Rotation angle, clockwise, as radians. Only available for 2D. + translation : (tx, ty) as array, list or tuple, optional + Translation parameters. Only available for 2D. + dimensionality : int, optional + Fallback number of dimensions for transform when none of `matrix`, + `scale`, `rotation`, `shear` or `translation` are specified. If any of + `scale`, `rotation`, `shear` or `translation` are specified, must equal + 2 (the default). + + Attributes + ---------- + params : (D+1, D+1) array + Homogeneous transformation matrix. + + Raises + ------ + ValueError + If both ``matrix`` and any of the other parameters are provided. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transform with an homogeneous transformation matrix: + + >>> tform = ski.transform.AffineTransform(np.diag([2., 3., 1.])) + >>> tform.params + array([[2., 0., 0.], + [0., 3., 0.], + [0., 0., 1.]]) + + Define a transform with parameters: + + >>> tform = ski.transform.AffineTransform(scale=4, rotation=0.2) + >>> np.round(tform.params, 2) + array([[ 3.92, -0.79, 0. ], + [ 0.79, 3.92, 0. ], + [ 0. , 0. , 1. ]]) + + You can estimate a transformation to map between source and destination + points: + + >>> src = np.array([[150, 150], + ... [250, 100], + ... [150, 200]]) + >>> dst = np.array([[200, 200], + ... [300, 150], + ... [150, 400]]) + >>> tform = ski.transform.AffineTransform.from_estimate(src, dst) + >>> np.allclose(tform.params, [[ 0.5, -1. , 275. ], + ... [ 1.5, 4. , -625. ], + ... [ 0. , 0. , 1. ]]) + True + + Apply the transformation to some image data. + + >>> img = ski.data.astronaut() + >>> warped = ski.transform.warp(img, inverse_map=tform.inverse) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((3, 2)) + >>> bad_tform = ski.transform.AffineTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + + References + ---------- + .. [1] Wikipedia, "Affine transformation", + https://en.wikipedia.org/wiki/Affine_transformation#Image_transformation + .. [2] Wikipedia, "Shear mapping", + https://en.wikipedia.org/wiki/Shear_mapping + """ + + def __init__( + self, + matrix=None, + *, + scale=None, + shear=None, + rotation=None, + translation=None, + dimensionality=None, + ): + n_srst_none = sum(p is None for p in (scale, rotation, shear, translation)) + if n_srst_none != 4: + if matrix is not None: + raise ValueError( + "Do not specify any implicit parameters when " + "matrix is specified." + ) + if dimensionality is not None and dimensionality > 2: + raise ValueError('Implicit parameters only valid for 2D transforms') + # 2D parameter checks explicit or implicit in _srst2matrix. + matrix = self._srst2matrix(scale, rotation, shear, translation) + if matrix.shape[0] != 3: + raise ValueError('Implicit parameters must give 2D transforms') + super().__init__(matrix=matrix, dimensionality=dimensionality) + + @property + def _coeff_inds(self): + """Indices into flat ``self.params`` with coefficients to estimate""" + return range(self.dimensionality * (self.dimensionality + 1)) + + def _srst2matrix(self, scale, rotation, shear, translation): + scale = (1, 1) if scale is None else scale + sx, sy = (scale, scale) if np.isscalar(scale) else scale + rotation = 0 if rotation is None else rotation + if not np.isscalar(rotation): + raise ValueError('rotation must be scalar (2D rotation)') + shear = 0 if shear is None else shear + shear_x, shear_y = (shear, 0) if np.isscalar(shear) else shear + translation = (0, 0) if translation is None else translation + if np.isscalar(translation): + raise ValueError('translation must be length 2') + a2, b2 = translation + + a0 = sx * (math.cos(rotation) + math.tan(shear_y) * math.sin(rotation)) + a1 = -sy * (math.tan(shear_x) * math.cos(rotation) + math.sin(rotation)) + + b0 = sx * (math.sin(rotation) - math.tan(shear_y) * math.cos(rotation)) + b1 = -sy * (math.tan(shear_x) * math.sin(rotation) - math.cos(rotation)) + return np.array([[a0, a1, a2], [b0, b1, b2], [0, 0, 1]]) + + @property + def scale(self): + if self.dimensionality != 2: + return np.sqrt(np.sum(self.params**2, axis=0))[: self.dimensionality] + ss = np.sum(self.params**2, axis=0) + ss[1] = ss[1] / (math.tan(self.shear) ** 2 + 1) + return np.sqrt(ss)[: self.dimensionality] + + @property + def rotation(self): + if self.dimensionality != 2: + raise NotImplementedError( + 'The rotation property is only implemented for 2D transforms.' + ) + return math.atan2(self.params[1, 0], self.params[0, 0]) + + @property + def shear(self): + if self.dimensionality != 2: + raise NotImplementedError( + 'The shear property is only implemented for 2D transforms.' + ) + beta = math.atan2(-self.params[0, 1], self.params[1, 1]) + return beta - self.rotation + + @property + def translation(self): + return self.params[0 : self.dimensionality, self.dimensionality] + + +class PiecewiseAffineTransform(_GeometricTransform): + """Piecewise affine transformation. + + Control points are used to define the mapping. The transform is based on + a Delaunay triangulation of the points to form a mesh. Each triangle is + used to find a local affine transform. + + Attributes + ---------- + affines : list of AffineTransform objects + Affine transformations for each triangle in the mesh. + inverse_affines : list of AffineTransform objects + Inverse affine transformations for each triangle in the mesh. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transformation by estimation: + + >>> src = [[-12.3705, -10.5075], + ... [-10.7865, 15.4305], + ... [8.6985, 10.8675], + ... [11.4975, -9.5715], + ... [7.8435, 7.4835], + ... [-5.3325, 6.5025], + ... [6.7905, -6.3765], + ... [-6.1695, -0.8235]] + >>> dst = [[0, 0], + ... [0, 5800], + ... [4900, 5800], + ... [4900, 0], + ... [4479, 4580], + ... [1176, 3660], + ... [3754, 790], + ... [1024, 1931]] + >>> tform = ski.transform.PiecewiseAffineTransform.from_estimate(src, dst) + + Calling the transform applies the transformation to the points: + + >>> np.allclose(tform(src), dst) + True + + You can apply the inverse transform: + + >>> np.allclose(tform.inverse(dst), src) + True + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = [[1, 1]] * 6 + src[6:] + >>> bad_tform = ski.transform.PiecewiseAffineTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + """ + + def __init__(self): + self._tesselation = None + self._inverse_tesselation = None + self.affines = None + self.inverse_affines = None + + @classmethod + def from_estimate(cls, src, dst): + """Estimate the transformation from a set of corresponding points. + + Number of source and destination coordinates must match. + + Parameters + ---------- + src : (N, D) array_like + Source coordinates. + dst : (N, D) array_like + Destination coordinates. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = PiecewiseAffineTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + """ + return super().from_estimate(src, dst) + + def _estimate(self, src, dst): + src = np.asarray(src) + dst = np.asarray(dst) + N, D = src.shape + + # forward piecewise affine + # triangulate input positions into mesh + self._tesselation = spatial.Delaunay(src) + + fail_matrix = np.full((D + 1, D + 1), np.nan) + + # find affine mapping from source positions to destination + self.affines = [] + messages = [] + for i, tri in enumerate(self._tesselation.simplices): + affine = AffineTransform.from_estimate(src[tri, :], dst[tri, :]) + if not affine: + messages.append(f'Failure at forward simplex {i}: {affine}') + affine = AffineTransform(fail_matrix.copy()) + self.affines.append(affine) + + # inverse piecewise affine + # triangulate input positions into mesh + self._inverse_tesselation = spatial.Delaunay(dst) + # find affine mapping from source positions to destination + self.inverse_affines = [] + for i, tri in enumerate(self._inverse_tesselation.simplices): + affine = AffineTransform.from_estimate(dst[tri, :], src[tri, :]) + if not affine: + messages.append(f'Failure at inverse simplex {i}: {affine}') + affine = AffineTransform(fail_matrix.copy()) + self.inverse_affines.append(affine) + + return '; '.join(messages) if messages else None + + def __call__(self, coords): + """Apply forward transformation. + + Coordinates outside of the mesh will be set to `- 1`. + + Parameters + ---------- + coords : (N, D) array_like + Source coordinates. + + Returns + ------- + coords : (N, 2) array + Transformed coordinates. + + """ + coords = np.asarray(coords) + out = np.empty_like(coords, np.float64) + + # determine triangle index for each coordinate + simplex = self._tesselation.find_simplex(coords) + + # coordinates outside of mesh + out[simplex == -1, :] = -1 + + for index in range(len(self._tesselation.simplices)): + # affine transform for triangle + affine = self.affines[index] + # all coordinates within triangle + index_mask = simplex == index + + out[index_mask, :] = affine(coords[index_mask, :]) + + return out + + @property + def inverse(self): + """Return a transform object representing the inverse.""" + tform = type(self)() + # Copy parameters (None or list) for safety. + tform._tesselation = copy(self._inverse_tesselation) + tform._inverse_tesselation = copy(self._tesselation) + tform.affines = copy(self.inverse_affines) + tform.inverse_affines = copy(self.affines) + return tform + + @classmethod + def identity(cls, dimensionality=None): + """Identity transform + + Parameters + ---------- + dimensionality : optional + This transform does not use the `dimensionality` parameter, so the + value is ignored. The parameter exists for compatibility with + other transforms. + + Returns + ------- + tform : transform + Transform such that ``np.all(tform(pts) == pts)``. + """ + return cls() + + @_deprecate_estimate + def estimate(self, src, dst): + """Estimate the transformation from a set of corresponding points. + + Number of source and destination coordinates must match. + + Parameters + ---------- + src : (N, D) array_like + Source coordinates. + dst : (N, D) array_like + Destination coordinates. + + Returns + ------- + success : bool + True, if all pieces of the model are successfully estimated. + + """ + return self._estimate(src, dst) is None + + +def _euler_rotation_matrix(angles, degrees=False): + """Produce an Euler rotation matrix from the given intrinsic rotation angles + for the axes x, y and z. + + Parameters + ---------- + angles : array of float, shape (3,) + The transformation angles in radians. + degrees : bool, optional + If True, then the given angles are assumed to be in degrees. Default is False. + + Returns + ------- + R : array of float, shape (3, 3) + The Euler rotation matrix. + + """ + return spatial.transform.Rotation.from_euler( + 'XYZ', angles=angles, degrees=degrees + ).as_matrix() + + +class EuclideanTransform(ProjectiveTransform): + """Euclidean transformation, also known as a rigid transform. + + Has the following form:: + + X = a0 * x - b0 * y + a1 = + = x * cos(rotation) - y * sin(rotation) + a1 + + Y = b0 * x + a0 * y + b1 = + = x * sin(rotation) + y * cos(rotation) + b1 + + where the homogeneous transformation matrix is:: + + [[a0 -b0 a1] + [b0 a0 b1] + [0 0 1 ]] + + The Euclidean transformation is a rigid transformation with rotation and + translation parameters. The similarity transformation extends the Euclidean + transformation with a single scaling factor. + + In 2D and 3D, the transformation parameters may be provided either via + `matrix`, the homogeneous transformation matrix, above, or via the + implicit parameters `rotation` and/or `translation` (where `a1` is the + translation along `x`, `b1` along `y`, etc.). Beyond 3D, if the + transformation is only a translation, you may use the implicit parameter + `translation`; otherwise, you must use `matrix`. + + The implicit parameters are applied in the following order: + + 1. Rotation; + 2. Translation. + + Parameters + ---------- + matrix : (D+1, D+1) array_like, optional + Homogeneous transformation matrix. + rotation : float or sequence of float, optional + Rotation angle, clockwise, in radians. If given as a vector, it is + interpreted as Euler rotation angles [1]_. Only 2D (single rotation) + and 3D (Euler rotations) values are supported. For higher dimensions, + you must provide or estimate the transformation matrix instead, and + pass that as `matrix` above. + translation : (x, y[, z, ...]) sequence of float, length D, optional + Translation parameters for each axis. + dimensionality : int, optional + Fallback number of dimensions for transform when no other parameter + is specified. Otherwise ignored, and we infer dimensionality from the + input parameters. + + Attributes + ---------- + params : (D+1, D+1) array + Homogeneous transformation matrix. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transform with an homogeneous transformation matrix: + + >>> tform = ski.transform.EuclideanTransform(np.diag([2., 3., 1.])) + >>> tform.params + array([[2., 0., 0.], + [0., 3., 0.], + [0., 0., 1.]]) + + Define a transform with parameters: + + >>> tform = ski.transform.EuclideanTransform( + ... rotation=0.2, translation=[1, 2]) + >>> np.round(tform.params, 2) + array([[ 0.98, -0.2 , 1. ], + [ 0.2 , 0.98, 2. ], + [ 0. , 0. , 1. ]]) + + You can estimate a transformation to map between source and destination + points: + + >>> src = np.array([[150, 150], + ... [250, 100], + ... [150, 200]]) + >>> dst = np.array([[200, 200], + ... [300, 150], + ... [150, 400]]) + >>> tform = ski.transform.EuclideanTransform.from_estimate(src, dst) + >>> np.allclose(tform.params, [[ 0.99, 0.12, 16.77], + ... [-0.12, 0.99, 122.91], + ... [ 0. , 0. , 1. ]], atol=0.01) + True + + Apply the transformation to some image data. + + >>> img = ski.data.astronaut() + >>> warped = ski.transform.warp(img, inverse_map=tform.inverse) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((3, 2)) + >>> bad_tform = ski.transform.EuclideanTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions + + """ + + # Whether to estimate scale during estimation. + _estimate_scale = False + + def __init__( + self, matrix=None, *, rotation=None, translation=None, dimensionality=None + ): + n_rt_none = sum(p is None for p in (rotation, translation)) + if n_rt_none != 2: + if matrix is not None: + raise ValueError( + "Do not specify any implicit parameters when " + "matrix is specified." + ) + n_dims, chk_msg = self._rt2ndims_msg(rotation, translation) + if chk_msg is not None: + raise ValueError(chk_msg) + matrix = self._rt2matrix(rotation, translation, n_dims) + super().__init__(matrix=matrix, dimensionality=dimensionality) + + def _rt2ndims_msg(self, rotation, translation): + if rotation is not None: + N = 1 if np.isscalar(rotation) else len(rotation) + msg = ( + '``rotations`` must be scalar (3D) or length 3 (3D)' + if N not in (1, 3) + else None + ) + return 2 if N == 1 else N, msg + if translation is not None: + return (2 if np.isscalar(translation) else len(translation), None) + return None, None + + def _rt2matrix(self, rotation, translation, n_dims): + if translation is None: + translation = (0,) * n_dims + if rotation is None: + rotation = 0 if n_dims == 2 else np.zeros(3) + matrix = np.eye(n_dims + 1) + if n_dims == 2: + cos_r, sin_r = math.cos(rotation), math.sin(rotation) + matrix[:2, :2] = [[cos_r, -sin_r], [sin_r, cos_r]] + elif n_dims == 3: + matrix[:3, :3] = _euler_rotation_matrix(rotation) + matrix[0:n_dims, n_dims] = translation + return matrix + + @classmethod + def from_estimate(cls, src, dst) -> Self | FailedEstimation: + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = EuclideanTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + """ + # Use base implementation to avoid weights argument of + # ProjectiveTransform ancestor class. + return _from_estimate(cls, src, dst) + + def _estimate(self, src, dst): + self.params = _umeyama(src, dst, self._estimate_scale) + + # _umeyama will return nan if the problem is not well-conditioned. + return ( + 'Poor conditioning for estimation' + if np.any(np.isnan(self.params)) + else None + ) + + @property + def rotation(self): + if self.dimensionality == 2: + return math.atan2(self.params[1, 0], self.params[1, 1]) + elif self.dimensionality == 3: + # Returning 3D Euler rotation matrix + return self.params[:3, :3] + else: + raise NotImplementedError( + 'Rotation only implemented for 2D and 3D transforms.' + ) + + @property + def translation(self): + return self.params[0 : self.dimensionality, self.dimensionality] + + @_deprecate_estimate + def estimate(self, src, dst): + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(src, dst) is None + + +@_update_from_estimate_docstring +@_deprecate_inherited_estimate +class SimilarityTransform(EuclideanTransform): + """Similarity transformation. + + Has the following form in 2D:: + + X = a0 * x - b0 * y + a1 = + = s * x * cos(rotation) - s * y * sin(rotation) + a1 + + Y = b0 * x + a0 * y + b1 = + = s * x * sin(rotation) + s * y * cos(rotation) + b1 + + where ``s`` is a scale factor and the homogeneous transformation matrix is:: + + [[a0 -b0 a1] + [b0 a0 b1] + [0 0 1 ]] + + The similarity transformation extends the Euclidean transformation with a + single scaling factor in addition to the rotation and translation + parameters. + + The implicit parameters are applied in the following order: + + 1. Scale; + 2. Rotation; + 3. Translation. + + Parameters + ---------- + matrix : (dim+1, dim+1) array_like, optional + Homogeneous transformation matrix. + scale : float, optional + Scale factor. Implemented only for 2D and 3D. + rotation : float, optional + Rotation angle, clockwise, as radians. + Implemented only for 2D and 3D. For 3D, this is given in ZYX Euler + angles. + translation : (dim,) array_like, optional + x, y[, z] translation parameters. Implemented only for 2D and 3D. + dimensionality : int, optional + The dimensionality of the transform, corresponding to ``dim`` above. + Ignored if `matrix` is not None, and set to ``matrix.shape[0] - 1``. + Otherwise, must be one of 2 or 3. + + Attributes + ---------- + params : (dim+1, dim+1) array + Homogeneous transformation matrix. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transform with an homogeneous transformation matrix: + + >>> tform = ski.transform.SimilarityTransform(np.diag([2., 3., 1.])) + >>> tform.params + array([[2., 0., 0.], + [0., 3., 0.], + [0., 0., 1.]]) + + Define a transform with parameters: + + >>> tform = ski.transform.SimilarityTransform( + ... rotation=0.2, translation=[1, 2]) + >>> np.round(tform.params, 2) + array([[ 0.98, -0.2 , 1. ], + [ 0.2 , 0.98, 2. ], + [ 0. , 0. , 1. ]]) + + You can estimate a transformation to map between source and destination + points: + + >>> src = np.array([[150, 150], + ... [250, 100], + ... [150, 200]]) + >>> dst = np.array([[200, 200], + ... [300, 150], + ... [150, 400]]) + >>> tform = ski.transform.SimilarityTransform.from_estimate(src, dst) + >>> np.allclose(tform.params, [[ 1.79, 0.21, -142.86], + ... [-0.21, 1.79, 21.43], + ... [ 0. , 0. , 1. ]], atol=0.01) + True + + Apply the transformation to some image data. + + >>> img = ski.data.astronaut() + >>> warped = ski.transform.warp(img, inverse_map=tform.inverse) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((3, 2)) + >>> bad_tform = ski.transform.SimilarityTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + """ + + # Whether to estimate scale during estimation. + _estimate_scale = True + + def __init__( + self, + matrix=None, + *, + scale=None, + rotation=None, + translation=None, + dimensionality=None, + ): + n_srt_none = sum(p is None for p in (scale, rotation, translation)) + if n_srt_none != 3: + if matrix is not None: + raise ValueError( + "Do not specify any implicit parameters when " + "matrix is specified." + ) + self._check_scale(scale, (rotation, translation), dimensionality) + # Scale is special. Scalar scale does not tell us the dimensions. + if scale is not None and not np.isscalar(scale): + n_dims, chk_msg = len(scale), None + else: + n_dims, chk_msg = self._rt2ndims_msg(rotation, translation) + if chk_msg is not None: + raise ValueError(chk_msg) + # n_dims can be None for scalar scale, other parameters are None. + n_dims = ( + n_dims + if n_dims is not None + else dimensionality + if dimensionality is not None + else 2 + ) + matrix = self._rt2matrix(rotation, translation, n_dims) + if scale not in (None, 1): + matrix[:n_dims, :n_dims] *= scale + super().__init__(matrix=matrix, dimensionality=dimensionality) + + def _check_scale(self, scale, other_params, dimensionality): + """Check, warn for scalar scaling""" + if dimensionality in (None, 2) or scale is None or not np.isscalar(scale): + return + if all(p is None for p in other_params): + warnings.warn( + 'In the future, it will be a ValueError to pass a ' + 'scalar `scale` value with a ``dimensionality`` ' + '> 2\n,and without other implicit parameters ' + 'to indicate the dimensionality of the transform.\n' + 'Please indicate dimensionality by passing a vector ' + 'of suitable length to `scale`.', + FutureWarning, + stacklevel=2, + ) + + @property + def scale(self): + # det = scale**(# of dimensions), therefore scale = det**(1/ndim) + if self.dimensionality == 2: + return np.sqrt(np.linalg.det(self.params)) + elif self.dimensionality == 3: + return np.cbrt(np.linalg.det(self.params)) + else: + raise NotImplementedError('Scale is only implemented for 2D and 3D.') + + +class PolynomialTransform(_GeometricTransform): + """2D polynomial transformation. + + Has the following form:: + + X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) + Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) + + Parameters + ---------- + params : (2, N) array_like, optional + Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So, + a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`. + dimensionality : int, optional + Must have value 2 (the default) for polynomial transforms. + + Attributes + ---------- + params : (2, N) array + Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So, + a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + Define a transformation by estimation: + + >>> src = [[-12.3705, -10.5075], + ... [-10.7865, 15.4305], + ... [8.6985, 10.8675], + ... [11.4975, -9.5715], + ... [7.8435, 7.4835], + ... [-5.3325, 6.5025], + ... [6.7905, -6.3765], + ... [-6.1695, -0.8235]] + >>> dst = [[0, 0], + ... [0, 5800], + ... [4900, 5800], + ... [4900, 0], + ... [4479, 4580], + ... [1176, 3660], + ... [3754, 790], + ... [1024, 1931]] + >>> tform = ski.transform.PolynomialTransform.from_estimate(src, dst) + + Calling the transform applies the transformation to the points: + + >>> pts = tform(src) + >>> np.allclose(pts, [[ 7.54, 12.27], + ... [ 2.98, 5796.95], + ... [4870.44, 5766.59], + ... [4889.72, -6.72], + ... [4515.62, 4617.5 ], + ... [1183.25, 3694. ], + ... [3767.57, 800.53], + ... [ 998.02, 1881.97]], atol=0.01) + True + """ + + def __init__(self, params=None, *, dimensionality=None): + if dimensionality is None: + dimensionality = 2 + elif dimensionality != 2: + raise NotImplementedError( + 'Polynomial transforms are only implemented for 2D.' + ) + self.params = np.array([[0, 1, 0], [0, 0, 1]] if params is None else params) + if self.params.shape == () or self.params.shape[0] != 2: + raise ValueError("Transformation parameters must be shape (2, N)") + + @classmethod + def from_estimate(cls, src, dst, order=2, weights=None): + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + The transformation is defined as:: + + X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) + Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) + + These equations can be transformed to the following form:: + + 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X + 0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y + + which exist for each set of corresponding points, so we have a set of + N * 2 equations. The coefficients appear linearly so we can write + A x = 0, where:: + + A = [[1 x y x**2 x*y y**2 ... 0 ... 0 -X] + [0 ... 0 1 x y x**2 x*y y**2 -Y] + ... + ... + ] + x.T = [a00 a10 a11 a20 a21 a22 ... ann + b00 b10 b11 b20 b21 b22 ... bnn c3] + + In case of total least-squares the solution of this homogeneous system + of equations is the right singular vector of A which corresponds to the + smallest singular value normed by the coefficient c3. + + Weights can be applied to each pair of corresponding points to + indicate, particularly in an overdetermined system, if point pairs have + higher or lower confidence or uncertainties associated with them. From + the matrix treatment of least squares problems, these weight values are + normalized, square-rooted, then built into a diagonal matrix, by which + A is multiplied. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + order : int, optional + Polynomial order (number of coefficients is order + 1). + weights : (N,) array_like, optional + Relative weight values for each pair of points. + + Returns + ------- + tf : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tf = PolynomialTransform.from_estimate(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + """ + return super().from_estimate(src, dst, order, weights) + + def _estimate(self, src, dst, order=2, weights=None): + src = np.asarray(src) + dst = np.asarray(dst) + xs = src[:, 0] + ys = src[:, 1] + xd = dst[:, 0] + yd = dst[:, 1] + rows = src.shape[0] + + # number of unknown polynomial coefficients + order = safe_as_int(order) + u = (order + 1) * (order + 2) + + A = np.zeros((rows * 2, u + 1)) + pidx = 0 + for j in range(order + 1): + for i in range(j + 1): + A[:rows, pidx] = xs ** (j - i) * ys**i + A[rows:, pidx + u // 2] = xs ** (j - i) * ys**i + pidx += 1 + + A[:rows, -1] = xd + A[rows:, -1] = yd + + # Get the vectors that correspond to singular values, also applying + # the weighting if provided + if weights is None: + _, _, V = np.linalg.svd(A) + else: + weights = np.asarray(weights) + W = np.diag(np.tile(np.sqrt(weights / np.max(weights)), 2)) + _, _, V = np.linalg.svd(W @ A) + + # solution is right singular vector that corresponds to smallest + # singular value + params = -V[-1, :-1] / V[-1, -1] + + self.params = params.reshape((2, u // 2)) + + return None + + def __call__(self, coords): + """Apply forward transformation. + + Parameters + ---------- + coords : (N, 2) array_like + source coordinates + + Returns + ------- + coords : (N, 2) array + Transformed coordinates. + + """ + coords = np.asarray(coords) + x = coords[:, 0] + y = coords[:, 1] + u = len(self.params.ravel()) + # number of coefficients -> u = (order + 1) * (order + 2) + order = int((-3 + math.sqrt(9 - 4 * (2 - u))) / 2) + dst = np.zeros(coords.shape) + + pidx = 0 + for j in range(order + 1): + for i in range(j + 1): + dst[:, 0] += self.params[0, pidx] * x ** (j - i) * y**i + dst[:, 1] += self.params[1, pidx] * x ** (j - i) * y**i + pidx += 1 + + return dst + + @classmethod + def identity(cls, dimensionality=None): + """Identity transform + + Parameters + ---------- + dimensionality : {None, 2}, optional + This transform only allows dimensionality of 2, where None + corresponds to 2. The parameter exists for compatibility with other + transforms. + + Returns + ------- + tform : transform + Transform such that ``np.all(tform(pts) == pts)``. + """ + return cls(params=None, dimensionality=dimensionality) + + @property + def inverse(self): + raise NotImplementedError( + 'There is no explicit way to do the inverse polynomial ' + 'transformation. Instead, estimate the inverse transformation ' + 'parameters by exchanging source and destination coordinates,' + 'then apply the forward transformation.' + ) + + @_deprecate_estimate + def estimate(self, src, dst, order=2, weights=None): + """Estimate the transformation from a set of corresponding points. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + The transformation is defined as:: + + X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) + Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) + + These equations can be transformed to the following form:: + + 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X + 0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y + + which exist for each set of corresponding points, so we have a set of + N * 2 equations. The coefficients appear linearly so we can write + A x = 0, where:: + + A = [[1 x y x**2 x*y y**2 ... 0 ... 0 -X] + [0 ... 0 1 x y x**2 x*y y**2 -Y] + ... + ... + ] + x.T = [a00 a10 a11 a20 a21 a22 ... ann + b00 b10 b11 b20 b21 b22 ... bnn c3] + + In case of total least-squares the solution of this homogeneous system + of equations is the right singular vector of A which corresponds to the + smallest singular value normed by the coefficient c3. + + Weights can be applied to each pair of corresponding points to + indicate, particularly in an overdetermined system, if point pairs have + higher or lower confidence or uncertainties associated with them. From + the matrix treatment of least squares problems, these weight values are + normalized, square-rooted, then built into a diagonal matrix, by which + A is multiplied. + + Parameters + ---------- + src : (N, 2) array_like + Source coordinates. + dst : (N, 2) array_like + Destination coordinates. + order : int, optional + Polynomial order (number of coefficients is order + 1). + weights : (N,) array_like, optional + Relative weight values for each pair of points. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(src, dst, order, weights) is None + + +TRANSFORMS = { + 'euclidean': EuclideanTransform, + 'similarity': SimilarityTransform, + 'affine': AffineTransform, + 'piecewise-affine': PiecewiseAffineTransform, + 'projective': ProjectiveTransform, + 'fundamental': FundamentalMatrixTransform, + 'essential': EssentialMatrixTransform, + 'polynomial': PolynomialTransform, +} + + +def estimate_transform(ttype, src, dst, *args, **kwargs): + """Estimate 2D geometric transformation parameters. + + You can determine the over-, well- and under-determined parameters + with the total least-squares method. + + Number of source and destination coordinates must match. + + Parameters + ---------- + ttype : {'euclidean', similarity', 'affine', 'piecewise-affine', \ + 'projective', 'polynomial'} + Type of transform. + kwargs : array_like or int + Function parameters (src, dst, n, angle):: + + NAME / TTYPE FUNCTION PARAMETERS + 'euclidean' `src, `dst` + 'similarity' `src, `dst` + 'affine' `src, `dst` + 'piecewise-affine' `src, `dst` + 'projective' `src, `dst` + 'polynomial' `src, `dst`, `order` (polynomial order, + default order is 2) + + Also see examples below. + + Returns + ------- + tf : :class:`_GeometricTransform` or ``FailedEstimation`` + An instance of the requested transformation if the estimation + Otherwise, we return a special ``FailedEstimation`` object to signal a + failed estimation. Testing the truth value of the failed estimation + object will return ``False``. E.g. + + .. code-block:: python + + tf = estimate_transform(...) + if not tf: + raise RuntimeError(f"Failed estimation: {tf}") + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + + >>> # estimate transformation parameters + >>> src = np.array([0, 0, 10, 10]).reshape((2, 2)) + >>> dst = np.array([12, 14, 1, -20]).reshape((2, 2)) + + >>> tform = ski.transform.estimate_transform('similarity', src, dst) + + >>> np.allclose(tform.inverse(tform(src)), src) + True + + >>> # warp image using the estimated transformation + >>> image = ski.data.camera() + + >>> ski.transform.warp(image, inverse_map=tform.inverse) # doctest: +SKIP + + >>> # create transformation with explicit parameters + >>> tform2 = ski.transform.SimilarityTransform(scale=1.1, rotation=1, + ... translation=(10, 20)) + + >>> # unite transformations, applied in order from left to right + >>> tform3 = tform + tform2 + >>> np.allclose(tform3(src), tform2(tform(src))) + True + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> # A successfully estimated model is truthy (applying ``bool()`` + >>> # gives ``True``): + >>> if tform: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate transform with identical points. + >>> bad_src = np.ones((2, 2)) + >>> bad_tform = ski.transform.estimate_transform('similarity', + ... bad_src, dst) + >>> if not bad_tform: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tform.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + + """ + ttype = ttype.lower() + if ttype not in TRANSFORMS: + raise ValueError(f'the transformation type \'{ttype}\' is not implemented') + + return TRANSFORMS[ttype].from_estimate(src, dst, *args, **kwargs) + + +def matrix_transform(coords, matrix): + """Apply 2D matrix transform. + + Parameters + ---------- + coords : (N, 2) array_like + x, y coordinates to transform + matrix : (3, 3) array_like + Homogeneous transformation matrix. + + Returns + ------- + coords : (N, 2) array + Transformed coordinates. + + """ + return ProjectiveTransform(matrix)(coords) diff --git a/envs/kitoverlay/skimage/transform/_thin_plate_splines.py b/envs/kitoverlay/skimage/transform/_thin_plate_splines.py new file mode 100644 index 0000000000000000000000000000000000000000..35ca055d6acdfc7f8d62621186003532323960fc --- /dev/null +++ b/envs/kitoverlay/skimage/transform/_thin_plate_splines.py @@ -0,0 +1,251 @@ +from typing import Self + +import numpy as np +from scipy.spatial import distance_matrix + +from .._shared.utils import check_nD, _deprecate_estimate, FailedEstimation + + +class ThinPlateSplineTransform: + """Thin-plate spline transformation. + + Given two matching sets of points, source and destination, this class + estimates the thin-plate spline (TPS) transformation which transforms + each point in source into its destination counterpart. + + Attributes + ---------- + src : (N, 2) array_like + Coordinates of control points in source image. + + References + ---------- + .. [1] Bookstein, Fred L. "Principal warps: Thin-plate splines and the + decomposition of deformations," IEEE Transactions on pattern analysis + and machine intelligence 11.6 (1989): 567–585. + DOI:`10.1109/34.24792` + https://user.engineering.uiowa.edu/~aip/papers/bookstein-89.pdf + + Examples + -------- + >>> import skimage as ski + + Define source and destination control points such that they simulate + rotating by 90 degrees and generate a meshgrid from them: + + >>> src = np.array([[0, 0], [0, 5], [5, 5], [5, 0]]) + >>> dst = np.array([[5, 0], [0, 0], [0, 5], [5, 5]]) + + Estimate the transformation: + + >>> tps = ski.transform.ThinPlateSplineTransform.from_estimate(src, dst) + + Appyling the transformation to `src` approximates `dst`: + + >>> np.round(tps(src), 4) # doctest: +FLOAT_CMP + array([[5., 0.], + [0., 0.], + [0., 5.], + [5., 5.]]) + + Create a meshgrid to apply the transformation to: + + >>> grid = np.meshgrid(np.arange(5), np.arange(5)) + >>> grid[1] + array([[0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4]]) + + >>> coords = np.vstack([grid[0].ravel(), grid[1].ravel()]).T + >>> transformed = tps(coords) + >>> np.round(transformed[:, 1]).reshape(5, 5).astype(int) + array([[0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4]]) + + The estimation can fail - for example, if all the input or output points + are the same. If this happens, you will get a transform that is not + "truthy" - meaning that ``bool(tform)`` is ``False``: + + >>> if tps: + ... print("Estimation succeeded.") + Estimation succeeded. + + Not so for a degenerate transform with identical points. + + >>> bad_src = np.ones((4, 2)) + >>> bad_tps = ski.transform.ThinPlateSplineTransform.from_estimate( + ... bad_src, dst) + >>> if not bad_tps: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_tps.params # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "params" for failed estimation ... + """ + + def __init__(self): + self._estimated = False + self._spline_mappings = None + self.src = None + + def __call__(self, coords): + """Estimate the transformation from a set of corresponding points. + + Parameters + ---------- + coords : (N, 2) array_like + x, y coordinates to transform + + Returns + ------- + transformed_coords: (N, D) array + Destination coordinates + """ + if self._spline_mappings is None: + msg = ( + "Transformation is undefined, define it by calling `estimate` " + "before applying it" + ) + raise ValueError(msg) + coords = np.array(coords) + + if coords.ndim != 2 or coords.shape[1] != 2: + msg = "Input `coords` must have shape (N, 2)" + raise ValueError(msg) + + radial_dist = self._radial_distance(coords) + transformed_coords = self._spline_function(coords, radial_dist) + + return transformed_coords + + @property + def inverse(self): + raise NotImplementedError("Not supported") + + @classmethod + def from_estimate(cls, src, dst) -> Self | FailedEstimation: + """Estimate optimal spline mappings between source and destination points. + + Parameters + ---------- + src : (N, 2) array_like + Control points at source coordinates. + dst : (N, 2) array_like + Control points at destination coordinates. + + Returns + ------- + tform : Self or ``FailedEstimation`` + An instance of the transformation if the estimation succeeded. + Otherwise, we return a special ``FailedEstimation`` object to + signal a failed estimation. Testing the truth value of the failed + estimation object will return ``False``. E.g. + + .. code-block:: python + + tform = ThinPlateSplineTransform.from_estimate(...) + if not tform: + raise RuntimeError(f"Failed estimation: {tf}") + + Notes + ----- + The number N of source and destination points must match. + """ + tf = cls() + msg = tf._estimate(src, dst) + return tf if msg is None else FailedEstimation(f'{cls.__name__}: {msg}') + + def _estimate(self, src, dst): + """Try to estimate and return reason if estimation fails.""" + check_nD(src, 2, arg_name="src") + check_nD(dst, 2, arg_name="dst") + + if src.shape[0] < 3 or dst.shape[0] < 3: + msg = "Need at least 3 points in in `src` and `dst`" + raise ValueError(msg) + if src.shape != dst.shape: + msg = f"Shape of `src` and `dst` didn't match, {src.shape} != {dst.shape}" + raise ValueError(msg) + + self.src = src + n, d = src.shape + + dist = distance_matrix(src, src) + K = self._radial_basis_kernel(dist) + P = np.hstack([np.ones((n, 1)), src]) + n_plus_3 = n + 3 + L = np.zeros((n_plus_3, n_plus_3), dtype=np.float32) + L[:n, :n] = K + L[:n, -3:] = P + L[-3:, :n] = P.T + V = np.vstack([dst, np.zeros((d + 1, d))]) + try: + self._spline_mappings = np.linalg.solve(L, V) + except np.linalg.LinAlgError: + return 'Unable to solve for spline mappings' + return None + + def _radial_distance(self, coords): + """Compute the radial distance between input points and source points.""" + dists = distance_matrix(coords, self.src) + return self._radial_basis_kernel(dists) + + def _spline_function(self, coords, radial_dist): + """Estimate the spline function in X and Y directions.""" + n = self.src.shape[0] + w = self._spline_mappings[:n] + a = self._spline_mappings[n:] + transformed_coords = a[0] + np.dot(coords, a[1:]) + np.dot(radial_dist, w) + return transformed_coords + + @staticmethod + def _radial_basis_kernel(r): + """Compute the radial basis function for thin-plate splines. + + Parameters + ---------- + r : (4, N) ndarray + Input array representing the Euclidean distance between each pair of + two collections of control points. + + Returns + ------- + U : (4, N) ndarray + Calculated kernel function U. + """ + _small = 1e-8 # Small value to avoid divide-by-zero + r_sq = r**2 + U = np.where(r == 0.0, 0.0, r_sq * np.log(r_sq + _small)) + return U + + @_deprecate_estimate + def estimate(self, src, dst): + """Estimate optimal spline mappings between source and destination points. + + Parameters + ---------- + src : (N, 2) array_like + Control points at source coordinates. + dst : (N, 2) array_like + Control points at destination coordinates. + + Returns + ------- + success: bool + True indicates that the estimation was successful. + + Notes + ----- + The number N of source and destination points must match. + """ + return self._estimate(src, dst) is None diff --git a/envs/kitoverlay/skimage/transform/_warps.py b/envs/kitoverlay/skimage/transform/_warps.py new file mode 100644 index 0000000000000000000000000000000000000000..1267e0a550a382a6f049fd9d36ab72eba6010292 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/_warps.py @@ -0,0 +1,1404 @@ +import numpy as np +from scipy import ndimage as ndi + +from ._geometric import SimilarityTransform, AffineTransform, ProjectiveTransform +from ._warps_cy import _warp_fast +from ..measure import block_reduce + +from .._shared.utils import ( + get_bound_method_class, + safe_as_int, + warn, + convert_to_float, + _to_ndimage_mode, + _validate_interpolation_order, + channel_as_last_axis, +) + +HOMOGRAPHY_TRANSFORMS = (SimilarityTransform, AffineTransform, ProjectiveTransform) + + +def _preprocess_resize_output_shape(image, output_shape): + """Validate resize output shape according to input image. + + Parameters + ---------- + image : ndarray + Image to be resized. + output_shape : iterable + Size of the generated output image `(rows, cols[, ...][, dim])`. If + `dim` is not provided, the number of channels is preserved. + + Returns + ------- + image: ndarray + The input image, but with additional singleton dimensions appended in + the case where ``len(output_shape) > input.ndim``. + output_shape: tuple + The output image converted to tuple. + + Raises + ------ + ValueError: + If output_shape length is smaller than the image number of + dimensions + + Notes + ----- + The input image is reshaped if its number of dimensions is not + equal to output_shape_length. + + """ + output_shape = tuple(output_shape) + output_ndim = len(output_shape) + input_shape = image.shape + if output_ndim > image.ndim: + # append dimensions to input_shape + input_shape += (1,) * (output_ndim - image.ndim) + image = np.reshape(image, input_shape) + elif output_ndim == image.ndim - 1: + # multichannel case: append shape of last axis + output_shape = output_shape + (image.shape[-1],) + elif output_ndim < image.ndim: + raise ValueError( + "output_shape length cannot be smaller than the " + "image number of dimensions" + ) + + return image, output_shape + + +def resize( + image, + output_shape, + order=None, + mode='reflect', + cval=0, + clip=True, + preserve_range=False, + anti_aliasing=None, + anti_aliasing_sigma=None, +): + """Resize image to match a certain size. + + Performs interpolation to up-size or down-size N-dimensional images. Note + that anti-aliasing should be enabled when down-sizing images to avoid + aliasing artifacts. For downsampling with an integer factor also see + `skimage.transform.downscale_local_mean`. + + Parameters + ---------- + image : ndarray + Input image. + output_shape : iterable + Size of the generated output image `(rows, cols[, ...][, dim])`. If + `dim` is not provided, the number of channels is preserved. In case the + number of input channels does not equal the number of output channels a + n-dimensional interpolation is applied. + + Returns + ------- + resized : ndarray + Resized version of the input. See Notes regarding dtype. + + Other parameters + ---------------- + order : int, optional + The order of the spline interpolation, default is 0 if + image.dtype is bool and 1 otherwise. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional + Points outside the boundaries of the input are filled according + to the given mode. Modes match the behaviour of `numpy.pad`. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool, optional + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + anti_aliasing : bool, optional + Whether to apply a Gaussian filter to smooth the image prior + to downsampling. It is crucial to filter when downsampling + the image to avoid aliasing artifacts. If not specified, it is set to + True when downsampling an image whose data type is not bool. + It is also set to False when using nearest neighbor interpolation + (``order`` == 0) with integer input data type. + anti_aliasing_sigma : {float, tuple of floats}, optional + Standard deviation for Gaussian filtering used when anti-aliasing. + By default, this value is chosen as (s - 1) / 2 where s is the + downsampling factor, where s > 1. For the up-size case, s < 1, no + anti-aliasing is performed prior to rescaling. + + See Also + -------- + scipy.ndimage.zoom + + Notes + ----- + Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge + pixels are duplicated during the reflection. As an example, if an array + has values [0, 1, 2] and was padded to the right by four values using + symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it + would be [0, 1, 2, 1, 0, 1, 2]. + + `resize` uses interpolation. Unless the interpolation method is nearest-neighbor + (``order==0``), the algorithm will generate output values as weighted averages + of input values. Accordingly, the output dtype is ``float64`` with the following + exceptions: + + - When ``order==0``, the output dtype is ``image.dtype``. + - When ``image.dtype`` is ``float16`` or ``float32``, the output dtype is + ``float32``. + + For a similar function that preserves the dtype of the input, consider + `scipy.ndimage.zoom`. + + Examples + -------- + >>> from skimage import data + >>> from skimage.transform import resize + >>> image = data.camera() + >>> resize(image, (100, 100)).shape + (100, 100) + + """ + + image, output_shape = _preprocess_resize_output_shape(image, output_shape) + input_shape = image.shape + input_type = image.dtype + + if input_type == np.float16: + image = image.astype(np.float32) + + if anti_aliasing is None: + anti_aliasing = ( + not input_type == bool + and not (np.issubdtype(input_type, np.integer) and order == 0) + and any(x < y for x, y in zip(output_shape, input_shape)) + ) + + if input_type == bool and anti_aliasing: + raise ValueError("anti_aliasing must be False for boolean images") + + factors = np.divide(input_shape, output_shape) + order = _validate_interpolation_order(input_type, order) + if order > 0: + image = convert_to_float(image, preserve_range) + + # Translate modes used by np.pad to those used by scipy.ndimage + ndi_mode = _to_ndimage_mode(mode) + if anti_aliasing: + if anti_aliasing_sigma is None: + anti_aliasing_sigma = np.maximum(0, (factors - 1) / 2) + else: + anti_aliasing_sigma = np.atleast_1d(anti_aliasing_sigma) * np.ones_like( + factors + ) + if np.any(anti_aliasing_sigma < 0): + raise ValueError( + "Anti-aliasing standard deviation must be " + "greater than or equal to zero" + ) + elif np.any((anti_aliasing_sigma > 0) & (factors <= 1)): + warn( + "Anti-aliasing standard deviation greater than zero but " + "not down-sampling along all axes" + ) + filtered = ndi.gaussian_filter( + image, anti_aliasing_sigma, cval=cval, mode=ndi_mode + ) + else: + filtered = image + + zoom_factors = [1 / f for f in factors] + out = ndi.zoom( + filtered, zoom_factors, order=order, mode=ndi_mode, cval=cval, grid_mode=True + ) + + _clip_warp_output(image, out, mode, cval, clip) + + return out + + +@channel_as_last_axis() +def rescale( + image, + scale, + order=None, + mode='reflect', + cval=0, + clip=True, + preserve_range=False, + anti_aliasing=None, + anti_aliasing_sigma=None, + *, + channel_axis=None, +): + """Scale image by a certain factor. + + Performs interpolation to up-scale or down-scale N-dimensional images. + Note that anti-aliasing should be enabled when down-sizing images to avoid + aliasing artifacts. For down-sampling with an integer factor also see + `skimage.transform.downscale_local_mean`. + + Parameters + ---------- + image : (M, N[, ...][, C]) ndarray + Input image. + scale : {float, tuple of floats} + Scale factors for spatial dimensions. Separate scale factors can be defined as + (m, n[, ...]). + + Returns + ------- + scaled : ndarray + Scaled version of the input. + + Other parameters + ---------------- + order : int, optional + The order of the spline interpolation, default is 0 if + image.dtype is bool and 1 otherwise. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional + Points outside the boundaries of the input are filled according + to the given mode. Modes match the behaviour of `numpy.pad`. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool, optional + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + anti_aliasing : bool, optional + Whether to apply a Gaussian filter to smooth the image prior + to down-scaling. It is crucial to filter when down-sampling + the image to avoid aliasing artifacts. If input image data + type is bool, no anti-aliasing is applied. + anti_aliasing_sigma : {float, tuple of floats}, optional + Standard deviation for Gaussian filtering to avoid aliasing artifacts. + By default, this value is chosen as (s - 1) / 2 where s is the + down-scaling factor. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Notes + ----- + Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge + pixels are duplicated during the reflection. As an example, if an array + has values [0, 1, 2] and was padded to the right by four values using + symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it + would be [0, 1, 2, 1, 0, 1, 2]. + + Examples + -------- + >>> from skimage import data + >>> from skimage.transform import rescale + >>> image = data.camera() + >>> rescale(image, 0.1).shape + (51, 51) + >>> rescale(image, 0.5).shape + (256, 256) + + """ + scale = np.atleast_1d(scale) + multichannel = channel_axis is not None + if len(scale) > 1: + if (not multichannel and len(scale) != image.ndim) or ( + multichannel and len(scale) != image.ndim - 1 + ): + raise ValueError("Supply a single scale, or one value per spatial " "axis") + if multichannel: + scale = np.concatenate((scale, [1])) + orig_shape = np.asarray(image.shape) + output_shape = np.maximum(np.round(scale * orig_shape), 1) + if multichannel: # don't scale channel dimension + output_shape[-1] = orig_shape[-1] + + return resize( + image, + output_shape, + order=order, + mode=mode, + cval=cval, + clip=clip, + preserve_range=preserve_range, + anti_aliasing=anti_aliasing, + anti_aliasing_sigma=anti_aliasing_sigma, + ) + + +def rotate( + image, + angle, + resize=False, + center=None, + order=None, + mode='constant', + cval=0, + clip=True, + preserve_range=False, +): + """Rotate image by a certain angle around its center. + + Parameters + ---------- + image : ndarray + Input image. + angle : float + Rotation angle in degrees in counter-clockwise direction. + resize : bool, optional + Determine whether the shape of the output image will be automatically + calculated, so the complete rotated image exactly fits. Default is + False. + center : iterable of length 2 + The rotation center. If ``center=None``, the image is rotated around + its center, i.e. ``center=(cols / 2 - 0.5, rows / 2 - 0.5)``. Please + note that this parameter is (cols, rows), contrary to normal skimage + ordering. + + Returns + ------- + rotated : ndarray + Rotated version of the input. + + Other parameters + ---------------- + order : int, optional + The order of the spline interpolation, default is 0 if + image.dtype is bool and 1 otherwise. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional + Points outside the boundaries of the input are filled according + to the given mode. Modes match the behaviour of `numpy.pad`. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool, optional + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + Notes + ----- + Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge + pixels are duplicated during the reflection. As an example, if an array + has values [0, 1, 2] and was padded to the right by four values using + symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it + would be [0, 1, 2, 1, 0, 1, 2]. + + Examples + -------- + >>> from skimage import data + >>> from skimage.transform import rotate + >>> image = data.camera() + >>> rotate(image, 2).shape + (512, 512) + >>> rotate(image, 2, resize=True).shape + (530, 530) + >>> rotate(image, 90, resize=True).shape + (512, 512) + + """ + + rows, cols = image.shape[0], image.shape[1] + + if image.dtype == np.float16: + image = image.astype(np.float32) + + # rotation around center + if center is None: + center = np.array((cols, rows)) / 2.0 - 0.5 + else: + center = np.asarray(center) + tform1 = SimilarityTransform(translation=center) + tform2 = SimilarityTransform(rotation=np.deg2rad(angle)) + tform3 = SimilarityTransform(translation=-center) + tform = tform3 + tform2 + tform1 + + output_shape = None + if resize: + # determine shape of output image + corners = np.array([[0, 0], [0, rows - 1], [cols - 1, rows - 1], [cols - 1, 0]]) + corners = tform.inverse(corners) + minc = corners[:, 0].min() + minr = corners[:, 1].min() + maxc = corners[:, 0].max() + maxr = corners[:, 1].max() + out_rows = maxr - minr + 1 + out_cols = maxc - minc + 1 + output_shape = np.around((out_rows, out_cols)) + + # fit output image in new shape + translation = (minc, minr) + tform4 = SimilarityTransform(translation=translation) + tform = tform4 + tform + + # Make sure the transform is exactly affine, to ensure fast warping. + tform.params[2] = (0, 0, 1) + + return warp( + image, + tform, + output_shape=output_shape, + order=order, + mode=mode, + cval=cval, + clip=clip, + preserve_range=preserve_range, + ) + + +def downscale_local_mean(image, factors, cval=0, clip=True): + """Down-sample N-dimensional image by local averaging. + + The image is padded with `cval` if it is not perfectly divisible by the + integer factors. + + In contrast to interpolation in `skimage.transform.resize` and + `skimage.transform.rescale` this function calculates the local mean of + elements in each block of size `factors` in the input image. + + Parameters + ---------- + image : (M[, ...]) ndarray + Input image. + factors : array_like + Array containing down-sampling integer factor along each axis. + cval : float, optional + Constant padding value if image is not perfectly divisible by the + integer factors. + clip : bool, optional + Unused, but kept here for API consistency with the other transforms + in this module. (The local mean will never fall outside the range + of values in the input image, assuming the provided `cval` also + falls within that range.) + + Returns + ------- + image : ndarray + Down-sampled image with same number of dimensions as input image. + For integer inputs, the output dtype will be ``float64``. + See :func:`numpy.mean` for details. + + Examples + -------- + >>> a = np.arange(15).reshape(3, 5) + >>> a + array([[ 0, 1, 2, 3, 4], + [ 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14]]) + >>> downscale_local_mean(a, (2, 3)) + array([[3.5, 4. ], + [5.5, 4.5]]) + + """ + return block_reduce(image, factors, np.mean, cval) + + +def _swirl_mapping(xy, center, rotation, strength, radius): + x, y = xy.T + x0, y0 = center + rho = np.sqrt((x - x0) ** 2 + (y - y0) ** 2) + + # Ensure that the transformation decays to approximately 1/1000-th + # within the specified radius. + radius = radius / 5 * np.log(2) + + theta = rotation + strength * np.exp(-rho / radius) + np.arctan2(y - y0, x - x0) + + xy[..., 0] = x0 + rho * np.cos(theta) + xy[..., 1] = y0 + rho * np.sin(theta) + + return xy + + +def swirl( + image, + center=None, + strength=1, + radius=100, + rotation=0, + output_shape=None, + order=None, + mode='reflect', + cval=0, + clip=True, + preserve_range=False, +): + """Perform a swirl transformation. + + Parameters + ---------- + image : ndarray + Input image. + center : (column, row) tuple or (2,) ndarray, optional + Center coordinate of transformation. + strength : float, optional + The amount of swirling applied. + radius : float, optional + The extent of the swirl in pixels. The effect dies out + rapidly beyond `radius`. + rotation : float, optional + Additional rotation applied to the image. + + Returns + ------- + swirled : ndarray + Swirled version of the input. + + Other parameters + ---------------- + output_shape : tuple (rows, cols), optional + Shape of the output image generated. By default the shape of the input + image is preserved. + order : int, optional + The order of the spline interpolation, default is 0 if + image.dtype is bool and 1 otherwise. The order has to be in + the range 0-5. See `skimage.transform.warp` for detail. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional + Points outside the boundaries of the input are filled according + to the given mode, with 'reflect' used as the default. Modes match + the behaviour of `numpy.pad`. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool, optional + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + """ + if center is None: + center = np.array(image.shape)[:2][::-1] / 2 + + warp_args = { + 'center': center, + 'rotation': rotation, + 'strength': strength, + 'radius': radius, + } + + return warp( + image, + _swirl_mapping, + map_args=warp_args, + output_shape=output_shape, + order=order, + mode=mode, + cval=cval, + clip=clip, + preserve_range=preserve_range, + ) + + +def _stackcopy(a, b): + """Copy b into each color layer of a, such that:: + + a[:,:,0] = a[:,:,1] = ... = b + + Parameters + ---------- + a : (M, N) or (M, N, P) ndarray + Target array. + b : (M, N) + Source array. + + Notes + ----- + Color images are stored as an ``(M, N, 3)`` or ``(M, N, 4)`` arrays. + + """ + if a.ndim == 3: + a[:] = b[:, :, np.newaxis] + else: + a[:] = b + + +def warp_coords(coord_map, shape, dtype=np.float64): + """Build the source coordinates for the output of a 2-D image warp. + + Parameters + ---------- + coord_map : callable like GeometricTransform.inverse + Return input coordinates for given output coordinates. + Coordinates are in the shape (P, 2), where P is the number + of coordinates and each element is a ``(row, col)`` pair. + shape : tuple + Shape of output image ``(rows, cols[, bands])``. + dtype : np.dtype or string + dtype for return value (sane choices: float32 or float64). + + Returns + ------- + coords : (ndim, rows, cols[, bands]) array of dtype `dtype` + Coordinates for `scipy.ndimage.map_coordinates`, that will yield + an image of shape (orows, ocols, bands) by drawing from source + points according to the `coord_transform_fn`. + + Notes + ----- + + This is a lower-level routine that produces the source coordinates for 2-D + images used by `warp()`. + + It is provided separately from `warp` to give additional flexibility to + users who would like, for example, to re-use a particular coordinate + mapping, to use specific dtypes at various points along the the + image-warping process, or to implement different post-processing logic + than `warp` performs after the call to `ndi.map_coordinates`. + + + Examples + -------- + Produce a coordinate map that shifts an image up and to the right: + + >>> from skimage import data + >>> from scipy.ndimage import map_coordinates + >>> + >>> def shift_up10_left20(xy): + ... return xy - np.array([-20, 10])[None, :] + >>> + >>> image = data.astronaut().astype(np.float32) + >>> coords = warp_coords(shift_up10_left20, image.shape) + >>> warped_image = map_coordinates(image, coords) + + """ + shape = safe_as_int(shape) + rows, cols = shape[0], shape[1] + coords_shape = [len(shape), rows, cols] + if len(shape) == 3: + coords_shape.append(shape[2]) + coords = np.empty(coords_shape, dtype=dtype) + + # Reshape grid coordinates into a (P, 2) array of (row, col) pairs + tf_coords = np.indices((cols, rows), dtype=dtype).reshape(2, -1).T + + # Map each (row, col) pair to the source image according to + # the user-provided mapping + tf_coords = coord_map(tf_coords) + + # Reshape back to a (2, M, N) coordinate grid + tf_coords = tf_coords.T.reshape((-1, cols, rows)).swapaxes(1, 2) + + # Place the y-coordinate mapping + _stackcopy(coords[1, ...], tf_coords[0, ...]) + + # Place the x-coordinate mapping + _stackcopy(coords[0, ...], tf_coords[1, ...]) + + if len(shape) == 3: + coords[2, ...] = range(shape[2]) + + return coords + + +def _clip_warp_output(input_image, output_image, mode, cval, clip): + """Clip output image to range of values of input image. + + Note that this function modifies the values of `output_image` in-place + and it is only modified if ``clip=True``. + + Parameters + ---------- + input_image : ndarray + Input image. + output_image : ndarray + Output image, which is modified in-place. + + Other parameters + ---------------- + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'} + Points outside the boundaries of the input are filled according + to the given mode. Modes match the behaviour of `numpy.pad`. + cval : float + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + + """ + if clip: + min_val = np.min(input_image) + if np.isnan(min_val): + # NaNs detected, use NaN-safe min/max + min_func = np.nanmin + max_func = np.nanmax + min_val = min_func(input_image) + else: + min_func = np.min + max_func = np.max + max_val = max_func(input_image) + + # Check if cval has been used such that it expands the effective input + # range + preserve_cval = ( + mode == 'constant' + and not min_val <= cval <= max_val + and min_func(output_image) <= cval <= max_func(output_image) + ) + + # expand min/max range to account for cval + if preserve_cval: + # cast cval to the same dtype as the input image + cval = input_image.dtype.type(cval) + min_val = min(min_val, cval) + max_val = max(max_val, cval) + + # Convert array-like types to ndarrays (gh-7159) + min_val, max_val = np.asarray(min_val), np.asarray(max_val) + np.clip(output_image, min_val, max_val, out=output_image) + + +def warp( + image, + inverse_map, + map_args=None, + output_shape=None, + order=None, + mode='constant', + cval=0.0, + clip=True, + preserve_range=False, +): + """Warp an image according to a given coordinate transformation. + + Parameters + ---------- + image : ndarray + Input image. + inverse_map : transformation object, callable ``cr = f(cr, **kwargs)``, or ndarray + Inverse coordinate map, which transforms coordinates in the output + images into their corresponding coordinates in the input image. + + There are a number of different options to define this map, depending + on the dimensionality of the input image. A 2-D image can have 2 + dimensions for gray-scale images, or 3 dimensions with color + information. + + - For 2-D images, you can directly pass a transformation object, + e.g. `skimage.transform.SimilarityTransform`, or its inverse. + - For 2-D images, you can pass a ``(3, 3)`` homogeneous + transformation matrix, e.g. + `skimage.transform.SimilarityTransform.params`. + - For 2-D images, a function that transforms a ``(M, 2)`` array of + ``(col, row)`` coordinates in the output image to their + corresponding coordinates in the input image. Extra parameters to + the function can be specified through `map_args`. + - For N-D images, you can directly pass an array of coordinates. + The first dimension specifies the coordinates in the input image, + while the subsequent dimensions determine the position in the + output image. E.g. in case of 2-D images, you need to pass an array + of shape ``(2, rows, cols)``, where `rows` and `cols` determine the + shape of the output image, and the first dimension contains the + ``(row, col)`` coordinate in the input image. + See `scipy.ndimage.map_coordinates` for further documentation. + + Note, that a ``(3, 3)`` matrix is interpreted as a homogeneous + transformation matrix, so you cannot interpolate values from a 3-D + input, if the output is of shape ``(3,)``. + + See example section for usage. + map_args : dict, optional + Keyword arguments passed to `inverse_map`. + output_shape : tuple (rows, cols), optional + Shape of the output image generated. By default the shape of the input + image is preserved. Note that, even for multi-band images, only rows + and columns need to be specified. + order : int, optional + The order of interpolation. The order has to be in the range 0-5: + - 0: Nearest-neighbor + - 1: Bi-linear (default) + - 2: Bi-quadratic + - 3: Bi-cubic + - 4: Bi-quartic + - 5: Bi-quintic + + Default is 0 if image.dtype is bool and 1 otherwise. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional + Points outside the boundaries of the input are filled according + to the given mode. Modes match the behaviour of `numpy.pad`. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + clip : bool, optional + Whether to clip the output to the range of values of the input image. + This is enabled by default, since higher order interpolation may + produce values outside the given input range. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + Returns + ------- + warped : double ndarray + The warped input image. + + Notes + ----- + - The input image is converted to a `double` image. + - In case of a `SimilarityTransform`, `AffineTransform` and + `ProjectiveTransform` and `order` in [0, 3] this function uses the + underlying transformation matrix to warp the image with a much faster + routine. + + Examples + -------- + >>> from skimage.transform import warp + >>> from skimage import data + >>> image = data.camera() + + The following image warps are all equal but differ substantially in + execution time. The image is shifted to the bottom. + + Use a geometric transform to warp an image (fast): + + >>> from skimage.transform import SimilarityTransform + >>> tform = SimilarityTransform(translation=(0, -10)) + >>> warped = warp(image, tform) + + Use a callable (slow): + + >>> def shift_down(xy): + ... xy[:, 1] -= 10 + ... return xy + >>> warped = warp(image, shift_down) + + Use a transformation matrix to warp an image (fast): + + >>> matrix = np.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]]) + >>> warped = warp(image, matrix) + >>> from skimage.transform import ProjectiveTransform + >>> warped = warp(image, ProjectiveTransform(matrix=matrix)) + + You can also use the inverse of a geometric transformation (fast): + + >>> warped = warp(image, tform.inverse) + + For N-D images you can pass a coordinate array, that specifies the + coordinates in the input image for every element in the output image. E.g. + if you want to rescale a 3-D cube, you can do: + + >>> cube_shape = np.array([30, 30, 30]) + >>> rng = np.random.default_rng() + >>> cube = rng.random(cube_shape) + + Setup the coordinate array, that defines the scaling: + + >>> scale = 0.1 + >>> output_shape = (scale * cube_shape).astype(int) + >>> coords0, coords1, coords2 = np.mgrid[:output_shape[0], + ... :output_shape[1], :output_shape[2]] + >>> coords = np.array([coords0, coords1, coords2]) + + Assume that the cube contains spatial data, where the first array element + center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to + account for this extra offset when scaling the image: + + >>> coords = (coords + 0.5) / scale - 0.5 + >>> warped = warp(cube, coords) + + """ + if map_args is None: + map_args = {} + + if image.size == 0: + raise ValueError("Cannot warp empty image with dimensions", image.shape) + + order = _validate_interpolation_order(image.dtype, order) + + if order > 0: + image = convert_to_float(image, preserve_range) + if image.dtype == np.float16: + image = image.astype(np.float32) + + input_shape = np.array(image.shape) + + if output_shape is None: + output_shape = input_shape + else: + output_shape = safe_as_int(output_shape) + + warped = None + + if order == 2: + # When fixing this issue, make sure to fix the branches further + # below in this function + warn( + "Bi-quadratic interpolation behavior has changed due " + "to a bug in the implementation of scikit-image. " + "The new version now serves as a wrapper " + "around SciPy's interpolation functions, which itself " + "is not verified to be a correct implementation. Until " + "skimage's implementation is fixed, we recommend " + "to use bi-linear or bi-cubic interpolation instead." + ) + + if order in (1, 3) and not map_args: + # use fast Cython version for specific interpolation orders and input + + matrix = None + + if isinstance(inverse_map, np.ndarray) and inverse_map.shape == (3, 3): + # inverse_map is a transformation matrix as numpy array + matrix = inverse_map + + elif isinstance(inverse_map, HOMOGRAPHY_TRANSFORMS): + # inverse_map is a homography + matrix = inverse_map.params + + elif ( + hasattr(inverse_map, '__name__') + and inverse_map.__name__ == 'inverse' + and get_bound_method_class(inverse_map) in HOMOGRAPHY_TRANSFORMS + ): + # inverse_map is the inverse of a homography + matrix = np.linalg.inv(inverse_map.__self__.params) + + if matrix is not None: + matrix = matrix.astype(image.dtype) + ctype = 'float32_t' if image.dtype == np.float32 else 'float64_t' + if image.ndim == 2: + warped = _warp_fast[ctype]( + image, + matrix, + output_shape=output_shape, + order=order, + mode=mode, + cval=cval, + ) + elif image.ndim == 3: + dims = [] + for dim in range(image.shape[2]): + dims.append( + _warp_fast[ctype]( + image[..., dim], + matrix, + output_shape=output_shape, + order=order, + mode=mode, + cval=cval, + ) + ) + warped = np.dstack(dims) + + if warped is None: + # use ndi.map_coordinates + + if isinstance(inverse_map, np.ndarray) and inverse_map.shape == (3, 3): + # inverse_map is a transformation matrix as numpy array, + # this is only used for order >= 4. + inverse_map = ProjectiveTransform(matrix=inverse_map) + + if isinstance(inverse_map, np.ndarray): + # inverse_map is directly given as coordinates + coords = inverse_map + else: + # inverse_map is given as function, that transforms (N, 2) + # destination coordinates to their corresponding source + # coordinates. This is only supported for 2(+1)-D images. + + if image.ndim < 2 or image.ndim > 3: + raise ValueError( + "Only 2-D images (grayscale or color) are " + "supported, when providing a callable " + "`inverse_map`." + ) + + def coord_map(*args): + return inverse_map(*args, **map_args) + + if len(input_shape) == 3 and len(output_shape) == 2: + # Input image is 2D and has color channel, but output_shape is + # given for 2-D images. Automatically add the color channel + # dimensionality. + output_shape = (output_shape[0], output_shape[1], input_shape[2]) + + coords = warp_coords(coord_map, output_shape) + + # Pre-filtering not necessary for order 0, 1 interpolation + prefilter = order > 1 + + ndi_mode = _to_ndimage_mode(mode) + warped = ndi.map_coordinates( + image, coords, prefilter=prefilter, mode=ndi_mode, order=order, cval=cval + ) + + _clip_warp_output(image, warped, mode, cval, clip) + + return warped + + +def _linear_polar_mapping(output_coords, k_angle, k_radius, center): + """Inverse mapping function to convert from cartesian to polar coordinates + + Parameters + ---------- + output_coords : (M, 2) ndarray + Array of `(col, row)` coordinates in the output image. + k_angle : float + Scaling factor that relates the intended number of rows in the output + image to angle: ``k_angle = nrows / (2 * np.pi)``. + k_radius : float + Scaling factor that relates the radius of the circle bounding the + area to be transformed to the intended number of columns in the output + image: ``k_radius = ncols / radius``. + center : tuple (row, col) + Coordinates that represent the center of the circle that bounds the + area to be transformed in an input image. + + Returns + ------- + coords : (M, 2) ndarray + Array of `(col, row)` coordinates in the input image that + correspond to the `output_coords` given as input. + """ + angle = output_coords[:, 1] / k_angle + rr = ((output_coords[:, 0] / k_radius) * np.sin(angle)) + center[0] + cc = ((output_coords[:, 0] / k_radius) * np.cos(angle)) + center[1] + coords = np.column_stack((cc, rr)) + return coords + + +def _log_polar_mapping(output_coords, k_angle, k_radius, center): + """Inverse mapping function to convert from cartesian to polar coordinates + + Parameters + ---------- + output_coords : (M, 2) ndarray + Array of `(col, row)` coordinates in the output image. + k_angle : float + Scaling factor that relates the intended number of rows in the output + image to angle: ``k_angle = nrows / (2 * np.pi)``. + k_radius : float + Scaling factor that relates the radius of the circle bounding the + area to be transformed to the intended number of columns in the output + image: ``k_radius = width / np.log(radius)``. + center : 2-tuple + `(row, col)` coordinates that represent the center of the circle that bounds the + area to be transformed in an input image. + + Returns + ------- + coords : ndarray, shape (M, 2) + Array of `(col, row)` coordinates in the input image that + correspond to the `output_coords` given as input. + """ + angle = output_coords[:, 1] / k_angle + rr = ((np.exp(output_coords[:, 0] / k_radius)) * np.sin(angle)) + center[0] + cc = ((np.exp(output_coords[:, 0] / k_radius)) * np.cos(angle)) + center[1] + coords = np.column_stack((cc, rr)) + return coords + + +@channel_as_last_axis() +def warp_polar( + image, + center=None, + *, + radius=None, + output_shape=None, + scaling='linear', + channel_axis=None, + **kwargs, +): + """Remap image to polar or log-polar coordinates space. + + Parameters + ---------- + image : (M, N[, C]) ndarray + Input image. For multichannel images `channel_axis` has to be specified. + center : 2-tuple, optional + `(row, col)` coordinates of the point in `image` that represents the center of + the transformation (i.e., the origin in Cartesian space). Values can be of + type `float`. If no value is given, the center is assumed to be the center point + of `image`. + radius : float, optional + Radius of the circle that bounds the area to be transformed. + output_shape : tuple (row, col), optional + scaling : {'linear', 'log'}, optional + Specify whether the image warp is polar or log-polar. Defaults to + 'linear'. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + **kwargs : keyword arguments + Passed to `transform.warp`. + + Returns + ------- + warped : ndarray + The polar or log-polar warped image. + + Examples + -------- + Perform a basic polar warp on a grayscale image: + + >>> from skimage import data + >>> from skimage.transform import warp_polar + >>> image = data.checkerboard() + >>> warped = warp_polar(image) + + Perform a log-polar warp on a grayscale image: + + >>> warped = warp_polar(image, scaling='log') + + Perform a log-polar warp on a grayscale image while specifying center, + radius, and output shape: + + >>> warped = warp_polar(image, (100,100), radius=100, + ... output_shape=image.shape, scaling='log') + + Perform a log-polar warp on a color image: + + >>> image = data.astronaut() + >>> warped = warp_polar(image, scaling='log', channel_axis=-1) + """ + multichannel = channel_axis is not None + if image.ndim != 2 and not multichannel: + raise ValueError( + f'Input array must be 2-dimensional when ' + f'`channel_axis=None`, got {image.ndim}' + ) + + if image.ndim != 3 and multichannel: + raise ValueError( + f'Input array must be 3-dimensional when ' + f'`channel_axis` is specified, got {image.ndim}' + ) + + if center is None: + center = (np.array(image.shape)[:2] / 2) - 0.5 + + if radius is None: + w, h = np.array(image.shape)[:2] / 2 + radius = np.sqrt(w**2 + h**2) + + if output_shape is None: + height = 360 + width = int(np.ceil(radius)) + output_shape = (height, width) + else: + output_shape = safe_as_int(output_shape) + height = output_shape[0] + width = output_shape[1] + + if scaling == 'linear': + k_radius = width / radius + map_func = _linear_polar_mapping + elif scaling == 'log': + k_radius = width / np.log(radius) + map_func = _log_polar_mapping + else: + raise ValueError("Scaling value must be in {'linear', 'log'}") + + k_angle = height / (2 * np.pi) + warp_args = {'k_angle': k_angle, 'k_radius': k_radius, 'center': center} + + warped = warp( + image, map_func, map_args=warp_args, output_shape=output_shape, **kwargs + ) + + return warped + + +def _local_mean_weights(old_size, new_size, grid_mode, dtype): + """Create a 2D weight matrix for resizing with the local mean. + + Parameters + ---------- + old_size : int + Old size. + new_size : int + New size. + grid_mode : bool + Whether to use grid data model of pixel/voxel model for + average weights computation. + dtype : dtype + Output array data type. + + Returns + ------- + weights: (new_size, old_size) array + Rows sum to 1. + + """ + if grid_mode: + old_breaks = np.linspace(0, old_size, num=old_size + 1, dtype=dtype) + new_breaks = np.linspace(0, old_size, num=new_size + 1, dtype=dtype) + else: + old, new = old_size - 1, new_size - 1 + old_breaks = np.pad( + np.linspace(0.5, old - 0.5, old, dtype=dtype), + 1, + 'constant', + constant_values=(0, old), + ) + if new == 0: + val = np.inf + else: + val = 0.5 * old / new + new_breaks = np.pad( + np.linspace(val, old - val, new, dtype=dtype), + 1, + 'constant', + constant_values=(0, old), + ) + + upper = np.minimum(new_breaks[1:, np.newaxis], old_breaks[np.newaxis, 1:]) + lower = np.maximum(new_breaks[:-1, np.newaxis], old_breaks[np.newaxis, :-1]) + + weights = np.maximum(upper - lower, 0) + weights /= weights.sum(axis=1, keepdims=True) + + return weights + + +def resize_local_mean( + image, output_shape, grid_mode=True, preserve_range=False, *, channel_axis=None +): + """Resize an array with the local mean / bilinear scaling. + + Parameters + ---------- + image : ndarray + Input image. If this is a multichannel image, the axis corresponding + to channels should be specified using `channel_axis`. + output_shape : iterable + Size of the generated output image. When `channel_axis` is not None, + the `channel_axis` should either be omitted from `output_shape` or the + ``output_shape[channel_axis]`` must match + ``image.shape[channel_axis]``. If the length of `output_shape` exceeds + image.ndim, additional singleton dimensions will be appended to the + input ``image`` as needed. + grid_mode : bool, optional + Defines ``image`` pixels position: if True, pixels are assumed to be at + grid intersections, otherwise at cell centers. As a consequence, + for example, a 1d signal of length 5 is considered to have length 4 + when `grid_mode` is False, but length 5 when `grid_mode` is True. See + the following visual illustration: + + .. code-block:: text + + | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 | + |<-------------------------------------->| + vs. + |<----------------------------------------------->| + + The starting point of the arrow in the diagram above corresponds to + coordinate location 0 in each mode. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see + https://scikit-image.org/docs/dev/user_guide/data_types.html + + Returns + ------- + resized : ndarray + Resized version of the input. + + See Also + -------- + resize, downscale_local_mean + + Notes + ----- + This method is sometimes referred to as "area-based" interpolation or + "pixel mixing" interpolation [1]_. When `grid_mode` is True, it is + equivalent to using OpenCV's resize with `INTER_AREA` interpolation mode. + It is commonly used for image downsizing. If the downsizing factors are + integers, then `downscale_local_mean` should be preferred instead. + + References + ---------- + .. [1] http://entropymine.com/imageworsener/pixelmixing/ + + Examples + -------- + >>> from skimage import data + >>> from skimage.transform import resize_local_mean + >>> image = data.camera() + >>> resize_local_mean(image, (100, 100)).shape + (100, 100) + + """ + if channel_axis is not None: + if channel_axis < -image.ndim or channel_axis >= image.ndim: + raise ValueError("invalid channel_axis") + + # move channels to last position + image = np.moveaxis(image, channel_axis, -1) + nc = image.shape[-1] + + output_ndim = len(output_shape) + if output_ndim == image.ndim - 1: + # insert channels dimension at the end + output_shape = output_shape + (nc,) + elif output_ndim == image.ndim: + if output_shape[channel_axis] != nc: + raise ValueError( + "Cannot reshape along the channel_axis. Use " + "channel_axis=None to reshape along all axes." + ) + # move channels to last position in output_shape + channel_axis = channel_axis % image.ndim + output_shape = ( + output_shape[:channel_axis] + output_shape[channel_axis:] + (nc,) + ) + else: + raise ValueError( + "len(output_shape) must be image.ndim or (image.ndim - 1) " + "when a channel_axis is specified." + ) + resized = image + else: + resized, output_shape = _preprocess_resize_output_shape(image, output_shape) + resized = convert_to_float(resized, preserve_range) + dtype = resized.dtype + + for axis, (old_size, new_size) in enumerate(zip(image.shape, output_shape)): + if old_size == new_size: + continue + weights = _local_mean_weights(old_size, new_size, grid_mode, dtype) + product = np.tensordot(resized, weights, [[axis], [-1]]) + resized = np.moveaxis(product, -1, axis) + + if channel_axis is not None: + # restore channels to original axis + resized = np.moveaxis(resized, -1, channel_axis) + + return resized diff --git a/envs/kitoverlay/skimage/transform/finite_radon_transform.py b/envs/kitoverlay/skimage/transform/finite_radon_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..a04a0bad568e45abad2082ff049fdac994023b00 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/finite_radon_transform.py @@ -0,0 +1,132 @@ +""" +:author: Gary Ruben, 2009 +:license: modified BSD +""" + +__all__ = ["frt2", "ifrt2"] + +import numpy as np +from numpy import roll, newaxis + + +def frt2(a): + """Compute the 2-dimensional finite Radon transform (FRT) for the input array. + + Parameters + ---------- + a : ndarray of int, shape (M, M) + Input array. + + Returns + ------- + FRT : ndarray of int, shape (M+1, M) + Finite Radon Transform array of coefficients. + + See Also + -------- + ifrt2 : The two-dimensional inverse FRT. + + Notes + ----- + The FRT has a unique inverse if and only if M is prime. [FRT] + The idea for this algorithm is due to Vlad Negnevitski. + + Examples + -------- + + Generate a test image: + Use a prime number for the array dimensions + + >>> SIZE = 59 + >>> img = np.tri(SIZE, dtype=np.int32) + + Apply the Finite Radon Transform: + + >>> f = frt2(img) + + References + ---------- + .. [FRT] A. Kingston and I. Svalbe, "Projective transforms on periodic + discrete image arrays," in P. Hawkes (Ed), Advances in Imaging + and Electron Physics, 139 (2006) + + """ + if a.ndim != 2 or a.shape[0] != a.shape[1]: + raise ValueError("Input must be a square, 2-D array") + + ai = a.copy() + n = ai.shape[0] + f = np.empty((n + 1, n), np.uint32) + f[0] = ai.sum(axis=0) + for m in range(1, n): + # Roll the pth row of ai left by p places + for row in range(1, n): + ai[row] = roll(ai[row], -row) + f[m] = ai.sum(axis=0) + f[n] = ai.sum(axis=1) + return f + + +def ifrt2(a): + """Compute the 2-dimensional inverse finite Radon transform (iFRT) for the input array. + + Parameters + ---------- + a : ndarray of int, shape (M+1, M) + Input array. + + Returns + ------- + iFRT : ndarray of int, shape (M, M) + Inverse Finite Radon Transform coefficients. + + See Also + -------- + frt2 : The two-dimensional FRT + + Notes + ----- + The FRT has a unique inverse if and only if M is prime. + See [1]_ for an overview. + The idea for this algorithm is due to Vlad Negnevitski. + + Examples + -------- + + >>> SIZE = 59 + >>> img = np.tri(SIZE, dtype=np.int32) + + Apply the Finite Radon Transform: + + >>> f = frt2(img) + + Apply the Inverse Finite Radon Transform to recover the input + + >>> fi = ifrt2(f) + + Check that it's identical to the original + + >>> assert len(np.nonzero(img-fi)[0]) == 0 + + References + ---------- + .. [1] A. Kingston and I. Svalbe, "Projective transforms on periodic + discrete image arrays," in P. Hawkes (Ed), Advances in Imaging + and Electron Physics, 139 (2006) + + """ + if a.ndim != 2 or a.shape[0] != a.shape[1] + 1: + raise ValueError("Input must be an (n+1) row x n column, 2-D array") + + ai = a.copy()[:-1] + n = ai.shape[1] + f = np.empty((n, n), np.uint32) + f[0] = ai.sum(axis=0) + for m in range(1, n): + # Rolls the pth row of ai right by p places. + for row in range(1, ai.shape[0]): + ai[row] = roll(ai[row], row) + f[m] = ai.sum(axis=0) + f += a[-1][newaxis].T + f = (f - ai[0].sum()) / n + return f diff --git a/envs/kitoverlay/skimage/transform/hough_transform.py b/envs/kitoverlay/skimage/transform/hough_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..42d10698a137f64f1dcaf3f433a064652bd598ba --- /dev/null +++ b/envs/kitoverlay/skimage/transform/hough_transform.py @@ -0,0 +1,473 @@ +import numpy as np +from scipy.spatial import cKDTree + +from ._hough_transform import _hough_circle, _hough_ellipse, _hough_line +from ._hough_transform import _probabilistic_hough_line as _prob_hough_line + + +def hough_line_peaks( + hspace, + angles, + dists, + min_distance=9, + min_angle=10, + threshold=None, + num_peaks=np.inf, +): + """Return peaks in a straight line Hough transform. + + Identifies most prominent lines separated by a certain angle and distance + in a Hough transform. Non-maximum suppression with different sizes is + applied separately in the first (distances) and second (angles) dimension + of the Hough space to identify peaks. + + Parameters + ---------- + hspace : ndarray, shape (M, N) + Hough space returned by the `hough_line` function. + angles : array, shape (N,) + Angles returned by the `hough_line` function. Assumed to be continuous. + (`angles[-1] - angles[0] == PI`). + dists : array, shape (M,) + Distances returned by the `hough_line` function. + min_distance : int, optional + Minimum distance separating lines (maximum filter size for first + dimension of hough space). + min_angle : int, optional + Minimum angle separating lines (maximum filter size for second + dimension of hough space). + threshold : float, optional + Minimum intensity of peaks. Default is `0.5 * max(hspace)`. + num_peaks : int, optional + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` coordinates based on peak intensity. + + Returns + ------- + accum, angles, dists : tuple of array + Peak values in Hough space, angles and distances. + + Examples + -------- + >>> from skimage.transform import hough_line, hough_line_peaks + >>> from skimage.draw import line + >>> img = np.zeros((15, 15), dtype=bool) + >>> rr, cc = line(0, 0, 14, 14) + >>> img[rr, cc] = 1 + >>> rr, cc = line(0, 14, 14, 0) + >>> img[cc, rr] = 1 + >>> hspace, angles, dists = hough_line(img) + >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) + >>> len(angles) + 2 + + """ + from ..feature.peak import _prominent_peaks + + min_angle = min(min_angle, hspace.shape[1]) + h, a, d = _prominent_peaks( + hspace, + min_xdistance=min_angle, + min_ydistance=min_distance, + threshold=threshold, + num_peaks=num_peaks, + ) + if a.size > 0: + return (h, angles[a], dists[d]) + else: + return (h, np.array([]), np.array([])) + + +def hough_circle(image, radius, normalize=True, full_output=False): + """Perform a circular Hough transform. + + Parameters + ---------- + image : ndarray, shape (M, N) + Input image with nonzero values representing edges. + radius : scalar or sequence of scalars + Radii at which to compute the Hough transform. + Floats are converted to integers. + normalize : bool, optional + Normalize the accumulator with the number + of pixels used to draw the radius. + full_output : bool, optional + Extend the output size by twice the largest + radius in order to detect centers outside the + input picture. + + Returns + ------- + H : ndarray, shape (radius index, M + 2R, N + 2R) + Hough transform accumulator for each radius. + R designates the larger radius if full_output is True. + Otherwise, R = 0. + + Examples + -------- + >>> from skimage.transform import hough_circle + >>> from skimage.draw import circle_perimeter + >>> img = np.zeros((100, 100), dtype=bool) + >>> rr, cc = circle_perimeter(25, 35, 23) + >>> img[rr, cc] = 1 + >>> try_radii = np.arange(5, 50) + >>> res = hough_circle(img, try_radii) + >>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape) + >>> r, c, try_radii[ridx] + (25, 35, 23) + + """ + radius = np.atleast_1d(np.asarray(radius)) + return _hough_circle( + image, radius.astype(np.intp), normalize=normalize, full_output=full_output + ) + + +def hough_ellipse(image, threshold=4, accuracy=1, min_size=4, max_size=None): + """Perform an elliptical Hough transform. + + Parameters + ---------- + image : (M, N) ndarray + Input image with nonzero values representing edges. + threshold : int, optional + Accumulator threshold value. A lower value will return more ellipses. + accuracy : double, optional + Bin size on the minor axis used in the accumulator. A higher value + will return more ellipses, but lead to a less precise estimation of + the minor axis lengths. + min_size : int, optional + Minimal major axis length. + max_size : int, optional + Maximal minor axis length. + If None, the value is set to half of the smaller + image dimension. + + Returns + ------- + result : ndarray with fields [(accumulator, yc, xc, a, b, orientation)]. + Where ``(yc, xc)`` is the center, ``(a, b)`` the major and minor + axes, respectively. The `orientation` value follows the + `skimage.draw.ellipse_perimeter` convention. + + Examples + -------- + >>> from skimage.transform import hough_ellipse + >>> from skimage.draw import ellipse_perimeter + >>> img = np.zeros((25, 25), dtype=np.uint8) + >>> rr, cc = ellipse_perimeter(10, 10, 6, 8) + >>> img[cc, rr] = 1 + >>> result = hough_ellipse(img, threshold=8) + >>> result.tolist() + [(10, 10.0, 10.0, 8.0, 6.0, 0.0)] + + Notes + ----- + Potential ellipses in the image are characterized by their major and + minor axis lengths. For any pair of nonzero pixels in the image that + are at least half of `min_size` apart, an accumulator keeps track of + the minor axis lengths of potential ellipses formed with all the + other nonzero pixels. If any bin (with `bin_size = accuracy * accuracy`) + in the histogram of those accumulated minor axis lengths is above + `threshold`, the corresponding ellipse is added to the results. + + A higher `accuracy` will therefore lead to more ellipses being found + in the image, at the cost of a less precise estimation of the minor + axis length. + + References + ---------- + .. [1] Xie, Yonghong, and Qiang Ji. "A new efficient ellipse detection + method." Pattern Recognition, 2002. Proceedings. 16th International + Conference on. Vol. 2. IEEE, 2002 + """ + return _hough_ellipse( + image, + threshold=threshold, + accuracy=accuracy, + min_size=min_size, + max_size=max_size, + ) + + +def hough_line(image, theta=None): + """Perform a straight line Hough transform. + + Parameters + ---------- + image : (M, N) ndarray + Input image with nonzero values representing edges. + theta : ndarray of double, shape (K,), optional + Angles at which to compute the transform, in radians. + Defaults to a vector of 180 angles evenly spaced in the + range [-pi/2, pi/2). + + Returns + ------- + hspace : ndarray of uint64, shape (P, Q) + Hough transform accumulator. + angles : ndarray + Angles at which the transform is computed, in radians. + distances : ndarray + Distance values. + + Notes + ----- + The origin is the top left corner of the original image. + X and Y axis are horizontal and vertical edges respectively. + The distance is the minimal algebraic distance from the origin + to the detected line. + The angle accuracy can be improved by decreasing the step size in + the `theta` array. + + Examples + -------- + Generate a test image: + + >>> img = np.zeros((100, 150), dtype=bool) + >>> img[30, :] = 1 + >>> img[:, 65] = 1 + >>> img[35:45, 35:50] = 1 + >>> for i in range(90): + ... img[i, i] = 1 + >>> rng = np.random.default_rng() + >>> img += rng.random(img.shape) > 0.95 + + Apply the Hough transform: + + >>> out, angles, d = hough_line(img) + """ + if image.ndim != 2: + raise ValueError('The input image `image` must be 2D.') + + if theta is None: + # These values are approximations of pi/2 + theta = np.linspace(-np.pi / 2, np.pi / 2, 180, endpoint=False) + + return _hough_line(image, theta=theta) + + +def probabilistic_hough_line( + image, threshold=10, line_length=50, line_gap=10, theta=None, rng=None +): + """Return lines from a progressive probabilistic line Hough transform. + + Parameters + ---------- + image : ndarray, shape (M, N) + Input image with nonzero values representing edges. + threshold : int, optional + Threshold + line_length : int, optional + Minimum accepted length of detected lines. + Increase the parameter to extract longer lines. + line_gap : int, optional + Maximum gap between pixels to still form a line. + Increase the parameter to merge broken lines more aggressively. + theta : ndarray of dtype, shape (K,), optional + Angles at which to compute the transform, in radians. + Defaults to a vector of 180 angles evenly spaced in the + range [-pi/2, pi/2). + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + Returns + ------- + lines : list + List of lines identified, lines in format ((x0, y0), (x1, y1)), + indicating line start and end. + + References + ---------- + .. [1] C. Galamhos, J. Matas and J. Kittler, "Progressive probabilistic + Hough transform for line detection", in IEEE Computer Society + Conference on Computer Vision and Pattern Recognition, 1999. + """ + + if image.ndim != 2: + raise ValueError('The input image `image` must be 2D.') + + if theta is None: + theta = np.linspace(-np.pi / 2, np.pi / 2, 180, endpoint=False) + + return _prob_hough_line( + image, + threshold=threshold, + line_length=line_length, + line_gap=line_gap, + theta=theta, + rng=rng, + ) + + +def hough_circle_peaks( + hspaces, + radii, + min_xdistance=1, + min_ydistance=1, + threshold=None, + num_peaks=np.inf, + total_num_peaks=np.inf, + normalize=False, +): + """Return peaks in a circle Hough transform. + + Identifies most prominent circles separated by certain distances in given + Hough spaces. Non-maximum suppression with different sizes is applied + separately in the first and second dimension of the Hough space to + identify peaks. For circles with different radius but close in distance, + only the one with highest peak is kept. + + Parameters + ---------- + hspaces : (M, N, P) array + Hough spaces returned by the `hough_circle` function. + radii : (M,) array + Radii corresponding to Hough spaces. + min_xdistance : int, optional + Minimum distance separating centers in the x dimension. + min_ydistance : int, optional + Minimum distance separating centers in the y dimension. + threshold : float, optional + Minimum intensity of peaks in each Hough space. + Default is `0.5 * max(hspace)`. + num_peaks : int, optional + Maximum number of peaks in each Hough space. When the + number of peaks exceeds `num_peaks`, only `num_peaks` + coordinates based on peak intensity are considered for the + corresponding radius. + total_num_peaks : int, optional + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` coordinates based on peak intensity. + normalize : bool, optional + If True, normalize the accumulator by the radius to sort the prominent + peaks. + + Returns + ------- + accum, cx, cy, rad : tuple of array + Peak values in Hough space, x and y center coordinates and radii. + + Examples + -------- + >>> from skimage import transform, draw + >>> img = np.zeros((120, 100), dtype=int) + >>> radius, x_0, y_0 = (20, 99, 50) + >>> y, x = draw.circle_perimeter(y_0, x_0, radius) + >>> img[x, y] = 1 + >>> hspaces = transform.hough_circle(img, radius) + >>> accum, cx, cy, rad = hough_circle_peaks(hspaces, [radius,]) + + Notes + ----- + Circles with bigger radius have higher peaks in Hough space. If larger + circles are preferred over smaller ones, `normalize` should be False. + Otherwise, circles will be returned in the order of decreasing voting + number. + """ + from ..feature.peak import _prominent_peaks + + r = [] + cx = [] + cy = [] + accum = [] + + for rad, hp in zip(radii, hspaces): + h_p, x_p, y_p = _prominent_peaks( + hp, + min_xdistance=min_xdistance, + min_ydistance=min_ydistance, + threshold=threshold, + num_peaks=num_peaks, + ) + r.extend((rad,) * len(h_p)) + cx.extend(x_p) + cy.extend(y_p) + accum.extend(h_p) + + r = np.array(r) + cx = np.array(cx) + cy = np.array(cy) + accum = np.array(accum) + if normalize: + s = np.argsort(accum / r) + else: + s = np.argsort(accum) + accum_sorted, cx_sorted, cy_sorted, r_sorted = ( + accum[s][::-1], + cx[s][::-1], + cy[s][::-1], + r[s][::-1], + ) + + tnp = len(accum_sorted) if total_num_peaks == np.inf else total_num_peaks + + # Skip searching for neighboring circles + # if default min_xdistance and min_ydistance are used + # or if no peak was detected + if (min_xdistance == 1 and min_ydistance == 1) or len(accum_sorted) == 0: + return (accum_sorted[:tnp], cx_sorted[:tnp], cy_sorted[:tnp], r_sorted[:tnp]) + + # For circles with centers too close, only keep the one with + # the highest peak + should_keep = label_distant_points( + cx_sorted, cy_sorted, min_xdistance, min_ydistance, tnp + ) + return ( + accum_sorted[should_keep], + cx_sorted[should_keep], + cy_sorted[should_keep], + r_sorted[should_keep], + ) + + +def label_distant_points(xs, ys, min_xdistance, min_ydistance, max_points): + """Keep points that are separated by certain distance in each dimension. + + The first point is always accepted and all subsequent points are selected + so that they are distant from all their preceding ones. + + Parameters + ---------- + xs : array, shape (M,) + X coordinates of points. + ys : array, shape (M,) + Y coordinates of points. + min_xdistance : int + Minimum distance separating points in the x dimension. + min_ydistance : int + Minimum distance separating points in the y dimension. + max_points : int + Max number of distant points to keep. + + Returns + ------- + should_keep : array of bool + A mask array for distant points to keep. + """ + is_neighbor = np.zeros(len(xs), dtype=bool) + coordinates = np.stack([xs, ys], axis=1) + # Use a KDTree to search for neighboring points effectively + kd_tree = cKDTree(coordinates) + n_pts = 0 + for i in range(len(xs)): + if n_pts >= max_points: + # Ignore the point if points to keep reaches maximum + is_neighbor[i] = True + elif not is_neighbor[i]: + # Find a short list of candidates to remove + # by searching within a circle + neighbors_i = kd_tree.query_ball_point( + (xs[i], ys[i]), np.hypot(min_xdistance, min_ydistance) + ) + # Check distance in both dimensions and mark if close + for ni in neighbors_i: + x_close = abs(xs[ni] - xs[i]) <= min_xdistance + y_close = abs(ys[ni] - ys[i]) <= min_ydistance + if x_close and y_close and ni > i: + is_neighbor[ni] = True + n_pts += 1 + should_keep = ~is_neighbor + return should_keep diff --git a/envs/kitoverlay/skimage/transform/integral.py b/envs/kitoverlay/skimage/transform/integral.py new file mode 100644 index 0000000000000000000000000000000000000000..532b56b1ec64225497e9152d3a544cd644f04941 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/integral.py @@ -0,0 +1,149 @@ +import numpy as np + + +def integral_image(image, *, dtype=None): + r"""Integral image / summed area table. + + The integral image contains the sum of all elements above and to the + left of it, i.e.: + + .. math:: + + S[m, n] = \sum_{i \leq m} \sum_{j \leq n} X[i, j] + + Parameters + ---------- + image : ndarray + Input image. + dtype : data-type, optional + Data type (NumPy dtype) to be used for calculation, and for + output array `S`. If None, defaults to the more precise of either + float64 or `image`'s dtype. + + Returns + ------- + S : ndarray + Integral image/summed area table of same shape as input image. + + Notes + ----- + For better accuracy and to avoid potential overflow, the data type of the + output may differ from the input's when the default dtype of None is used. + For inputs with integer dtype, the behavior matches that for + :func:`numpy.cumsum`. Floating point inputs will be promoted to at least + double precision. The user can set `dtype` to override this behavior. + + References + ---------- + .. [1] F.C. Crow, "Summed-area tables for texture mapping," + ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212. + + """ + if dtype is None and image.real.dtype.kind == 'f': + # default to at least double precision cumsum for accuracy + dtype = np.promote_types(image.dtype, np.float64) + + S = image + for i in range(image.ndim): + S = S.cumsum(axis=i, dtype=dtype) + return S + + +def integrate(ii, start, end): + """Use an integral image to integrate over a given window. + + Parameters + ---------- + ii : ndarray + Integral image. + start : List of tuples, each tuple of length equal to dimension of `ii` + Coordinates of top left corner of window(s). + Each tuple in the list contains the starting row, col, ... index + i.e `[(row_win1, col_win1, ...), (row_win2, col_win2,...), ...]`. + end : List of tuples, each tuple of length equal to dimension of `ii` + Coordinates of bottom right corner of window(s). + Each tuple in the list containing the end row, col, ... index i.e + `[(row_win1, col_win1, ...), (row_win2, col_win2, ...), ...]`. + + Returns + ------- + S : scalar or ndarray + Integral (sum) over the given window(s). + + See Also + -------- + integral_image : Create an integral image / summed area table. + + Examples + -------- + >>> arr = np.ones((5, 6), dtype=float) + >>> ii = integral_image(arr) + >>> integrate(ii, (1, 0), (1, 2)) # sum from (1, 0) to (1, 2) + array([3.]) + >>> integrate(ii, [(3, 3)], [(4, 5)]) # sum from (3, 3) to (4, 5) + array([6.]) + >>> # sum from (1, 0) to (1, 2) and from (3, 3) to (4, 5) + >>> integrate(ii, [(1, 0), (3, 3)], [(1, 2), (4, 5)]) + array([3., 6.]) + """ + start = np.atleast_2d(np.array(start)) + end = np.atleast_2d(np.array(end)) + rows = start.shape[0] + + total_shape = ii.shape + total_shape = np.tile(total_shape, [rows, 1]) + + # convert negative indices into equivalent positive indices + start_negatives = start < 0 + end_negatives = end < 0 + start = (start + total_shape) * start_negatives + start * ~(start_negatives) + end = (end + total_shape) * end_negatives + end * ~(end_negatives) + + if np.any((end - start) < 0): + raise IndexError('end coordinates must be greater or equal to start') + + # bit_perm is the total number of terms in the expression + # of S. For example, in the case of a 4x4 2D image + # sum of image from (1,1) to (2,2) is given by + # S = + ii[2, 2] + # - ii[0, 2] - ii[2, 0] + # + ii[0, 0] + # The total terms = 4 = 2 ** 2(dims) + + S = np.zeros(rows) + bit_perm = 2**ii.ndim + width = len(bin(bit_perm - 1)[2:]) + + # Sum of a (hyper)cube, from an integral image is computed using + # values at the corners of the cube. The corners of cube are + # selected using binary numbers as described in the following example. + # In a 3D cube there are 8 corners. The corners are selected using + # binary numbers 000 to 111. Each number is called a permutation, where + # perm(000) means, select end corner where none of the coordinates + # is replaced, i.e ii[end_row, end_col, end_depth]. Similarly, perm(001) + # means replace last coordinate by start - 1, i.e + # ii[end_row, end_col, start_depth - 1], and so on. + # Sign of even permutations is positive, while those of odd is negative. + # If 'start_coord - 1' is -ve it is labeled bad and not considered in + # the final sum. + + for i in range(bit_perm): # for all permutations + # boolean permutation array eg [True, False] for '10' + binary = bin(i)[2:].zfill(width) + bool_mask = [bit == '1' for bit in binary] + + sign = (-1) ** sum(bool_mask) # determine sign of permutation + + bad = [ + np.any(((start[r] - 1) * bool_mask) < 0) for r in range(rows) + ] # find out bad start rows + + corner_points = (end * (np.invert(bool_mask))) + ( + (start - 1) * bool_mask + ) # find corner for each row + + S += [ + sign * float(ii[tuple(corner_points[r])]) if (not bad[r]) else 0 + for r in range(rows) + ] # add only good rows + return S diff --git a/envs/kitoverlay/skimage/transform/pyramids.py b/envs/kitoverlay/skimage/transform/pyramids.py new file mode 100644 index 0000000000000000000000000000000000000000..3d20c4680158421ef6ef6b457448ac9189739cd7 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/pyramids.py @@ -0,0 +1,408 @@ +import math + +import numpy as np + +from .._shared.filters import gaussian +from .._shared.utils import convert_to_float +from ._warps import resize + + +def _smooth(image, sigma, mode, cval, channel_axis): + """Return image with each channel smoothed by the Gaussian filter.""" + smoothed = np.empty_like(image) + + # apply Gaussian filter to all channels independently + if channel_axis is not None: + # can rely on gaussian to insert a 0 entry at channel_axis + channel_axis = channel_axis % image.ndim + sigma = (sigma,) * (image.ndim - 1) + else: + channel_axis = None + gaussian( + image, + sigma=sigma, + out=smoothed, + mode=mode, + cval=cval, + channel_axis=channel_axis, + ) + return smoothed + + +def _check_factor(factor): + if factor <= 1: + raise ValueError('scale factor must be greater than 1') + + +def pyramid_reduce( + image, + downscale=2, + sigma=None, + order=1, + mode='reflect', + cval=0, + preserve_range=False, + *, + channel_axis=None, +): + """Smooth and then downsample image. + + Parameters + ---------- + image : ndarray + Input image. + downscale : float, optional + Downscale factor. + sigma : float, optional + Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which + corresponds to a filter mask twice the size of the scale factor that + covers more than 99% of the Gaussian distribution. + order : int, optional + Order of splines used in interpolation of downsampling. See + `skimage.transform.warp` for detail. + mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional + The mode parameter determines how the array borders are handled, where + cval is the value when mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : array + Smoothed and downsampled float image. + + References + ---------- + .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf + + """ + _check_factor(downscale) + + image = convert_to_float(image, preserve_range) + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + out_shape = tuple( + math.ceil(d / float(downscale)) if ax != channel_axis else d + for ax, d in enumerate(image.shape) + ) + else: + out_shape = tuple(math.ceil(d / float(downscale)) for d in image.shape) + + if sigma is None: + # automatically determine sigma which covers > 99% of distribution + sigma = 2 * downscale / 6.0 + + smoothed = _smooth(image, sigma, mode, cval, channel_axis) + out = resize( + smoothed, out_shape, order=order, mode=mode, cval=cval, anti_aliasing=False + ) + + return out + + +def pyramid_expand( + image, + upscale=2, + sigma=None, + order=1, + mode='reflect', + cval=0, + preserve_range=False, + *, + channel_axis=None, +): + """Upsample and then smooth image. + + Parameters + ---------- + image : ndarray + Input image. + upscale : float, optional + Upscale factor. + sigma : float, optional + Sigma for Gaussian filter. Default is `2 * upscale / 6.0` which + corresponds to a filter mask twice the size of the scale factor that + covers more than 99% of the Gaussian distribution. + order : int, optional + Order of splines used in interpolation of upsampling. See + `skimage.transform.warp` for detail. + mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional + The mode parameter determines how the array borders are handled, where + cval is the value when mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : array + Upsampled and smoothed float image. + + References + ---------- + .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf + + """ + _check_factor(upscale) + image = convert_to_float(image, preserve_range) + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + out_shape = tuple( + math.ceil(upscale * d) if ax != channel_axis else d + for ax, d in enumerate(image.shape) + ) + else: + out_shape = tuple(math.ceil(upscale * d) for d in image.shape) + + if sigma is None: + # automatically determine sigma which covers > 99% of distribution + sigma = 2 * upscale / 6.0 + + resized = resize( + image, out_shape, order=order, mode=mode, cval=cval, anti_aliasing=False + ) + out = _smooth(resized, sigma, mode, cval, channel_axis) + + return out + + +def pyramid_gaussian( + image, + max_layer=-1, + downscale=2, + sigma=None, + order=1, + mode='reflect', + cval=0, + preserve_range=False, + *, + channel_axis=None, +): + """Yield images of the Gaussian pyramid formed by the input image. + + Recursively applies the `pyramid_reduce` function to the image, and yields + the downscaled images. + + Note that the first image of the pyramid will be the original, unscaled + image. The total number of images is `max_layer + 1`. In case all layers + are computed, the last image is either a one-pixel image or the image where + the reduction does not change its shape. + + Parameters + ---------- + image : ndarray + Input image. + max_layer : int, optional + Number of layers for the pyramid. 0th layer is the original image. + Default is -1 which builds all possible layers. + downscale : float, optional + Downscale factor. + sigma : float, optional + Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which + corresponds to a filter mask twice the size of the scale factor that + covers more than 99% of the Gaussian distribution. + order : int, optional + Order of splines used in interpolation of downsampling. See + `skimage.transform.warp` for detail. + mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional + The mode parameter determines how the array borders are handled, where + cval is the value when mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + pyramid : generator + Generator yielding pyramid layers as float images. + + References + ---------- + .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf + + """ + _check_factor(downscale) + + # cast to float for consistent data type in pyramid + image = convert_to_float(image, preserve_range) + + layer = 0 + current_shape = image.shape + + prev_layer_image = image + yield image + + # build downsampled images until max_layer is reached or downscale process + # does not change image size + while layer != max_layer: + layer += 1 + + layer_image = pyramid_reduce( + prev_layer_image, + downscale, + sigma, + order, + mode, + cval, + channel_axis=channel_axis, + ) + + prev_shape = current_shape + prev_layer_image = layer_image + current_shape = layer_image.shape + + # no change to previous pyramid layer + if current_shape == prev_shape: + break + + yield layer_image + + +def pyramid_laplacian( + image, + max_layer=-1, + downscale=2, + sigma=None, + order=1, + mode='reflect', + cval=0, + preserve_range=False, + *, + channel_axis=None, +): + """Yield images of the laplacian pyramid formed by the input image. + + Each layer contains the difference between the downsampled and the + downsampled, smoothed image:: + + layer = resize(prev_layer) - smooth(resize(prev_layer)) + + Note that the first image of the pyramid will be the difference between the + original, unscaled image and its smoothed version. The total number of + images is `max_layer + 1`. In case all layers are computed, the last image + is either a one-pixel image or the image where the reduction does not + change its shape. + + Parameters + ---------- + image : ndarray + Input image. + max_layer : int, optional + Number of layers for the pyramid. 0th layer is the original image. + Default is -1 which builds all possible layers. + downscale : float, optional + Downscale factor. + sigma : float, optional + Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which + corresponds to a filter mask twice the size of the scale factor that + covers more than 99% of the Gaussian distribution. + order : int, optional + Order of splines used in interpolation of downsampling. See + `skimage.transform.warp` for detail. + mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional + The mode parameter determines how the array borders are handled, where + cval is the value when mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if mode is 'constant'. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + pyramid : generator + Generator yielding pyramid layers as float images. + + References + ---------- + .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf + .. [2] http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html + + """ + _check_factor(downscale) + + # cast to float for consistent data type in pyramid + image = convert_to_float(image, preserve_range) + + if sigma is None: + # automatically determine sigma which covers > 99% of distribution + sigma = 2 * downscale / 6.0 + + current_shape = image.shape + + smoothed_image = _smooth(image, sigma, mode, cval, channel_axis) + yield image - smoothed_image + + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + shape_without_channels = list(current_shape) + shape_without_channels.pop(channel_axis) + shape_without_channels = tuple(shape_without_channels) + else: + shape_without_channels = current_shape + + # build downsampled images until max_layer is reached or downscale process + # does not change image size + if max_layer == -1: + max_layer = math.ceil(math.log(max(shape_without_channels), downscale)) + + for layer in range(max_layer): + if channel_axis is not None: + out_shape = tuple( + math.ceil(d / float(downscale)) if ax != channel_axis else d + for ax, d in enumerate(current_shape) + ) + else: + out_shape = tuple(math.ceil(d / float(downscale)) for d in current_shape) + + resized_image = resize( + smoothed_image, + out_shape, + order=order, + mode=mode, + cval=cval, + anti_aliasing=False, + ) + smoothed_image = _smooth(resized_image, sigma, mode, cval, channel_axis) + current_shape = resized_image.shape + + yield resized_image - smoothed_image diff --git a/envs/kitoverlay/skimage/transform/radon_transform.py b/envs/kitoverlay/skimage/transform/radon_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..69388efb4693d374fde949f97b770b6a09970869 --- /dev/null +++ b/envs/kitoverlay/skimage/transform/radon_transform.py @@ -0,0 +1,536 @@ +import numpy as np + +from scipy.interpolate import interp1d +from scipy.constants import golden_ratio +from scipy.fft import fft, ifft, fftfreq, fftshift +from ._warps import warp +from ._radon_transform import sart_projection_update +from .._shared.utils import convert_to_float +from warnings import warn +from functools import partial + + +__all__ = ['radon', 'order_angles_golden_ratio', 'iradon', 'iradon_sart'] + + +def radon(image, theta=None, circle=True, *, preserve_range=False): + """ + Calculates the radon transform of an image given specified + projection angles. + + Parameters + ---------- + image : ndarray + Input image. The rotation axis will be located in the pixel with + indices ``(image.shape[0] // 2, image.shape[1] // 2)``. + theta : array, optional + Projection angles (in degrees). If `None`, the value is set to + np.arange(180). + circle : bool, optional + Assume image is zero outside the inscribed circle, making the + width of each projection (the first dimension of the sinogram) + equal to ``min(image.shape)``. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + + Returns + ------- + radon_image : ndarray + Radon transform (sinogram). The tomography rotation axis will lie + at the pixel index ``radon_image.shape[0] // 2`` along the 0th + dimension of ``radon_image``. + + References + ---------- + .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic + Imaging", IEEE Press 1988. + .. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing + the Discrete Radon Transform With Some Applications", Proceedings of + the Fourth IEEE Region 10 International Conference, TENCON '89, 1989 + + Notes + ----- + Based on code of Justin K. Romberg + (https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html) + + """ + if image.ndim != 2: + raise ValueError('The input image must be 2-D') + if theta is None: + theta = np.arange(180) + + image = convert_to_float(image, preserve_range) + + if circle: + shape_min = min(image.shape) + radius = shape_min // 2 + img_shape = np.array(image.shape) + coords = np.array(np.ogrid[: image.shape[0], : image.shape[1]], dtype=object) + dist = ((coords - img_shape // 2) ** 2).sum(0) + outside_reconstruction_circle = dist > radius**2 + if np.any(image[outside_reconstruction_circle]): + warn( + 'Radon transform: image must be zero outside the ' + 'reconstruction circle' + ) + # Crop image to make it square + slices = tuple( + ( + slice(int(np.ceil(excess / 2)), int(np.ceil(excess / 2) + shape_min)) + if excess > 0 + else slice(None) + ) + for excess in (img_shape - shape_min) + ) + padded_image = image[slices] + else: + diagonal = np.sqrt(2) * max(image.shape) + pad = [int(np.ceil(diagonal - s)) for s in image.shape] + new_center = [(s + p) // 2 for s, p in zip(image.shape, pad)] + old_center = [s // 2 for s in image.shape] + pad_before = [nc - oc for oc, nc in zip(old_center, new_center)] + pad_width = [(pb, p - pb) for pb, p in zip(pad_before, pad)] + padded_image = np.pad(image, pad_width, mode='constant', constant_values=0) + + # padded_image is always square + if padded_image.shape[0] != padded_image.shape[1]: + raise ValueError('padded_image must be a square') + center = padded_image.shape[0] // 2 + radon_image = np.zeros((padded_image.shape[0], len(theta)), dtype=image.dtype) + + for i, angle in enumerate(np.deg2rad(theta)): + cos_a, sin_a = np.cos(angle), np.sin(angle) + R = np.array( + [ + [cos_a, sin_a, -center * (cos_a + sin_a - 1)], + [-sin_a, cos_a, -center * (cos_a - sin_a - 1)], + [0, 0, 1], + ] + ) + rotated = warp(padded_image, R, clip=False) + radon_image[:, i] = rotated.sum(0) + return radon_image + + +def _sinogram_circle_to_square(sinogram): + diagonal = int(np.ceil(np.sqrt(2) * sinogram.shape[0])) + pad = diagonal - sinogram.shape[0] + old_center = sinogram.shape[0] // 2 + new_center = diagonal // 2 + pad_before = new_center - old_center + pad_width = ((pad_before, pad - pad_before), (0, 0)) + return np.pad(sinogram, pad_width, mode='constant', constant_values=0) + + +def _get_fourier_filter(size, filter_name): + """Construct the Fourier filter. + + This computation lessens artifacts and removes a small bias as + explained in [1], Chap 3. Equation 61. + + Parameters + ---------- + size : int + filter size. Must be even. + filter_name : str + Filter used in frequency domain filtering. Filters available: + ramp, shepp-logan, cosine, hamming, hann. Assign None to use + no filter. + + Returns + ------- + fourier_filter: ndarray + The computed Fourier filter. + + References + ---------- + .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic + Imaging", IEEE Press 1988. + + """ + n = np.concatenate( + ( + np.arange(1, size / 2 + 1, 2, dtype=int), + np.arange(size / 2 - 1, 0, -2, dtype=int), + ) + ) + f = np.zeros(size) + f[0] = 0.25 + f[1::2] = -1 / (np.pi * n) ** 2 + + # Computing the ramp filter from the fourier transform of its + # frequency domain representation lessens artifacts and removes a + # small bias as explained in [1], Chap 3. Equation 61 + fourier_filter = 2 * np.real(fft(f)) # ramp filter + if filter_name == "ramp": + pass + elif filter_name == "shepp-logan": + # Start from first element to avoid divide by zero + omega = np.pi * fftfreq(size)[1:] + fourier_filter[1:] *= np.sin(omega) / omega + elif filter_name == "cosine": + freq = np.linspace(0, np.pi, size, endpoint=False) + cosine_filter = fftshift(np.sin(freq)) + fourier_filter *= cosine_filter + elif filter_name == "hamming": + fourier_filter *= fftshift(np.hamming(size)) + elif filter_name == "hann": + fourier_filter *= fftshift(np.hanning(size)) + elif filter_name is None: + fourier_filter[:] = 1 + + return fourier_filter[:, np.newaxis] + + +def iradon( + radon_image, + theta=None, + output_size=None, + filter_name="ramp", + interpolation="linear", + circle=True, + preserve_range=True, +): + """Inverse radon transform. + + Reconstruct an image from the radon transform, using the filtered + back projection algorithm. + + Parameters + ---------- + radon_image : ndarray + Image containing radon transform (sinogram). Each column of + the image corresponds to a projection along a different + angle. The tomography rotation axis should lie at the pixel + index ``radon_image.shape[0] // 2`` along the 0th dimension of + ``radon_image``. + theta : array, optional + Reconstruction angles (in degrees). Default: m angles evenly spaced + between 0 and 180 (if the shape of `radon_image` is (N, M)). + output_size : int, optional + Number of rows and columns in the reconstruction. + filter_name : str, optional + Filter used in frequency domain filtering. Ramp filter used by default. + Filters available: ramp, shepp-logan, cosine, hamming, hann. + Assign None to use no filter. + interpolation : str, optional + Interpolation method used in reconstruction. Methods available: + 'linear', 'nearest', and 'cubic' ('cubic' is slow). + circle : bool, optional + Assume the reconstructed image is zero outside the inscribed circle. + Also changes the default output_size to match the behaviour of + ``radon`` called with ``circle=True``. + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + + Returns + ------- + reconstructed : ndarray + Reconstructed image. The rotation axis will be located in the pixel + with indices + ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``. + + .. versionchanged:: 0.19 + In ``iradon``, ``filter`` argument is deprecated in favor of + ``filter_name``. + + References + ---------- + .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic + Imaging", IEEE Press 1988. + .. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing + the Discrete Radon Transform With Some Applications", Proceedings of + the Fourth IEEE Region 10 International Conference, TENCON '89, 1989 + + Notes + ----- + It applies the Fourier slice theorem to reconstruct an image by + multiplying the frequency domain of the filter with the FFT of the + projection data. This algorithm is called filtered back projection. + + """ + if radon_image.ndim != 2: + raise ValueError('The input image must be 2-D') + + if theta is None: + theta = np.linspace(0, 180, radon_image.shape[1], endpoint=False) + + angles_count = len(theta) + if angles_count != radon_image.shape[1]: + raise ValueError( + "The given ``theta`` does not match the number of " + "projections in ``radon_image``." + ) + + interpolation_types = ('linear', 'nearest', 'cubic') + if interpolation not in interpolation_types: + raise ValueError(f"Unknown interpolation: {interpolation}") + + filter_types = ('ramp', 'shepp-logan', 'cosine', 'hamming', 'hann', None) + if filter_name not in filter_types: + raise ValueError(f"Unknown filter: {filter_name}") + + radon_image = convert_to_float(radon_image, preserve_range) + dtype = radon_image.dtype + + img_shape = radon_image.shape[0] + if output_size is None: + # If output size not specified, estimate from input radon image + if circle: + output_size = img_shape + else: + output_size = int(np.floor(np.sqrt((img_shape) ** 2 / 2.0))) + + if circle: + radon_image = _sinogram_circle_to_square(radon_image) + img_shape = radon_image.shape[0] + + # Resize image to next power of two (but no less than 64) for + # Fourier analysis; speeds up Fourier and lessens artifacts + projection_size_padded = max(64, int(2 ** np.ceil(np.log2(2 * img_shape)))) + pad_width = ((0, projection_size_padded - img_shape), (0, 0)) + img = np.pad(radon_image, pad_width, mode='constant', constant_values=0) + + # Apply filter in Fourier domain + fourier_filter = _get_fourier_filter(projection_size_padded, filter_name) + projection = fft(img, axis=0) * fourier_filter + radon_filtered = np.real(ifft(projection, axis=0)[:img_shape, :]) + + # Reconstruct image by interpolation + reconstructed = np.zeros((output_size, output_size), dtype=dtype) + radius = output_size // 2 + xpr, ypr = np.mgrid[:output_size, :output_size] - radius + x = np.arange(img_shape) - img_shape // 2 + + for col, angle in zip(radon_filtered.T, np.deg2rad(theta)): + t = ypr * np.cos(angle) - xpr * np.sin(angle) + if interpolation == 'linear': + interpolant = partial(np.interp, xp=x, fp=col, left=0, right=0) + else: + interpolant = interp1d( + x, col, kind=interpolation, bounds_error=False, fill_value=0 + ) + reconstructed += interpolant(t) + + if circle: + out_reconstruction_circle = (xpr**2 + ypr**2) > radius**2 + reconstructed[out_reconstruction_circle] = 0.0 + + return reconstructed * np.pi / (2 * angles_count) + + +def order_angles_golden_ratio(theta): + """Order angles to reduce the amount of correlated information in + subsequent projections. + + Parameters + ---------- + theta : array of floats, shape (M,) + Projection angles in degrees. Duplicate angles are not allowed. + + Returns + ------- + indices_generator : generator yielding unsigned integers + The returned generator yields indices into ``theta`` such that + ``theta[indices]`` gives the approximate golden ratio ordering + of the projections. In total, ``len(theta)`` indices are yielded. + All non-negative integers < ``len(theta)`` are yielded exactly once. + + Notes + ----- + The method used here is that of the golden ratio introduced + by T. Kohler. + + References + ---------- + .. [1] Kohler, T. "A projection access scheme for iterative + reconstruction based on the golden section." Nuclear Science + Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. + .. [2] Winkelmann, Stefanie, et al. "An optimal radial profile order + based on the Golden Ratio for time-resolved MRI." + Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76. + + """ + interval = 180 + + remaining_indices = list(np.argsort(theta)) # indices into theta + # yield an arbitrary angle to start things off + angle = theta[remaining_indices[0]] + yield remaining_indices.pop(0) + # determine subsequent angles using the golden ratio method + angle_increment = interval / golden_ratio**2 + while remaining_indices: + remaining_angles = theta[remaining_indices] + angle = (angle + angle_increment) % interval + index_above = np.searchsorted(remaining_angles, angle) + index_below = index_above - 1 + index_above %= len(remaining_indices) + + diff_below = abs(angle - remaining_angles[index_below]) + distance_below = min(diff_below % interval, diff_below % -interval) + + diff_above = abs(angle - remaining_angles[index_above]) + distance_above = min(diff_above % interval, diff_above % -interval) + + if distance_below < distance_above: + yield remaining_indices.pop(index_below) + else: + yield remaining_indices.pop(index_above) + + +def iradon_sart( + radon_image, + theta=None, + image=None, + projection_shifts=None, + clip=None, + relaxation=0.15, + dtype=None, +): + """Inverse radon transform. + + Reconstruct an image from the radon transform, using a single iteration of + the Simultaneous Algebraic Reconstruction Technique (SART) algorithm. + + Parameters + ---------- + radon_image : ndarray, shape (M, N) + Image containing radon transform (sinogram). Each column of + the image corresponds to a projection along a different angle. The + tomography rotation axis should lie at the pixel index + ``radon_image.shape[0] // 2`` along the 0th dimension of + ``radon_image``. + theta : array, shape (N,), optional + Reconstruction angles (in degrees). Default: m angles evenly spaced + between 0 and 180 (if the shape of `radon_image` is (N, M)). + image : ndarray, shape (M, M), optional + Image containing an initial reconstruction estimate. Default is an array of zeros. + projection_shifts : array, shape (N,), optional + Shift the projections contained in ``radon_image`` (the sinogram) by + this many pixels before reconstructing the image. The i'th value + defines the shift of the i'th column of ``radon_image``. + clip : length-2 sequence of floats, optional + Force all values in the reconstructed tomogram to lie in the range + ``[clip[0], clip[1]]`` + relaxation : float, optional + Relaxation parameter for the update step. A higher value can + improve the convergence rate, but one runs the risk of instabilities. + Values close to or higher than 1 are not recommended. + dtype : dtype, optional + Output data type, must be floating point. By default, if input + data type is not float, input is cast to double, otherwise + dtype is set to input data type. + + Returns + ------- + reconstructed : ndarray + Reconstructed image. The rotation axis will be located in the pixel + with indices + ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``. + + Notes + ----- + Algebraic Reconstruction Techniques are based on formulating the tomography + reconstruction problem as a set of linear equations. Along each ray, + the projected value is the sum of all the values of the cross section along + the ray. A typical feature of SART (and a few other variants of algebraic + techniques) is that it samples the cross section at equidistant points + along the ray, using linear interpolation between the pixel values of the + cross section. The resulting set of linear equations are then solved using + a slightly modified Kaczmarz method. + + When using SART, a single iteration is usually sufficient to obtain a good + reconstruction. Further iterations will tend to enhance high-frequency + information, but will also often increase the noise. + + References + ---------- + .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic + Imaging", IEEE Press 1988. + .. [2] AH Andersen, AC Kak, "Simultaneous algebraic reconstruction + technique (SART): a superior implementation of the ART algorithm", + Ultrasonic Imaging 6 pp 81--94 (1984) + .. [3] S Kaczmarz, "Angenäherte auflösung von systemen linearer + gleichungen", Bulletin International de l’Academie Polonaise des + Sciences et des Lettres 35 pp 355--357 (1937) + .. [4] Kohler, T. "A projection access scheme for iterative + reconstruction based on the golden section." Nuclear Science + Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. + .. [5] Kaczmarz' method, Wikipedia, + https://en.wikipedia.org/wiki/Kaczmarz_method + + """ + if radon_image.ndim != 2: + raise ValueError('radon_image must be two dimensional') + + if dtype is None: + if radon_image.dtype.char in 'fd': + dtype = radon_image.dtype + else: + warn( + "Only floating point data type are valid for SART inverse " + "radon transform. Input data is cast to float. To disable " + "this warning, please cast image_radon to float." + ) + dtype = np.dtype(float) + elif np.dtype(dtype).char not in 'fd': + raise ValueError( + "Only floating point data type are valid for inverse " "radon transform." + ) + + dtype = np.dtype(dtype) + radon_image = radon_image.astype(dtype, copy=False) + + reconstructed_shape = (radon_image.shape[0], radon_image.shape[0]) + + if theta is None: + theta = np.linspace(0, 180, radon_image.shape[1], endpoint=False, dtype=dtype) + elif len(theta) != radon_image.shape[1]: + raise ValueError( + f'Shape of theta ({len(theta)}) does not match the ' + f'number of projections ({radon_image.shape[1]})' + ) + else: + theta = np.asarray(theta, dtype=dtype) + + if image is None: + image = np.zeros(reconstructed_shape, dtype=dtype) + elif image.shape != reconstructed_shape: + raise ValueError( + f'Shape of image ({image.shape}) does not match first dimension ' + f'of radon_image ({reconstructed_shape})' + ) + elif image.dtype != dtype: + warn(f'image dtype does not match output dtype: ' f'image is cast to {dtype}') + + image = np.asarray(image, dtype=dtype) + + if projection_shifts is None: + projection_shifts = np.zeros((radon_image.shape[1],), dtype=dtype) + elif len(projection_shifts) != radon_image.shape[1]: + raise ValueError( + f'Shape of projection_shifts ({len(projection_shifts)}) does not match the ' + f'number of projections ({radon_image.shape[1]})' + ) + else: + projection_shifts = np.asarray(projection_shifts, dtype=dtype) + if clip is not None: + if len(clip) != 2: + raise ValueError('clip must be a length-2 sequence') + clip = np.asarray(clip, dtype=dtype) + + for angle_index in order_angles_golden_ratio(theta): + image_update = sart_projection_update( + image, + theta[angle_index], + radon_image[:, angle_index], + projection_shifts[angle_index], + ) + image += relaxation * image_update + if clip is not None: + image = np.clip(image, clip[0], clip[1]) + return image