diff --git a/envs/kitoverlay/skimage/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c73caf31ce6a699924b9586f38b54c4ce645710 Binary files /dev/null and b/envs/kitoverlay/skimage/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/__pycache__/conftest.cpython-311.pyc b/envs/kitoverlay/skimage/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a561d0498d7799e37df35f7e254d96f876901d Binary files /dev/null and b/envs/kitoverlay/skimage/__pycache__/conftest.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_vendored/__init__.py b/envs/kitoverlay/skimage/_vendored/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/envs/kitoverlay/skimage/_vendored/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/_vendored/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5a2ef113f1db69764c0f874aec134154adf07fa Binary files /dev/null and b/envs/kitoverlay/skimage/_vendored/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_vendored/__pycache__/numpy_lookfor.cpython-311.pyc b/envs/kitoverlay/skimage/_vendored/__pycache__/numpy_lookfor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11b87de116bc290535601dc3a9ae564b7ab5a22a Binary files /dev/null and b/envs/kitoverlay/skimage/_vendored/__pycache__/numpy_lookfor.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/_vendored/numpy_lookfor.py b/envs/kitoverlay/skimage/_vendored/numpy_lookfor.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa8f61dd3a35d2d114dfd21930580d2bba9b0cf --- /dev/null +++ b/envs/kitoverlay/skimage/_vendored/numpy_lookfor.py @@ -0,0 +1,298 @@ +# Vendored subset of numpy/lib/utils.py in 1.26.3 +# https://github.com/numpy/numpy/blob/b4bf93b936802618ebb49ee43e382b576b29a0a6/numpy/lib/utils.py +# +# Can be removed after deprecation of `skimage.lookfor` is completed. + +import sys +import os +import re + +from numpy import ufunc + + +# Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...} +# where kind: "func", "class", "module", "object" +# and index: index in breadth-first namespace traversal +_lookfor_caches = {} + + +# regexp whose match indicates that the string may contain a function +# signature +_function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I) + + +def _getmembers(item): + import inspect + + try: + members = inspect.getmembers(item) + except Exception: + members = [(x, getattr(item, x)) for x in dir(item) if hasattr(item, x)] + return members + + +def _lookfor_generate_cache(module, import_modules, regenerate): + """ + Generate docstring cache for given module. + + Parameters + ---------- + module : str, None, module + Module for which to generate docstring cache + import_modules : bool + Whether to import sub-modules in packages. + regenerate : bool + Re-generate the docstring cache + + Returns + ------- + cache : dict {obj_full_name: (docstring, kind, index), ...} + Docstring cache for the module, either cached one (regenerate=False) + or newly generated. + + """ + # Local import to speed up numpy's import time. + import inspect + + from io import StringIO + + if module is None: + module = "skimage" + + if isinstance(module, str): + try: + __import__(module) + except ImportError: + return {} + module = sys.modules[module] + elif isinstance(module, list) or isinstance(module, tuple): + cache = {} + for mod in module: + cache.update(_lookfor_generate_cache(mod, import_modules, regenerate)) + return cache + + if id(module) in _lookfor_caches and not regenerate: + return _lookfor_caches[id(module)] + + # walk items and collect docstrings + cache = {} + _lookfor_caches[id(module)] = cache + seen = {} + index = 0 + stack = [(module.__name__, module)] + while stack: + name, item = stack.pop(0) + if id(item) in seen: + continue + seen[id(item)] = True + + index += 1 + kind = "object" + + if inspect.ismodule(item): + kind = "module" + try: + _all = item.__all__ + except AttributeError: + _all = None + + # import sub-packages + if import_modules and hasattr(item, '__path__'): + for pth in item.__path__: + if os.path.isfile(pth) or not os.path.exists(pth): + continue + for mod_path in os.listdir(pth): + this_py = os.path.join(pth, mod_path) + init_py = os.path.join(pth, mod_path, '__init__.py') + if os.path.isfile(this_py) and mod_path.endswith('.py'): + to_import = mod_path[:-3] + elif os.path.isfile(init_py): + to_import = mod_path + else: + continue + if to_import == '__init__': + continue + + try: + old_stdout = sys.stdout + old_stderr = sys.stderr + try: + sys.stdout = StringIO() + sys.stderr = StringIO() + __import__(f"{name}.{to_import}") + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + except KeyboardInterrupt: + # Assume keyboard interrupt came from a user + raise + except BaseException: + # Ignore also SystemExit and pytests.importorskip + # `Skipped` (these are BaseExceptions; gh-22345) + continue + + for n, v in _getmembers(item): + try: + item_name = getattr( + v, + '__name__', + f"{name}.{n}", + ) + mod_name = getattr(v, '__module__', None) + except NameError: + # ref. SWIG's global cvars + # NameError: Unknown C global variable + item_name = f"{name}.{n}" + mod_name = None + if '.' not in item_name and mod_name: + item_name = f"{mod_name}.{item_name}" + + if not item_name.startswith(name + '.'): + # don't crawl "foreign" objects + if isinstance(v, ufunc): + # ... unless they are ufuncs + pass + else: + continue + elif not (inspect.ismodule(v) or _all is None or n in _all): + continue + + stack.append((f"{name}.{n}", v)) + elif inspect.isclass(item): + kind = "class" + for n, v in _getmembers(item): + stack.append((f"{name}.{n}", v)) + elif hasattr(item, "__call__"): + kind = "func" + + try: + doc = inspect.getdoc(item) + except NameError: + # ref SWIG's NameError: Unknown C global variable + doc = None + if doc is not None: + cache[name] = (doc, kind, index) + + return cache + + +def lookfor(what, module=None, import_modules=True, regenerate=False, output=None): + """ + Do a keyword search on docstrings. + + A list of objects that matched the search is displayed, + sorted by relevance. All given keywords need to be found in the + docstring for it to be returned as a result, but the order does + not matter. + + Parameters + ---------- + what : str + String containing words to look for. + module : str or list, optional + Name of module(s) whose docstrings to go through. + import_modules : bool, optional + Whether to import sub-modules in packages. Default is True. + regenerate : bool, optional + Whether to re-generate the docstring cache. Default is False. + output : file-like, optional + File-like object to write the output to. If omitted, use a pager. + + See Also + -------- + source, info + + Notes + ----- + Relevance is determined only roughly, by checking if the keywords occur + in the function name, at the start of a docstring, etc. + + Examples + -------- + >>> np.lookfor('binary representation') # doctest: +SKIP + Search results for 'binary representation' + ------------------------------------------ + numpy.binary_repr + Return the binary representation of the input number as a string. + numpy.core.setup_common.long_double_representation + Given a binary dump as given by GNU od -b, look for long double + numpy.base_repr + Return a string representation of a number in the given base system. + ... + + """ + import pydoc + + # Cache + cache = _lookfor_generate_cache(module, import_modules, regenerate) + + # Search + # XXX: maybe using a real stemming search engine would be better? + found = [] + whats = str(what).lower().split() + if not whats: + return + + for name, (docstring, kind, index) in cache.items(): + if kind in ('module', 'object'): + # don't show modules or objects + continue + doc = docstring.lower() + if all(w in doc for w in whats): + found.append(name) + + # Relevance sort + # XXX: this is full Harrison-Stetson heuristics now, + # XXX: it probably could be improved + + kind_relevance = {'func': 1000, 'class': 1000, 'module': -1000, 'object': -1000} + + def relevance(name, docstr, kind, index): + r = 0 + # do the keywords occur within the start of the docstring? + first_doc = "\n".join(docstr.lower().strip().split("\n")[:3]) + r += sum([200 for w in whats if w in first_doc]) + # do the keywords occur in the function name? + r += sum([30 for w in whats if w in name]) + # is the full name long? + r += -len(name) * 5 + # is the object of bad type? + r += kind_relevance.get(kind, -1000) + # is the object deep in namespace hierarchy? + r += -name.count('.') * 10 + r += max(-index / 100, -100) + return r + + def relevance_value(a): + return relevance(a, *cache[a]) + + found.sort(key=relevance_value) + + # Pretty-print + s = f"Search results for '{' '.join(whats)}'" + help_text = [s, "-" * len(s)] + for name in found[::-1]: + doc, kind, ix = cache[name] + + doclines = [line.strip() for line in doc.strip().split("\n") if line.strip()] + + # find a suitable short description + try: + first_doc = doclines[0].strip() + if _function_signature_re.search(first_doc): + first_doc = doclines[1].strip() + except IndexError: + first_doc = "" + help_text.append(f"{name}\n {first_doc}") + + if not found: + help_text.append("Nothing found.") + + # Output + if output is not None: + output.write("\n".join(help_text)) + elif len(help_text) > 10: + pager = pydoc.getpager() + pager("\n".join(help_text)) + else: + print("\n".join(help_text)) diff --git a/envs/kitoverlay/skimage/draw/__init__.py b/envs/kitoverlay/skimage/draw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01a8b726606eb04d9d359933ce976096215904a1 --- /dev/null +++ b/envs/kitoverlay/skimage/draw/__init__.py @@ -0,0 +1,5 @@ +"""Drawing primitives, such as lines, circles, text, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/draw/__init__.pyi b/envs/kitoverlay/skimage/draw/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..52e425396c86fdd647c3fae7d69d7043453f8c94 --- /dev/null +++ b/envs/kitoverlay/skimage/draw/__init__.pyi @@ -0,0 +1,45 @@ +# 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__ = [ + 'line', + 'line_aa', + 'line_nd', + 'bezier_curve', + 'polygon', + 'polygon_perimeter', + 'ellipse', + 'ellipse_perimeter', + 'ellipsoid', + 'ellipsoid_stats', + 'circle_perimeter', + 'circle_perimeter_aa', + 'disk', + 'set_color', + 'random_shapes', + 'rectangle', + 'rectangle_perimeter', + 'polygon2mask', +] + +from .draw3d import ellipsoid, ellipsoid_stats +from ._draw import _bezier_segment +from ._random_shapes import random_shapes +from ._polygon2mask import polygon2mask +from .draw_nd import line_nd +from .draw import ( + ellipse, + set_color, + polygon_perimeter, + line, + line_aa, + polygon, + ellipse_perimeter, + circle_perimeter, + circle_perimeter_aa, + disk, + bezier_curve, + rectangle, + rectangle_perimeter, +) diff --git a/envs/kitoverlay/skimage/draw/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..921bd4ac5e3c281ff06c79f1747f6068e0c83587 Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/__pycache__/_polygon2mask.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/_polygon2mask.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..002595322ad08b84e113bf4ca4c85e9059987954 Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/_polygon2mask.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/__pycache__/_random_shapes.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/_random_shapes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2db9aefa052f25b7d50253324b5222e3369b2f85 Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/_random_shapes.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/__pycache__/draw.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/draw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..338ed56782d5c8129587adbebfda5a6aae03de4c Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/draw.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/__pycache__/draw3d.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/draw3d.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2dba25f73d8ab084a1e45ba8360f0e957b71860 Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/draw3d.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/__pycache__/draw_nd.cpython-311.pyc b/envs/kitoverlay/skimage/draw/__pycache__/draw_nd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6daf7ae97210b6ae6ca063b90405817b5bfb9c5f Binary files /dev/null and b/envs/kitoverlay/skimage/draw/__pycache__/draw_nd.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/draw/_polygon2mask.py b/envs/kitoverlay/skimage/draw/_polygon2mask.py new file mode 100644 index 0000000000000000000000000000000000000000..59ea0891e04c7f88a3e267ce2e029d17d7ff7cbf --- /dev/null +++ b/envs/kitoverlay/skimage/draw/_polygon2mask.py @@ -0,0 +1,74 @@ +import numpy as np + +from . import draw + + +def polygon2mask(image_shape, polygon): + """Create a binary mask from a polygon. + + Parameters + ---------- + image_shape : tuple of size 2 + The shape of the mask. + polygon : (N, 2) array_like + The polygon coordinates of shape (N, 2) where N is + the number of points. The coordinates are (row, column). + + Returns + ------- + mask : 2-D ndarray of type 'bool' + The binary mask that corresponds to the input polygon. + + See Also + -------- + polygon: + Generate coordinates of pixels inside a polygon. + + Notes + ----- + This function does not do any border checking. Parts of the polygon that + are outside the coordinate space defined by `image_shape` are not drawn. + + Examples + -------- + >>> import skimage as ski + >>> image_shape = (10, 10) + >>> polygon = np.array([[1, 1], [2, 7], [8, 4]]) + >>> mask = ski.draw.polygon2mask(image_shape, polygon) + >>> mask.astype(int) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + + If vertices / points of the `polygon` are outside the coordinate space + defined by `image_shape`, only a part (or none at all) of the polygon is + drawn in the mask. + + >>> offset = np.array([[2, -4]]) + >>> ski.draw.polygon2mask(image_shape, polygon - offset).astype(int) + array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 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]]) + """ + polygon = np.asarray(polygon) + vertex_row_coords, vertex_col_coords = polygon.T + fill_row_coords, fill_col_coords = draw.polygon( + vertex_row_coords, vertex_col_coords, image_shape + ) + mask = np.zeros(image_shape, dtype=bool) + mask[fill_row_coords, fill_col_coords] = True + return mask diff --git a/envs/kitoverlay/skimage/draw/_random_shapes.py b/envs/kitoverlay/skimage/draw/_random_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..031816f24dd549629a17ca55a4d6318c1b687921 --- /dev/null +++ b/envs/kitoverlay/skimage/draw/_random_shapes.py @@ -0,0 +1,459 @@ +import math + +import numpy as np + +from .draw import polygon as draw_polygon, disk as draw_disk, ellipse as draw_ellipse +from .._shared.utils import warn + + +def _generate_rectangle_mask(point, image, shape, random): + """Generate a mask for a filled rectangle shape. + + The height and width of the rectangle are generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape + is placed. + shape : tuple + The minimum and maximum size of the shape to fit. + random : `numpy.random.Generator` + + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + + """ + available_width = min(image[1] - point[1], shape[1]) - shape[0] + available_height = min(image[0] - point[0], shape[1]) - shape[0] + + # Pick random widths and heights. + r = shape[0] + random.integers(max(1, available_height)) - 1 + c = shape[0] + random.integers(max(1, available_width)) - 1 + rectangle = draw_polygon( + [ + point[0], + point[0] + r, + point[0] + r, + point[0], + ], + [ + point[1], + point[1], + point[1] + c, + point[1] + c, + ], + ) + label = ('rectangle', ((point[0], point[0] + r + 1), (point[1], point[1] + c + 1))) + + return rectangle, label + + +def _generate_circle_mask(point, image, shape, random): + """Generate a mask for a filled circle shape. + + The radius of the circle is generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape is placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('size must be > 1 for circles') + min_radius = shape[0] // 2.0 + max_radius = shape[1] // 2.0 + left = point[1] + right = image[1] - point[1] + top = point[0] + bottom = image[0] - point[0] + available_radius = min(left, right, top, bottom, max_radius) - min_radius + if available_radius < 0: + raise ArithmeticError('cannot fit shape to image') + radius = int(min_radius + random.integers(max(1, available_radius))) + # TODO: think about how to deprecate this + # while draw_circle was deprecated in favor of draw_disk + # switching to a label of 'disk' here + # would be a breaking change for downstream libraries + # See discussion on naming convention here + # https://github.com/scikit-image/scikit-image/pull/4428 + disk = draw_disk((point[0], point[1]), radius) + # Until a deprecation path is decided, always return `'circle'` + label = ( + 'circle', + ( + (point[0] - radius + 1, point[0] + radius), + (point[1] - radius + 1, point[1] + radius), + ), + ) + + return disk, label + + +def _generate_triangle_mask(point, image, shape, random): + """Generate a mask for a filled equilateral triangle shape. + + The length of the sides of the triangle is generated randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of a up-pointing triangle. + image : tuple + The height, width and depth of the image into which the shape + is placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('dimension must be > 1 for triangles') + available_side = min(image[1] - point[1], point[0], shape[1]) - shape[0] + side = shape[0] + random.integers(max(1, available_side)) - 1 + triangle_height = int(np.ceil(np.sqrt(3 / 4.0) * side)) + triangle = draw_polygon( + [ + point[0], + point[0] - triangle_height, + point[0], + ], + [ + point[1], + point[1] + side // 2, + point[1] + side, + ], + ) + label = ( + 'triangle', + ((point[0] - triangle_height, point[0] + 1), (point[1], point[1] + side + 1)), + ) + + return triangle, label + + +def _generate_ellipse_mask(point, image, shape, random): + """Generate a mask for a filled ellipse shape. + + The rotation, major and minor semi-axes of the ellipse are generated + randomly. + + Parameters + ---------- + point : tuple + The row and column of the top left corner of the rectangle. + image : tuple + The height, width and depth of the image into which the shape is + placed. + shape : tuple + The minimum and maximum size and color of the shape to fit. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ArithmeticError + When a shape cannot be fit into the image with the given starting + coordinates. This usually means the image dimensions are too small or + shape dimensions too large. + + Returns + ------- + label : tuple + A (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + indices : 2-D array + A mask of indices that the shape fills. + """ + if shape[0] == 1 or shape[1] == 1: + raise ValueError('size must be > 1 for ellipses') + min_radius = shape[0] / 2.0 + max_radius = shape[1] / 2.0 + left = point[1] + right = image[1] - point[1] + top = point[0] + bottom = image[0] - point[0] + available_radius = min(left, right, top, bottom, max_radius) + if available_radius < min_radius: + raise ArithmeticError('cannot fit shape to image') + # NOTE: very conservative because we could take into account the fact that + # we have 2 different radii, but this is a good first approximation. + # Also, we can afford to have a uniform sampling because the ellipse will + # be rotated. + r_radius = random.uniform(min_radius, available_radius + 1) + c_radius = random.uniform(min_radius, available_radius + 1) + rotation = random.uniform(-np.pi, np.pi) + ellipse = draw_ellipse( + point[0], + point[1], + r_radius, + c_radius, + shape=image[:2], + rotation=rotation, + ) + max_radius = math.ceil(max(r_radius, c_radius)) + min_x = np.min(ellipse[0]) + max_x = np.max(ellipse[0]) + 1 + min_y = np.min(ellipse[1]) + max_y = np.max(ellipse[1]) + 1 + label = ('ellipse', ((min_x, max_x), (min_y, max_y))) + + return ellipse, label + + +# Allows lookup by key as well as random selection. +SHAPE_GENERATORS = dict( + rectangle=_generate_rectangle_mask, + circle=_generate_circle_mask, + triangle=_generate_triangle_mask, + ellipse=_generate_ellipse_mask, +) +SHAPE_CHOICES = list(SHAPE_GENERATORS.values()) + + +def _generate_random_colors(num_colors, num_channels, intensity_range, random): + """Generate an array of random colors. + + Parameters + ---------- + num_colors : int + Number of colors to generate. + num_channels : int + Number of elements representing color. + intensity_range : {tuple of tuples of ints, tuple of ints}, optional + The range of values to sample pixel values from. For grayscale images + the format is (min, max). For multichannel - ((min, max),) if the + ranges are equal across the channels, and + ((min_0, max_0), ... (min_N, max_N)) if they differ. + random : `numpy.random.Generator` + The random state to use for random sampling. + + Raises + ------ + ValueError + When the `intensity_range` is not in the interval (0, 255). + + Returns + ------- + colors : array + An array of shape (num_colors, num_channels), where the values for + each channel are drawn from the corresponding `intensity_range`. + + """ + if num_channels == 1: + intensity_range = (intensity_range,) + elif len(intensity_range) == 1: + intensity_range = intensity_range * num_channels + colors = [random.integers(r[0], r[1] + 1, size=num_colors) for r in intensity_range] + return np.transpose(colors) + + +def random_shapes( + image_shape, + max_shapes, + min_shapes=1, + min_size=2, + max_size=None, + num_channels=3, + shape=None, + intensity_range=None, + allow_overlap=False, + num_trials=100, + rng=None, + *, + channel_axis=-1, +): + """Generate an image with random shapes, labeled with bounding boxes. + + The image is populated with random shapes with random sizes, random + locations, and random colors, with or without overlap. + + Shapes have random (row, col) starting coordinates and random sizes bounded + by `min_size` and `max_size`. It can occur that a randomly generated shape + will not fit the image at all. In that case, the algorithm will try again + with new starting coordinates a certain number of times. However, it also + means that some shapes may be skipped altogether. In that case, this + function will generate fewer shapes than requested. + + Parameters + ---------- + image_shape : tuple + The number of rows and columns of the image to generate. + max_shapes : int + The maximum number of shapes to (attempt to) fit into the shape. + min_shapes : int, optional + The minimum number of shapes to (attempt to) fit into the shape. + min_size : int, optional + The minimum dimension of each shape to fit into the image. + max_size : int, optional + The maximum dimension of each shape to fit into the image. + num_channels : int, optional + Number of channels in the generated image. If 1, generate monochrome + images, else color images with multiple channels. Ignored if + ``multichannel`` is set to False. + shape : {rectangle, circle, triangle, ellipse, None} str, optional + The name of the shape to generate or `None` to pick random ones. + intensity_range : {tuple of tuples of uint8, tuple of uint8}, optional + The range of values to sample pixel values from. For grayscale + images the format is (min, max). For multichannel - ((min, max),) + if the ranges are equal across the channels, and + ((min_0, max_0), ... (min_N, max_N)) if they differ. As the + function supports generation of uint8 arrays only, the maximum + range is (0, 255). If None, set to (0, 254) for each channel + reserving color of intensity = 255 for background. + allow_overlap : bool, optional + If `True`, allow shapes to overlap. + num_trials : int, optional + How often to attempt to fit a shape into the image before skipping it. + 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. + 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 + ------- + image : uint8 array + An image with the fitted shapes. + labels : list + A list of labels, one per shape in the image. Each label is a + (category, ((r0, r1), (c0, c1))) tuple specifying the category and + bounding box coordinates of the shape. + + Examples + -------- + >>> import skimage.draw + >>> image, labels = skimage.draw.random_shapes((32, 32), max_shapes=3) + >>> image # doctest: +SKIP + array([ + [[255, 255, 255], + [255, 255, 255], + [255, 255, 255], + ..., + [255, 255, 255], + [255, 255, 255], + [255, 255, 255]]], dtype=uint8) + >>> labels # doctest: +SKIP + [('circle', ((22, 18), (25, 21))), + ('triangle', ((5, 6), (13, 13)))] + """ + if min_size > image_shape[0] or min_size > image_shape[1]: + raise ValueError('Minimum dimension must be less than ncols and nrows') + max_size = max_size or max(image_shape[0], image_shape[1]) + + if channel_axis is None: + num_channels = 1 + + if intensity_range is None: + intensity_range = (0, 254) if num_channels == 1 else ((0, 254),) + else: + tmp = (intensity_range,) if num_channels == 1 else intensity_range + for intensity_pair in tmp: + for intensity in intensity_pair: + if not (0 <= intensity <= 255): + msg = 'Intensity range must lie within (0, 255) interval' + raise ValueError(msg) + + rng = np.random.default_rng(rng) + user_shape = shape + image_shape = (image_shape[0], image_shape[1], num_channels) + image = np.full(image_shape, 255, dtype=np.uint8) + filled = np.zeros(image_shape, dtype=bool) + labels = [] + + num_shapes = rng.integers(min_shapes, max_shapes + 1) + colors = _generate_random_colors(num_shapes, num_channels, intensity_range, rng) + shape = (min_size, max_size) + for shape_idx in range(num_shapes): + if user_shape is None: + shape_generator = rng.choice(SHAPE_CHOICES) + else: + shape_generator = SHAPE_GENERATORS[user_shape] + for _ in range(num_trials): + # Pick start coordinates. + column = rng.integers(max(1, image_shape[1] - min_size)) + row = rng.integers(max(1, image_shape[0] - min_size)) + point = (row, column) + try: + indices, label = shape_generator(point, image_shape, shape, rng) + except ArithmeticError: + # Couldn't fit the shape, skip it. + indices = [] + continue + # Check if there is an overlap where the mask is nonzero. + if allow_overlap or not filled[indices].any(): + image[indices] = colors[shape_idx] + filled[indices] = True + labels.append(label) + break + else: + warn( + 'Could not fit any shapes to image, ' + 'consider reducing the minimum dimension' + ) + + if channel_axis is None: + image = np.squeeze(image, axis=2) + else: + image = np.moveaxis(image, -1, channel_axis) + + return image, labels diff --git a/envs/kitoverlay/skimage/draw/draw.py b/envs/kitoverlay/skimage/draw/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..92aa235bfb855b3f3aa843ee4e77fb24beddcc36 --- /dev/null +++ b/envs/kitoverlay/skimage/draw/draw.py @@ -0,0 +1,970 @@ +import numpy as np + +from .._shared._geometry import polygon_clip +from .._shared.version_requirements import require +from .._shared.compat import NP_COPY_IF_NEEDED +from ._draw import ( + _coords_inside_image, + _line, + _line_aa, + _polygon, + _ellipse_perimeter, + _circle_perimeter, + _circle_perimeter_aa, + _bezier_curve, +) + + +__doctest_requires__ = {("polygon_perimeter", "rectangle_perimeter"): ["matplotlib"]} + + +def _ellipse_in_shape(shape, center, radii, rotation=0.0): + """Generate coordinates of points within ellipse bounded by shape. + + Parameters + ---------- + shape : iterable of ints + Shape of the input image. Must be at least length 2. Only the first + two values are used to determine the extent of the input image. + center : iterable of floats + (row, column) position of center inside the given shape. + radii : iterable of floats + Size of two half axes (for row and column) + rotation : float, optional + Rotation of the ellipse defined by the above, in radians + in range (-PI, PI), in contra clockwise direction, + with respect to the column-axis. + + Returns + ------- + rows : iterable of ints + Row coordinates representing values within the ellipse. + cols : iterable of ints + Corresponding column coordinates representing values within the ellipse. + """ + r_lim, c_lim = np.ogrid[0 : float(shape[0]), 0 : float(shape[1])] + r_org, c_org = center + r_rad, c_rad = radii + rotation %= np.pi + sin_alpha, cos_alpha = np.sin(rotation), np.cos(rotation) + r, c = (r_lim - r_org), (c_lim - c_org) + distances = ((r * cos_alpha + c * sin_alpha) / r_rad) ** 2 + ( + (r * sin_alpha - c * cos_alpha) / c_rad + ) ** 2 + return np.nonzero(distances < 1) + + +def ellipse(r, c, r_radius, c_radius, shape=None, rotation=0.0): + """Generate coordinates of pixels within ellipse. + + Parameters + ---------- + r, c : double + Centre coordinate of ellipse. + r_radius, c_radius : double + Minor and major semi-axes. ``(r/r_radius)**2 + (c/c_radius)**2 = 1``. + shape : tuple, optional + Image shape which is used to determine the maximum extent of output pixel + coordinates. This is useful for ellipses which exceed the image size. + By default the full extent of the ellipse are used. Must be at least + length 2. Only the first two values are used to determine the extent. + rotation : float, optional (default 0.) + Set the ellipse rotation (rotation) in range (-PI, PI) + in contra clock wise direction, so PI/2 degree means swap ellipse axis + + Returns + ------- + rr, cc : ndarray of int + Pixel coordinates of ellipse. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Examples + -------- + >>> from skimage.draw import ellipse + >>> img = np.zeros((10, 12), dtype=np.uint8) + >>> rr, cc = ellipse(5, 6, 3, 5, rotation=np.deg2rad(30)) + >>> img[rr, cc] = 1 + >>> img + array([[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, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + Notes + ----- + The ellipse equation:: + + ((x * cos(alpha) + y * sin(alpha)) / x_radius) ** 2 + + ((x * sin(alpha) - y * cos(alpha)) / y_radius) ** 2 = 1 + + + Note that the positions of `ellipse` without specified `shape` can have + also, negative values, as this is correct on the plane. On the other hand + using these ellipse positions for an image afterwards may lead to appearing + on the other side of image, because ``image[-1, -1] = image[end-1, end-1]`` + + >>> rr, cc = ellipse(1, 2, 3, 6) + >>> img = np.zeros((6, 12), dtype=np.uint8) + >>> img[rr, cc] = 1 + >>> img + array([[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1]], dtype=uint8) + """ + + center = np.array([r, c]) + radii = np.array([r_radius, c_radius]) + # allow just rotation with in range +/- 180 degree + rotation %= np.pi + + # compute rotated radii by given rotation + r_radius_rot = abs(r_radius * np.cos(rotation)) + c_radius * np.sin(rotation) + c_radius_rot = r_radius * np.sin(rotation) + abs(c_radius * np.cos(rotation)) + # The upper_left and lower_right corners of the smallest rectangle + # containing the ellipse. + radii_rot = np.array([r_radius_rot, c_radius_rot]) + upper_left = np.ceil(center - radii_rot).astype(int) + lower_right = np.floor(center + radii_rot).astype(int) + + if shape is not None: + # Constrain upper_left and lower_right by shape boundary. + upper_left = np.maximum(upper_left, np.array([0, 0])) + lower_right = np.minimum(lower_right, np.array(shape[:2]) - 1) + + shifted_center = center - upper_left + bounding_shape = lower_right - upper_left + 1 + + rr, cc = _ellipse_in_shape(bounding_shape, shifted_center, radii, rotation) + rr.flags.writeable = True + cc.flags.writeable = True + rr += upper_left[0] + cc += upper_left[1] + return rr, cc + + +def disk(center, radius, *, shape=None): + """Generate coordinates of pixels within circle. + + Parameters + ---------- + center : tuple + Center coordinate of disk. + radius : double + Radius of disk. + shape : tuple, optional + Image shape as a tuple of size 2. Determines the maximum + extent of output pixel coordinates. This is useful for disks that + exceed the image size. If None, the full extent of the disk is used. + The shape might result in negative coordinates and wraparound + behaviour. + + Returns + ------- + rr, cc : ndarray of int + Pixel coordinates of disk. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Examples + -------- + >>> import numpy as np + >>> from skimage.draw import disk + >>> shape = (4, 4) + >>> img = np.zeros(shape, dtype=np.uint8) + >>> rr, cc = disk((0, 0), 2, shape=shape) + >>> img[rr, cc] = 1 + >>> img + array([[1, 1, 0, 0], + [1, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0]], dtype=uint8) + >>> img = np.zeros(shape, dtype=np.uint8) + >>> # Negative coordinates in rr and cc perform a wraparound + >>> rr, cc = disk((0, 0), 2, shape=None) + >>> img[rr, cc] = 1 + >>> img + array([[1, 1, 0, 1], + [1, 1, 0, 1], + [0, 0, 0, 0], + [1, 1, 0, 1]], dtype=uint8) + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = disk((4, 4), 5) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + r, c = center + return ellipse(r, c, radius, radius, shape) + + +@require("matplotlib", ">=3.3") +def polygon_perimeter(r, c, shape=None, clip=False): + """Generate polygon perimeter coordinates. + + Parameters + ---------- + r : (N,) ndarray + Row coordinates of vertices of polygon. + c : (N,) ndarray + Column coordinates of vertices of polygon. + shape : tuple, optional + Image shape which is used to determine maximum extents of output pixel + coordinates. This is useful for polygons that exceed the image size. + If None, the full extents of the polygon is used. Must be at least + length 2. Only the first two values are used to determine the extent of + the input image. + clip : bool, optional + Whether to clip the polygon to the provided shape. If this is set + to True, the drawn figure will always be a closed polygon with all + edges visible. + + Returns + ------- + rr, cc : ndarray of int + Pixel coordinates of polygon. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Examples + -------- + >>> from skimage.draw import polygon_perimeter + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = polygon_perimeter([5, -1, 5, 10], + ... [-1, 5, 11, 5], + ... shape=img.shape, clip=True) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 0, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + + """ + if clip: + if shape is None: + raise ValueError("Must specify clipping shape") + clip_box = np.array([0, 0, shape[0] - 1, shape[1] - 1]) + else: + clip_box = np.array([np.min(r), np.min(c), np.max(r), np.max(c)]) + + # Do the clipping irrespective of whether clip is set. This + # ensures that the returned polygon is closed and is an array. + r, c = polygon_clip(r, c, *clip_box) + + r = np.round(r).astype(int) + c = np.round(c).astype(int) + + # Construct line segments + rr, cc = [], [] + for i in range(len(r) - 1): + line_r, line_c = line(r[i], c[i], r[i + 1], c[i + 1]) + rr.extend(line_r) + cc.extend(line_c) + + rr = np.asarray(rr) + cc = np.asarray(cc) + + if shape is None: + return rr, cc + else: + return _coords_inside_image(rr, cc, shape) + + +def set_color(image, coords, color, alpha=1): + """Set pixel color in the image at the given coordinates. + + Note that this function modifies the color of the image in-place. + Coordinates that exceed the shape of the image will be ignored. + + Parameters + ---------- + image : (M, N, C) ndarray + Image + coords : tuple of ((K,) ndarray, (K,) ndarray) + Row and column coordinates of pixels to be colored. + color : (C,) ndarray + Color to be assigned to coordinates in the image. + alpha : scalar or (K,) ndarray + Alpha values used to blend color with image. 0 is transparent, + 1 is opaque. + + Examples + -------- + >>> from skimage.draw import line, set_color + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = line(1, 1, 20, 20) + >>> set_color(img, (rr, cc), 1) + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=uint8) + + """ + rr, cc = coords + + if image.ndim == 2: + image = image[..., np.newaxis] + + color = np.array(color, ndmin=1, copy=NP_COPY_IF_NEEDED) + + if image.shape[-1] != color.shape[-1]: + raise ValueError( + f'Color shape ({color.shape[0]}) must match last ' + 'image dimension ({image.shape[-1]}).' + ) + + if np.isscalar(alpha): + # Can be replaced by ``full_like`` when numpy 1.8 becomes + # minimum dependency + alpha = np.ones_like(rr) * alpha + + rr, cc, alpha = _coords_inside_image(rr, cc, image.shape, val=alpha) + + alpha = alpha[..., np.newaxis] + + color = color * alpha + vals = image[rr, cc] * (1 - alpha) + + image[rr, cc] = vals + color + + +def line(r0, c0, r1, c1): + """Generate line pixel coordinates. + + Parameters + ---------- + r0, c0 : int + Starting position (row, column). + r1, c1 : int + End position (row, column). + + Returns + ------- + rr, cc : (N,) ndarray of int + Indices of pixels that belong to the line. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Notes + ----- + Anti-aliased line generator is available with `line_aa`. + + Examples + -------- + >>> from skimage.draw import line + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = line(1, 1, 8, 8) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + return _line(r0, c0, r1, c1) + + +def line_aa(r0, c0, r1, c1): + """Generate anti-aliased line pixel coordinates. + + Parameters + ---------- + r0, c0 : int + Starting position (row, column). + r1, c1 : int + End position (row, column). + + Returns + ------- + rr, cc, val : (N,) ndarray (int, int, float) + Indices of pixels (`rr`, `cc`) and intensity values (`val`). + ``img[rr, cc] = val``. + + References + ---------- + .. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 + http://members.chello.at/easyfilter/Bresenham.pdf + + Examples + -------- + >>> from skimage.draw import line_aa + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc, val = line_aa(1, 1, 8, 8) + >>> img[rr, cc] = val * 255 + >>> img + array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 255, 74, 0, 0, 0, 0, 0, 0, 0], + [ 0, 74, 255, 74, 0, 0, 0, 0, 0, 0], + [ 0, 0, 74, 255, 74, 0, 0, 0, 0, 0], + [ 0, 0, 0, 74, 255, 74, 0, 0, 0, 0], + [ 0, 0, 0, 0, 74, 255, 74, 0, 0, 0], + [ 0, 0, 0, 0, 0, 74, 255, 74, 0, 0], + [ 0, 0, 0, 0, 0, 0, 74, 255, 74, 0], + [ 0, 0, 0, 0, 0, 0, 0, 74, 255, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + return _line_aa(r0, c0, r1, c1) + + +def polygon(r, c, shape=None): + """Generate coordinates of pixels inside a polygon. + + Parameters + ---------- + r : (N,) array_like + Row coordinates of the polygon's vertices. + c : (N,) array_like + Column coordinates of the polygon's vertices. + shape : tuple, optional + Image shape which is used to determine the maximum extent of output + pixel coordinates. This is useful for polygons that exceed the image + size. If None, the full extent of the polygon is used. Must be at + least length 2. Only the first two values are used to determine the + extent of the input image. + + Returns + ------- + rr, cc : ndarray of int + Pixel coordinates of polygon. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + See Also + -------- + polygon2mask: + Create a binary mask from a polygon. + + Notes + ----- + This function ensures that `rr` and `cc` don't contain negative values. + Pixels of the polygon that whose coordinates are smaller 0, are not drawn. + + Examples + -------- + >>> import skimage as ski + >>> r = np.array([1, 2, 8]) + >>> c = np.array([1, 7, 4]) + >>> rr, cc = ski.draw.polygon(r, c) + >>> img = np.zeros((10, 10), dtype=int) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + + If the image `shape` is defined and vertices / points of the `polygon` are + outside this coordinate space, only a part (or none at all) of the polygon's + pixels is returned. Shifting the polygon's vertices by an offset can be used + to move the polygon around and potentially draw an arbitrary sub-region of + the polygon. + + >>> offset = (2, -4) + >>> rr, cc = ski.draw.polygon(r - offset[0], c - offset[1], shape=img.shape) + >>> img = np.zeros((10, 10), dtype=int) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 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]]) + """ + return _polygon(r, c, shape) + + +def circle_perimeter(r, c, radius, method='bresenham', shape=None): + """Generate circle perimeter coordinates. + + Parameters + ---------- + r, c : int + Centre coordinate of circle. + radius : int + Radius of circle. + method : {'bresenham', 'andres'}, optional + bresenham : Bresenham method (default) + andres : Andres method + shape : tuple, optional + Image shape which is used to determine the maximum extent of output + pixel coordinates. This is useful for circles that exceed the image + size. If None, the full extent of the circle is used. Must be at least + length 2. Only the first two values are used to determine the extent of + the input image. + + Returns + ------- + rr, cc : (N,) ndarray of int + Bresenham and Andres' method: + Indices of pixels that belong to the circle perimeter. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Notes + ----- + Andres method presents the advantage that concentric + circles create a disc whereas Bresenham can make holes. There + is also less distortions when Andres circles are rotated. + Bresenham method is also known as midpoint circle algorithm. + Anti-aliased circle generator is available with `circle_perimeter_aa`. + + References + ---------- + .. [1] J.E. Bresenham, "Algorithm for computer control of a digital + plotter", IBM Systems journal, 4 (1965) 25-30. + .. [2] E. Andres, "Discrete circles, rings and spheres", Computers & + Graphics, 18 (1994) 695-706. + + Examples + -------- + >>> from skimage.draw import circle_perimeter + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = circle_perimeter(4, 4, 3) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + return _circle_perimeter(r, c, radius, method, shape) + + +def circle_perimeter_aa(r, c, radius, shape=None): + """Generate anti-aliased circle perimeter coordinates. + + Parameters + ---------- + r, c : int + Centre coordinate of circle. + radius : int + Radius of circle. + shape : tuple, optional + Image shape which is used to determine the maximum extent of output + pixel coordinates. This is useful for circles that exceed the image + size. If None, the full extent of the circle is used. Must be at least + length 2. Only the first two values are used to determine the extent of + the input image. + + Returns + ------- + rr, cc, val : (N,) ndarray (int, int, float) + Indices of pixels (`rr`, `cc`) and intensity values (`val`). + ``img[rr, cc] = val``. + + Notes + ----- + Wu's method draws anti-aliased circle. This implementation doesn't use + lookup table optimization. + + Use the function ``draw.set_color`` to apply ``circle_perimeter_aa`` + results to color images. + + References + ---------- + .. [1] X. Wu, "An efficient antialiasing technique", In ACM SIGGRAPH + Computer Graphics, 25 (1991) 143-152. + + Examples + -------- + >>> from skimage.draw import circle_perimeter_aa + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc, val = circle_perimeter_aa(4, 4, 3) + >>> img[rr, cc] = val * 255 + >>> img + array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0], + [ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0], + [ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0], + [ 0, 255, 0, 0, 0, 0, 0, 255, 0, 0], + [ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0], + [ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0], + [ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + >>> from skimage import data, draw + >>> image = data.chelsea() + >>> rr, cc, val = draw.circle_perimeter_aa(r=100, c=100, radius=75) + >>> draw.set_color(image, (rr, cc), [1, 0, 0], alpha=val) + """ + return _circle_perimeter_aa(r, c, radius, shape) + + +def ellipse_perimeter(r, c, r_radius, c_radius, orientation=0, shape=None): + """Generate ellipse perimeter coordinates. + + Parameters + ---------- + r, c : int + Centre coordinate of ellipse. + r_radius, c_radius : int + Minor and major semi-axes. ``(r/r_radius)**2 + (c/c_radius)**2 = 1``. + orientation : double, optional + Major axis orientation in clockwise direction as radians. + shape : tuple, optional + Image shape which is used to determine the maximum extent of output + pixel coordinates. This is useful for ellipses that exceed the image + size. If None, the full extent of the ellipse is used. Must be at + least length 2. Only the first two values are used to determine the + extent of the input image. + + Returns + ------- + rr, cc : (N,) ndarray of int + Indices of pixels that belong to the ellipse perimeter. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + References + ---------- + .. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 + http://members.chello.at/easyfilter/Bresenham.pdf + + Examples + -------- + >>> from skimage.draw import ellipse_perimeter + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = ellipse_perimeter(5, 5, 3, 4) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + + Note that the positions of `ellipse` without specified `shape` can have + also, negative values, as this is correct on the plane. On the other hand + using these ellipse positions for an image afterwards may lead to appearing + on the other side of image, because ``image[-1, -1] = image[end-1, end-1]`` + + >>> rr, cc = ellipse_perimeter(2, 3, 4, 5) + >>> img = np.zeros((9, 12), dtype=np.uint8) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=uint8) + """ + return _ellipse_perimeter(r, c, r_radius, c_radius, orientation, shape) + + +def bezier_curve(r0, c0, r1, c1, r2, c2, weight, shape=None): + """Generate Bezier curve coordinates. + + Parameters + ---------- + r0, c0 : int + Coordinates of the first control point. + r1, c1 : int + Coordinates of the middle control point. + r2, c2 : int + Coordinates of the last control point. + weight : double + Middle control point weight, it describes the line tension. + shape : tuple, optional + Image shape which is used to determine the maximum extent of output + pixel coordinates. This is useful for curves that exceed the image + size. If None, the full extent of the curve is used. + + Returns + ------- + rr, cc : (N,) ndarray of int + Indices of pixels that belong to the Bezier curve. + May be used to directly index into an array, e.g. + ``img[rr, cc] = 1``. + + Notes + ----- + The algorithm is the rational quadratic algorithm presented in + reference [1]_. + + References + ---------- + .. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 + http://members.chello.at/easyfilter/Bresenham.pdf + + Examples + -------- + >>> import numpy as np + >>> from skimage.draw import bezier_curve + >>> img = np.zeros((10, 10), dtype=np.uint8) + >>> rr, cc = bezier_curve(1, 5, 5, -2, 8, 8, 2) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + return _bezier_curve(r0, c0, r1, c1, r2, c2, weight, shape) + + +def rectangle(start, end=None, extent=None, shape=None): + """Generate coordinates of pixels within a rectangle. + + Parameters + ---------- + start : tuple + Origin point of the rectangle, e.g., ``([plane,] row, column)``. + end : tuple + End point of the rectangle ``([plane,] row, column)``. + For a 2D matrix, the slice defined by the rectangle is + ``[start:(end+1)]``. + Either `end` or `extent` must be specified. + extent : tuple + The extent (size) of the drawn rectangle. E.g., + ``([num_planes,] num_rows, num_cols)``. + Either `end` or `extent` must be specified. + A negative extent is valid, and will result in a rectangle + going along the opposite direction. If extent is negative, the + `start` point is not included. + shape : tuple, optional + Image shape used to determine the maximum bounds of the output + coordinates. This is useful for clipping rectangles that exceed + the image size. By default, no clipping is done. + + Returns + ------- + coords : array of int, shape (Ndim, Npoints) + The coordinates of all pixels in the rectangle. + + Notes + ----- + This function can be applied to N-dimensional images, by passing `start` and + `end` or `extent` as tuples of length N. + + Examples + -------- + >>> import numpy as np + >>> from skimage.draw import rectangle + >>> img = np.zeros((5, 5), dtype=np.uint8) + >>> start = (1, 1) + >>> extent = (3, 3) + >>> rr, cc = rectangle(start, extent=extent, shape=img.shape) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + + >>> img = np.zeros((5, 5), dtype=np.uint8) + >>> start = (0, 1) + >>> end = (3, 3) + >>> rr, cc = rectangle(start, end=end, shape=img.shape) + >>> img[rr, cc] = 1 + >>> img + array([[0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + >>> import numpy as np + >>> from skimage.draw import rectangle + >>> img = np.zeros((6, 6), dtype=np.uint8) + >>> start = (3, 3) + >>> + >>> rr, cc = rectangle(start, extent=(2, 2)) + >>> img[rr, cc] = 1 + >>> rr, cc = rectangle(start, extent=(-2, 2)) + >>> img[rr, cc] = 2 + >>> rr, cc = rectangle(start, extent=(-2, -2)) + >>> img[rr, cc] = 3 + >>> rr, cc = rectangle(start, extent=(2, -2)) + >>> img[rr, cc] = 4 + >>> print(img) + [[0 0 0 0 0 0] + [0 3 3 2 2 0] + [0 3 3 2 2 0] + [0 4 4 1 1 0] + [0 4 4 1 1 0] + [0 0 0 0 0 0]] + + """ + tl, br = _rectangle_slice(start=start, end=end, extent=extent) + + if shape is not None: + n_dim = len(start) + br = np.minimum(shape[0:n_dim], br) + tl = np.maximum(np.zeros_like(shape[0:n_dim]), tl) + coords = np.meshgrid(*[np.arange(st, en) for st, en in zip(tuple(tl), tuple(br))]) + return coords + + +@require("matplotlib", ">=3.3") +def rectangle_perimeter(start, end=None, extent=None, shape=None, clip=False): + """Generate coordinates of pixels that are exactly around a rectangle. + + Parameters + ---------- + start : tuple + Origin point of the inner rectangle, e.g., ``(row, column)``. + end : tuple + End point of the inner rectangle ``(row, column)``. + For a 2D matrix, the slice defined by inner the rectangle is + ``[start:(end+1)]``. + Either `end` or `extent` must be specified. + extent : tuple + The extent (size) of the inner rectangle. E.g., + ``(num_rows, num_cols)``. + Either `end` or `extent` must be specified. + Negative extents are permitted. See `rectangle` to better + understand how they behave. + shape : tuple, optional + Image shape used to determine the maximum bounds of the output + coordinates. This is useful for clipping perimeters that exceed + the image size. By default, no clipping is done. Must be at least + length 2. Only the first two values are used to determine the extent of + the input image. + clip : bool, optional + Whether to clip the perimeter to the provided shape. If this is set + to True, the drawn figure will always be a closed polygon with all + edges visible. + + Returns + ------- + coords : array of int, shape (2, Npoints) + The coordinates of all pixels in the rectangle. + + Examples + -------- + >>> import numpy as np + >>> from skimage.draw import rectangle_perimeter + >>> img = np.zeros((5, 6), dtype=np.uint8) + >>> start = (2, 3) + >>> end = (3, 4) + >>> rr, cc = rectangle_perimeter(start, end=end, shape=img.shape) + >>> img[rr, cc] = 1 + >>> img + array([[0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1], + [0, 0, 1, 0, 0, 1], + [0, 0, 1, 0, 0, 1], + [0, 0, 1, 1, 1, 1]], dtype=uint8) + + >>> img = np.zeros((5, 5), dtype=np.uint8) + >>> r, c = rectangle_perimeter(start, (10, 10), shape=img.shape, clip=True) + >>> img[r, c] = 1 + >>> img + array([[0, 0, 0, 0, 0], + [0, 0, 1, 1, 1], + [0, 0, 1, 0, 1], + [0, 0, 1, 0, 1], + [0, 0, 1, 1, 1]], dtype=uint8) + + """ + top_left, bottom_right = _rectangle_slice(start=start, end=end, extent=extent) + + top_left -= 1 + r = [top_left[0], top_left[0], bottom_right[0], bottom_right[0], top_left[0]] + c = [top_left[1], bottom_right[1], bottom_right[1], top_left[1], top_left[1]] + return polygon_perimeter(r, c, shape=shape, clip=clip) + + +def _rectangle_slice(start, end=None, extent=None): + """Return the slice ``(top_left, bottom_right)`` of the rectangle. + + Returns + ------- + (top_left, bottom_right) + The slice you would need to select the region in the rectangle defined + by the parameters. + Select it like: + + ``rect[top_left[0]:bottom_right[0], top_left[1]:bottom_right[1]]`` + """ + if end is None and extent is None: + raise ValueError("Either `end` or `extent` must be given.") + if end is not None and extent is not None: + raise ValueError("Cannot provide both `end` and `extent`.") + + if extent is not None: + end = np.asarray(start) + np.asarray(extent) + top_left = np.minimum(start, end) + bottom_right = np.maximum(start, end) + + top_left = np.round(top_left).astype(int) + bottom_right = np.round(bottom_right).astype(int) + + if extent is None: + bottom_right += 1 + + return (top_left, bottom_right) diff --git a/envs/kitoverlay/skimage/draw/draw3d.py b/envs/kitoverlay/skimage/draw/draw3d.py new file mode 100644 index 0000000000000000000000000000000000000000..22aa389c58d8cc4cd65710ed630df88cb9e28b3c --- /dev/null +++ b/envs/kitoverlay/skimage/draw/draw3d.py @@ -0,0 +1,107 @@ +import numpy as np +from scipy.special import elliprg + + +def ellipsoid(a, b, c, spacing=(1.0, 1.0, 1.0), levelset=False): + """Generate ellipsoid for given semi-axis lengths. + + The respective semi-axis lengths are given along three dimensions in + Cartesian coordinates. Each dimension may use a different grid spacing. + + Parameters + ---------- + a : float + Length of semi-axis along x-axis. + b : float + Length of semi-axis along y-axis. + c : float + Length of semi-axis along z-axis. + spacing : 3-tuple of floats + Grid spacing in three spatial dimensions. + levelset : bool + If True, returns the level set for this ellipsoid (signed level + set about zero, with positive denoting interior) as np.float64. + False returns a binarized version of said level set. + + Returns + ------- + ellipsoid : (M, N, P) array + Ellipsoid centered in a correctly sized array for given `spacing`. + Boolean dtype unless `levelset=True`, in which case a float array is + returned with the level set above 0.0 representing the ellipsoid. + + """ + if (a <= 0) or (b <= 0) or (c <= 0): + raise ValueError('Parameters a, b, and c must all be > 0') + + offset = np.r_[1, 1, 1] * np.r_[spacing] + + # Calculate limits, and ensure output volume is odd & symmetric + low = np.ceil(-np.r_[a, b, c] - offset) + high = np.floor(np.r_[a, b, c] + offset + 1) + + for dim in range(3): + if (high[dim] - low[dim]) % 2 == 0: + low[dim] -= 1 + num = np.arange(low[dim], high[dim], spacing[dim]) + if 0 not in num: + low[dim] -= np.max(num[num < 0]) + + # Generate (anisotropic) spatial grid + x, y, z = np.mgrid[ + low[0] : high[0] : spacing[0], + low[1] : high[1] : spacing[1], + low[2] : high[2] : spacing[2], + ] + + if not levelset: + arr = ((x / float(a)) ** 2 + (y / float(b)) ** 2 + (z / float(c)) ** 2) <= 1 + else: + arr = ((x / float(a)) ** 2 + (y / float(b)) ** 2 + (z / float(c)) ** 2) - 1 + + return arr + + +def ellipsoid_stats(a, b, c): + """Calculate analytical volume and surface area of an ellipsoid. + + The surface area of an ellipsoid is given by + + .. math:: S=4\\pi b c R_G\\!\\left(1, \\frac{a^2}{b^2}, \\frac{a^2}{c^2}\\right) + + where :math:`R_G` is Carlson's completely symmetric elliptic integral of + the second kind [1]_. The latter is implemented as + :py:func:`scipy.special.elliprg`. + + Parameters + ---------- + a : float + Length of semi-axis along x-axis. + b : float + Length of semi-axis along y-axis. + c : float + Length of semi-axis along z-axis. + + Returns + ------- + vol : float + Calculated volume of ellipsoid. + surf : float + Calculated surface area of ellipsoid. + + References + ---------- + .. [1] Paul Masson (2020). Surface Area of an Ellipsoid. + https://analyticphysics.com/Mathematical%20Methods/Surface%20Area%20of%20an%20Ellipsoid.htm + + """ + if (a <= 0) or (b <= 0) or (c <= 0): + raise ValueError('Parameters a, b, and c must all be > 0') + + # Volume + vol = 4 / 3.0 * np.pi * a * b * c + + # Surface area + surf = 3 * vol * elliprg(1 / a**2, 1 / b**2, 1 / c**2) + + return vol, surf diff --git a/envs/kitoverlay/skimage/draw/draw_nd.py b/envs/kitoverlay/skimage/draw/draw_nd.py new file mode 100644 index 0000000000000000000000000000000000000000..6e552a3a631423fca51413bb9c1403bcf6594d2d --- /dev/null +++ b/envs/kitoverlay/skimage/draw/draw_nd.py @@ -0,0 +1,108 @@ +import numpy as np + + +def _round_safe(coords): + """Round coords while ensuring successive values are less than 1 apart. + + When rounding coordinates for `line_nd`, we want coordinates that are less + than 1 apart (always the case, by design) to remain less than one apart. + However, NumPy rounds values to the nearest *even* integer, so: + + >>> np.round([0.5, 1.5, 2.5, 3.5, 4.5]) + array([0., 2., 2., 4., 4.]) + + So, for our application, we detect whether the above case occurs, and use + ``np.floor`` if so. It is sufficient to detect that the first coordinate + falls on 0.5 and that the second coordinate is 1.0 apart, since we assume + by construction that the inter-point distance is less than or equal to 1 + and that all successive points are equidistant. + + Parameters + ---------- + coords : 1D array of float + The coordinates array. We assume that all successive values are + equidistant (``np.all(np.diff(coords) = coords[1] - coords[0])``) + and that this distance is no more than 1 + (``np.abs(coords[1] - coords[0]) <= 1``). + + Returns + ------- + rounded : 1D array of int + The array correctly rounded for an indexing operation, such that no + successive indices will be more than 1 apart. + + Examples + -------- + >>> coords0 = np.array([0.5, 1.25, 2., 2.75, 3.5]) + >>> _round_safe(coords0) + array([0, 1, 2, 3, 4]) + >>> coords1 = np.arange(0.5, 8, 1) + >>> coords1 + array([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]) + >>> _round_safe(coords1) + array([0, 1, 2, 3, 4, 5, 6, 7]) + """ + if len(coords) > 1 and coords[0] % 1 == 0.5 and coords[1] - coords[0] == 1: + _round_function = np.floor + else: + _round_function = np.round + return _round_function(coords).astype(int) + + +def line_nd(start, stop, *, endpoint=False, integer=True): + """Draw a single-pixel thick line in n dimensions. + + The line produced will be ndim-connected. That is, two subsequent + pixels in the line will be either direct or diagonal neighbors in + n dimensions. + + Parameters + ---------- + start : array-like, shape (N,) + The start coordinates of the line. + stop : array-like, shape (N,) + The end coordinates of the line. + endpoint : bool, optional + Whether to include the endpoint in the returned line. Defaults + to False, which allows for easy drawing of multi-point paths. + integer : bool, optional + Whether to round the coordinates to integer. If True (default), + the returned coordinates can be used to directly index into an + array. `False` could be used for e.g. vector drawing. + + Returns + ------- + coords : tuple of arrays + The coordinates of points on the line. + + Examples + -------- + >>> lin = line_nd((1, 1), (5, 2.5), endpoint=False) + >>> lin + (array([1, 2, 3, 4]), array([1, 1, 2, 2])) + >>> im = np.zeros((6, 5), dtype=int) + >>> im[lin] = 1 + >>> im + array([[0, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + >>> line_nd([2, 1, 1], [5, 5, 2.5], endpoint=True) + (array([2, 3, 4, 4, 5]), array([1, 2, 3, 4, 5]), array([1, 1, 2, 2, 2])) + """ + start = np.asarray(start) + stop = np.asarray(stop) + npoints = int(np.ceil(np.max(np.abs(stop - start)))) + if endpoint: + npoints += 1 + + coords = np.linspace(start, stop, num=npoints, endpoint=endpoint).T + if integer: + for dim in range(len(start)): + coords[dim, :] = _round_safe(coords[dim, :]) + + coords = coords.astype(int) + + return tuple(coords) diff --git a/envs/kitoverlay/skimage/feature/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bafc2f51357bbc5749d1175c889d76ae6a4b66c Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_basic_features.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_basic_features.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06026d772f6595817216ce86af670252e9ea0273 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_basic_features.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_canny.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_canny.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4890d06aead824c0b0dc3a9cde2336bbde55666 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_canny.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_fisher_vector.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_fisher_vector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d868bbdea49ab5bf79bcaf612dac38642772f0e Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_fisher_vector.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_orb_descriptor_positions.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_orb_descriptor_positions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d9229bd962d1e062f644ee8236d020d461b3a05 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_orb_descriptor_positions.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/blob.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/blob.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a5021a51d430ebc8b695d8671ba337276d4aafa Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/blob.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/corner.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/corner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57f85a8055f8d11a54a7333022c8209912415d08 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/corner.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/haar.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/haar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c3aba53f28af2a788ef576539140ff9cee8c7fd Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/haar.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/match.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/match.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79f629ad6b3ac1b2e95b2b7b5fcea613c88c5a4d Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/match.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/sift.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/sift.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d68329827d595f27b45fbb2301f0997b0ea3ffe Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/sift.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/texture.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/texture.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40114abbcacc4eb8e9cf49c640b979fd112480e1 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/texture.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/util.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2159595e49d8e2f275a8ebf953f1011bbcfcc86 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/util.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__init__.py b/envs/kitoverlay/skimage/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..190c1e2f35f9b3090dd42d28e7ff8c3ccd709e8b --- /dev/null +++ b/envs/kitoverlay/skimage/io/__init__.py @@ -0,0 +1,43 @@ +"""Reading and saving of images and videos.""" + +import warnings + +from .manage_plugins import * +from .manage_plugins import _hide_plugin_deprecation_warnings +from .sift import * +from .collection import * + +from ._io import * +from ._image_stack import * + + +with _hide_plugin_deprecation_warnings(): + reset_plugins() + + +__all__ = [ + "concatenate_images", + "imread", + "imread_collection", + "imread_collection_wrapper", + "imsave", + "load_sift", + "load_surf", + "pop", + "push", + "ImageCollection", + "MultiImage", +] + + +def __getattr__(name): + if name == "available_plugins": + warnings.warn( + "`available_plugins` is deprecated since version 0.25 and will " + "be removed in version 0.27. Instead, use `imageio` or other " + "I/O packages directly.", + category=FutureWarning, + stacklevel=2, + ) + return globals()["_available_plugins"] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/envs/kitoverlay/skimage/io/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761b765f80e47571943406c190af533188894489 Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/_image_stack.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/_image_stack.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89565fdcbc6812c02b06eee9c83c42962e97092f Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/_image_stack.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/_io.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/_io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb4cbbcc22bd7057a8f17a4ab13c5658fb73d205 Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/_io.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/collection.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..285a8ffbd5ff07f5ae03299418fac334ceb16a3b Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/collection.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/manage_plugins.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/manage_plugins.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bcd32413006c514ddf4f26b4f84597eafe12561 Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/manage_plugins.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/sift.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/sift.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df812feec3295fd9a624d47a8d20499f00e04587 Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/sift.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/__pycache__/util.cpython-311.pyc b/envs/kitoverlay/skimage/io/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30fa27821dfb1351aa4ac2f1d10f39d1944ccebe Binary files /dev/null and b/envs/kitoverlay/skimage/io/__pycache__/util.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_image_stack.py b/envs/kitoverlay/skimage/io/_image_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..ca9896d5d866217b9b07ffc3010e8b6eb6b6842a --- /dev/null +++ b/envs/kitoverlay/skimage/io/_image_stack.py @@ -0,0 +1,35 @@ +import numpy as np + + +__all__ = ['image_stack', 'push', 'pop'] + + +# Shared image queue +image_stack = [] + + +def push(img): + """Push an image onto the shared image stack. + + Parameters + ---------- + img : ndarray + Image to push. + + """ + if not isinstance(img, np.ndarray): + raise ValueError("Can only push ndarrays to the image stack.") + + image_stack.append(img) + + +def pop(): + """Pop an image from the shared image stack. + + Returns + ------- + img : ndarray + Image popped from the stack. + + """ + return image_stack.pop() diff --git a/envs/kitoverlay/skimage/io/_io.py b/envs/kitoverlay/skimage/io/_io.py new file mode 100644 index 0000000000000000000000000000000000000000..02f15171dd2099350e5c126ad592b7f42c242d9c --- /dev/null +++ b/envs/kitoverlay/skimage/io/_io.py @@ -0,0 +1,286 @@ +import pathlib +import warnings + +import numpy as np + +from .._shared.utils import warn, deprecate_func, deprecate_parameter, DEPRECATED +from .._shared.version_requirements import require +from ..exposure import is_low_contrast +from ..color.colorconv import rgb2gray, rgba2rgb +from ..io.manage_plugins import call_plugin, _hide_plugin_deprecation_warnings +from .util import file_or_url_context + +__all__ = [ + 'imread', + 'imsave', + 'imshow', + 'show', + 'imread_collection', + 'imshow_collection', +] + + +_remove_plugin_param_template = ( + "The plugin infrastructure in `skimage.io` and the parameter " + "`{deprecated_name}` are 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}`. Instead, use `imageio` " + "or other I/O packages directly. See also `{func_name}`." +) + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imread(fname, as_gray=False, plugin=DEPRECATED, **plugin_args): + """Load an image from file. + + Parameters + ---------- + fname : str or pathlib.Path + Image file name, e.g. ``test.jpg`` or URL. + as_gray : bool, optional + If True, convert color images to gray-scale (64-bit floats). + Images that are already in gray-scale format are not converted. + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + + Returns + ------- + img_array : ndarray + The different color bands/channels are stored in the + third dimension, such that a gray-image is MxN, an + RGB-image MxNx3 and an RGBA-image MxNx4. + + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imread`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + + if isinstance(fname, pathlib.Path): + fname = str(fname.resolve()) + + if plugin is None and hasattr(fname, 'lower'): + if fname.lower().endswith(('.tiff', '.tif')): + plugin = 'tifffile' + + with file_or_url_context(fname) as fname, _hide_plugin_deprecation_warnings(): + img = call_plugin('imread', fname, plugin=plugin, **plugin_args) + + if not hasattr(img, 'ndim'): + return img + + if img.ndim > 2: + if img.shape[-1] not in (3, 4) and img.shape[-3] in (3, 4): + img = np.swapaxes(img, -1, -3) + img = np.swapaxes(img, -2, -3) + + if as_gray: + if img.shape[2] == 4: + img = rgba2rgb(img) + img = rgb2gray(img) + + return img + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imread_collection( + load_pattern, conserve_memory=True, plugin=DEPRECATED, **plugin_args +): + """ + Load a collection of images. + + Parameters + ---------- + load_pattern : str or list + List of objects to load. These are usually filenames, but may + vary depending on the currently active plugin. See :class:`ImageCollection` + for the default behaviour of this parameter. + conserve_memory : bool, optional + If True, never keep more than one in memory at a specific + time. Otherwise, images will be cached once they are loaded. + + Returns + ------- + ic : :class:`ImageCollection` + Collection of images. + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imread_collection`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + with _hide_plugin_deprecation_warnings(): + return call_plugin( + 'imread_collection', + load_pattern, + conserve_memory, + plugin=plugin, + **plugin_args, + ) + + +@deprecate_parameter( + "plugin", + start_version="0.25", + stop_version="0.27", + template=_remove_plugin_param_template, +) +def imsave(fname, arr, plugin=DEPRECATED, *, check_contrast=True, **plugin_args): + """Save an image to file. + + Parameters + ---------- + fname : str or pathlib.Path + Target filename. + arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4) + Image data. + check_contrast : bool, optional + Check for low contrast and print warning (default: True). + + Other Parameters + ---------------- + plugin_args : DEPRECATED + The plugin infrastructure is deprecated. + """ + if plugin is DEPRECATED: + plugin = None + if plugin_args: + msg = ( + "The plugin infrastructure in `skimage.io` is deprecated since " + "version 0.25 and will be removed in 0.27 (or later). To avoid " + "this warning, please do not pass additional keyword arguments " + "for plugins (`**plugin_args`). Instead, use `imageio` or other " + "I/O packages directly. See also `skimage.io.imsave`." + ) + warnings.warn(msg, category=FutureWarning, stacklevel=3) + + if isinstance(fname, pathlib.Path): + fname = str(fname.resolve()) + if plugin is None and hasattr(fname, 'lower'): + if fname.lower().endswith(('.tiff', '.tif')): + plugin = 'tifffile' + if arr.dtype == bool: + warn( + f'{fname} is a boolean image: setting True to 255 and False to 0. ' + 'To silence this warning, please convert the image using ' + 'img_as_ubyte.', + stacklevel=3, + ) + arr = arr.astype('uint8') * 255 + if check_contrast and is_low_contrast(arr): + warn(f'{fname} is a low contrast image') + + with _hide_plugin_deprecation_warnings(): + return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def imshow(arr, plugin=None, **plugin_args): + """Display an image. + + Parameters + ---------- + arr : ndarray or str + Image data or name of image file. + plugin : str + Name of plugin to use. By default, the different plugins are + tried (starting with imageio) until a suitable candidate is found. + + Other Parameters + ---------------- + plugin_args : keywords + Passed to the given plugin. + + """ + if isinstance(arr, str): + arr = call_plugin('imread', arr, plugin=plugin) + with _hide_plugin_deprecation_warnings(): + return call_plugin('imshow', arr, plugin=plugin, **plugin_args) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def imshow_collection(ic, plugin=None, **plugin_args): + """Display a collection of images. + + Parameters + ---------- + ic : :class:`ImageCollection` + Collection to display. + + Other Parameters + ---------------- + plugin_args : keywords + Passed to the given plugin. + + """ + with _hide_plugin_deprecation_warnings(): + return call_plugin('imshow_collection', ic, plugin=plugin, **plugin_args) + + +@require("matplotlib", ">=3.3") +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Please use `matplotlib`, `napari`, etc. to visualize images.", +) +def show(): + """Display pending images. + + Launch the event loop of the current GUI plugin, and display all + pending images, queued via `imshow`. This is required when using + `imshow` from non-interactive scripts. + + A call to `show` will block execution of code until all windows + have been closed. + + Examples + -------- + >>> import skimage.io as io + >>> rng = np.random.default_rng() + >>> for i in range(4): + ... ax_im = io.imshow(rng.random((50, 50))) # doctest: +SKIP + >>> io.show() # doctest: +SKIP + + """ + with _hide_plugin_deprecation_warnings(): + return call_plugin('_app_show') diff --git a/envs/kitoverlay/skimage/io/_plugins/__init__.py b/envs/kitoverlay/skimage/io/_plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d96cd345e000d59be8ac09440d5684ac5ab4494f Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/fits_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/fits_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4eb54ebaf8bf1d26566dd7a4c5fab872779039eb Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/fits_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/gdal_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/gdal_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adb8da90c9fb0d3fcd6ad9c79defeed4da522f57 Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/gdal_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/imageio_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/imageio_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bc7105fcb3da4d89e73e5fe31852ea37153dc56 Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/imageio_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/imread_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/imread_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dae36cbde571a41da8a62407b6cbd524568714ca Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/imread_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/matplotlib_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/matplotlib_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c6e1fa265519111c1def3744d42165246237fd Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/matplotlib_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/pil_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/pil_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2791d3e8e4180235d4eed661b37dc0d787e93bc9 Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/pil_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/simpleitk_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/simpleitk_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f3773d4e7b0aa1f8f1743fd42629a04e44690d8 Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/simpleitk_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/__pycache__/tifffile_plugin.cpython-311.pyc b/envs/kitoverlay/skimage/io/_plugins/__pycache__/tifffile_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fba2988c536372db28db569359d09db78e14bf8 Binary files /dev/null and b/envs/kitoverlay/skimage/io/_plugins/__pycache__/tifffile_plugin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/io/_plugins/fits_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/fits_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..1872c252ef089296a7d52641f8ae514aecbd364c --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/fits_plugin.ini @@ -0,0 +1,3 @@ +[fits] +description = FITS image reading via PyFITS +provides = imread, imread_collection diff --git a/envs/kitoverlay/skimage/io/_plugins/fits_plugin.py b/envs/kitoverlay/skimage/io/_plugins/fits_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..c97237cecb19776205c9917cdedda53c0c7f4c98 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/fits_plugin.py @@ -0,0 +1,135 @@ +__all__ = ['imread', 'imread_collection'] + +import skimage.io as io + +try: + from astropy.io import fits +except ImportError: + raise ImportError( + "Astropy could not be found. It is needed to read FITS files.\n" + "Please refer to https://www.astropy.org for installation\n" + "instructions." + ) + + +def imread(fname): + """Load an image from a FITS file. + + Parameters + ---------- + fname : string + Image file name, e.g. ``test.fits``. + + Returns + ------- + img_array : ndarray + Unlike plugins such as PIL, where different color bands/channels are + stored in the third dimension, FITS images are grayscale-only and can + be N-dimensional, so an array of the native FITS dimensionality is + returned, without color channels. + + Currently if no image is found in the file, None will be returned + + Notes + ----- + Currently FITS ``imread()`` always returns the first image extension when + given a Multi-Extension FITS file; use ``imread_collection()`` (which does + lazy loading) to get all the extensions at once. + + """ + + with fits.open(fname) as hdulist: + # Iterate over FITS image extensions, ignoring any other extension types + # such as binary tables, and get the first image data array: + img_array = None + for hdu in hdulist: + if isinstance(hdu, fits.ImageHDU) or isinstance(hdu, fits.PrimaryHDU): + if hdu.data is not None: + img_array = hdu.data + break + + return img_array + + +def imread_collection(load_pattern, conserve_memory=True): + """Load a collection of images from one or more FITS files + + Parameters + ---------- + load_pattern : str or list + List of extensions to load. Filename globbing is currently + unsupported. + conserve_memory : bool + If True, never keep more than one in memory at a specific + time. Otherwise, images will be cached once they are loaded. + + Returns + ------- + ic : ImageCollection + Collection of images. + + """ + + intype = type(load_pattern) + if intype is not list and intype is not str: + raise TypeError("Input must be a filename or list of filenames") + + # Ensure we have a list, otherwise we'll end up iterating over the string: + if intype is not list: + load_pattern = [load_pattern] + + # Generate a list of filename/extension pairs by opening the list of + # files and finding the image extensions in each one: + ext_list = [] + for filename in load_pattern: + with fits.open(filename) as hdulist: + for n, hdu in zip(range(len(hdulist)), hdulist): + if isinstance(hdu, fits.ImageHDU) or isinstance(hdu, fits.PrimaryHDU): + # Ignore (primary) header units with no data (use '.size' + # rather than '.data' to avoid actually loading the image): + try: + data_size = hdu.size # size is int in Astropy 3.1.2 + except TypeError: + data_size = hdu.size() + if data_size > 0: + ext_list.append((filename, n)) + + return io.ImageCollection( + ext_list, load_func=FITSFactory, conserve_memory=conserve_memory + ) + + +def FITSFactory(image_ext): + """Load an image extension from a FITS file and return a NumPy array + + Parameters + ---------- + image_ext : tuple + FITS extension to load, in the format ``(filename, ext_num)``. + The FITS ``(extname, extver)`` format is unsupported, since this + function is not called directly by the user and + ``imread_collection()`` does the work of figuring out which + extensions need loading. + + """ + + # Expect a length-2 tuple with a filename as the first element: + if not isinstance(image_ext, tuple): + raise TypeError("Expected a tuple") + + if len(image_ext) != 2: + raise ValueError("Expected a tuple of length 2") + + filename = image_ext[0] + extnum = image_ext[1] + + if not (isinstance(filename, str) and isinstance(extnum, int)): + raise ValueError("Expected a (filename, extension) tuple") + + with fits.open(filename) as hdulist: + data = hdulist[extnum].data + + if data is None: + raise RuntimeError(f"Extension {extnum} of {filename} has no data") + + return data diff --git a/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..1669097b022040f8211840a3bedabf03ed1da0b8 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.ini @@ -0,0 +1,3 @@ +[gdal] +description = Image reading via the GDAL Library (www.gdal.org) +provides = imread diff --git a/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.py b/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8f2478b892c8120468a92de910a8a2f4bde0d0 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/gdal_plugin.py @@ -0,0 +1,17 @@ +__all__ = ['imread'] + +try: + import osgeo.gdal as gdal +except ImportError: + raise ImportError( + "The GDAL Library could not be found. " + "Please refer to http://www.gdal.org/ " + "for further instructions." + ) + + +def imread(fname): + """Load an image from file.""" + ds = gdal.Open(fname) + + return ds.ReadAsArray() diff --git a/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..6429537b92763f7bb73a8bd43656d609f5ee4699 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.ini @@ -0,0 +1,3 @@ +[imageio] +description = Image reading via the ImageIO Library +provides = imread, imsave diff --git a/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.py b/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..2a58509d27b282f701142cb33ee43384ac54b4f6 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/imageio_plugin.py @@ -0,0 +1,14 @@ +__all__ = ['imread', 'imsave'] + +from functools import wraps +import numpy as np + +from imageio.v3 import imread as imageio_imread, imwrite as imsave + + +@wraps(imageio_imread) +def imread(*args, **kwargs): + out = np.asarray(imageio_imread(*args, **kwargs)) + if not out.flags['WRITEABLE']: + out = out.copy() + return out diff --git a/envs/kitoverlay/skimage/io/_plugins/imread_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/imread_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..a6a5ddb1096156acc8ef61e4bd4a45481739301e --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/imread_plugin.ini @@ -0,0 +1,3 @@ +[imread] +description = Image reading and writing via imread +provides = imread, imsave diff --git a/envs/kitoverlay/skimage/io/_plugins/imread_plugin.py b/envs/kitoverlay/skimage/io/_plugins/imread_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8fa2fc8900cf3e7ea15e6a9e6401d98f5c020b --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/imread_plugin.py @@ -0,0 +1,46 @@ +__all__ = ['imread', 'imsave'] + +from ...util.dtype import _convert + +try: + import imread as _imread +except ImportError: + raise ImportError( + "Imread could not be found" + "Please refer to http://pypi.python.org/pypi/imread/ " + "for further instructions." + ) + + +def imread(fname, dtype=None): + """Load an image from file. + + Parameters + ---------- + fname : str + Name of input file + + """ + im = _imread.imread(fname) + if dtype is not None: + im = _convert(im, dtype) + return im + + +def imsave(fname, arr, format_str=None): + """Save an image to disk. + + Parameters + ---------- + fname : str + Name of destination file. + arr : ndarray of uint8 or uint16 + Array (image) to save. + format_str : str,optional + Format to save as. + + Notes + ----- + Currently, only 8-bit precision is supported. + """ + return _imread.imsave(fname, arr, formatstr=format_str) diff --git a/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..a58b5aeb6d598293ee3cb5bcc12f3ebe0c72ef4e --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.ini @@ -0,0 +1,3 @@ +[matplotlib] +description = Display or save images using Matplotlib +provides = imshow, imread, imshow_collection, _app_show diff --git a/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.py b/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..874aef99b55f49ead489eabfef1293c3da549ba7 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/matplotlib_plugin.py @@ -0,0 +1,220 @@ +from collections import namedtuple +import numpy as np +from ...util import dtype as dtypes +from ...exposure import is_low_contrast +from ..._shared.utils import warn +from math import floor, ceil + + +_default_colormap = 'gray' +_nonstandard_colormap = 'viridis' +_diverging_colormap = 'RdBu' + + +ImageProperties = namedtuple( + 'ImageProperties', + ['signed', 'out_of_range_float', 'low_data_range', 'unsupported_dtype'], +) + + +def _get_image_properties(image): + """Determine nonstandard properties of an input image. + + Parameters + ---------- + image : array + The input image. + + Returns + ------- + ip : ImageProperties named tuple + The properties of the image: + + - signed: whether the image has negative values. + - out_of_range_float: if the image has floating point data + outside of [-1, 1]. + - low_data_range: if the image is in the standard image + range (e.g. [0, 1] for a floating point image) but its + data range would be too small to display with standard + image ranges. + - unsupported_dtype: if the image data type is not a + standard skimage type, e.g. ``numpy.uint64``. + """ + immin, immax = np.min(image), np.max(image) + imtype = image.dtype.type + try: + lo, hi = dtypes.dtype_range[imtype] + except KeyError: + lo, hi = immin, immax + + signed = immin < 0 + out_of_range_float = np.issubdtype(image.dtype, np.floating) and ( + immin < lo or immax > hi + ) + low_data_range = immin != immax and is_low_contrast(image) + unsupported_dtype = image.dtype not in dtypes._supported_types + + return ImageProperties( + signed, out_of_range_float, low_data_range, unsupported_dtype + ) + + +def _raise_warnings(image_properties): + """Raise the appropriate warning for each nonstandard image type. + + Parameters + ---------- + image_properties : ImageProperties named tuple + The properties of the considered image. + """ + ip = image_properties + if ip.unsupported_dtype: + warn( + "Non-standard image type; displaying image with " "stretched contrast.", + stacklevel=3, + ) + if ip.low_data_range: + warn( + "Low image data range; displaying image with " "stretched contrast.", + stacklevel=3, + ) + if ip.out_of_range_float: + warn( + "Float image out of standard range; displaying " + "image with stretched contrast.", + stacklevel=3, + ) + + +def _get_display_range(image): + """Return the display range for a given set of image properties. + + Parameters + ---------- + image : array + The input image. + + Returns + ------- + lo, hi : same type as immin, immax + The display range to be used for the input image. + cmap : string + The name of the colormap to use. + """ + ip = _get_image_properties(image) + immin, immax = np.min(image), np.max(image) + if ip.signed: + magnitude = max(abs(immin), abs(immax)) + lo, hi = -magnitude, magnitude + cmap = _diverging_colormap + elif any(ip): + _raise_warnings(ip) + lo, hi = immin, immax + cmap = _nonstandard_colormap + else: + lo = 0 + imtype = image.dtype.type + hi = dtypes.dtype_range[imtype][1] + cmap = _default_colormap + return lo, hi, cmap + + +def imshow(image, ax=None, show_cbar=None, **kwargs): + """Show the input image and return the current axes. + + By default, the image is displayed in grayscale, rather than + the matplotlib default colormap. + + Images are assumed to have standard range for their type. For + example, if a floating point image has values in [0, 0.5], the + most intense color will be gray50, not white. + + If the image exceeds the standard range, or if the range is too + small to display, we fall back on displaying exactly the range of + the input image, along with a colorbar to clearly indicate that + this range transformation has occurred. + + For signed images, we use a diverging colormap centered at 0. + + Parameters + ---------- + image : array, shape (M, N[, 3]) + The image to display. + ax : `matplotlib.axes.Axes`, optional + The axis to use for the image, defaults to plt.gca(). + show_cbar : bool, optional + Whether to show the colorbar (used to override default behavior). + **kwargs : Keyword arguments + These are passed directly to `matplotlib.pyplot.imshow`. + + Returns + ------- + ax_im : `matplotlib.pyplot.AxesImage` + The `AxesImage` object returned by `plt.imshow`. + """ + import matplotlib.pyplot as plt + from mpl_toolkits.axes_grid1 import make_axes_locatable + + lo, hi, cmap = _get_display_range(image) + + kwargs.setdefault('interpolation', 'nearest') + kwargs.setdefault('cmap', cmap) + kwargs.setdefault('vmin', lo) + kwargs.setdefault('vmax', hi) + + ax = ax or plt.gca() + ax_im = ax.imshow(image, **kwargs) + if (cmap != _default_colormap and show_cbar is not False) or show_cbar: + divider = make_axes_locatable(ax) + cax = divider.append_axes("right", size="5%", pad=0.05) + plt.colorbar(ax_im, cax=cax) + ax.get_figure().tight_layout() + + return ax_im + + +def imshow_collection(ic, *args, **kwargs): + """Display all images in the collection. + + Returns + ------- + fig : `matplotlib.figure.Figure` + The `Figure` object returned by `plt.subplots`. + """ + import matplotlib.pyplot as plt + + if len(ic) < 1: + raise ValueError('Number of images to plot must be greater than 0') + + # The target is to plot images on a grid with aspect ratio 4:3 + num_images = len(ic) + # Two pairs of `nrows, ncols` are possible + k = (num_images * 12) ** 0.5 + r1 = max(1, floor(k / 4)) + r2 = ceil(k / 4) + c1 = ceil(num_images / r1) + c2 = ceil(num_images / r2) + # Select the one which is closer to 4:3 + if abs(r1 / c1 - 0.75) < abs(r2 / c2 - 0.75): + nrows, ncols = r1, c1 + else: + nrows, ncols = r2, c2 + + fig, axes = plt.subplots(nrows=nrows, ncols=ncols) + ax = np.asarray(axes).ravel() + for n, image in enumerate(ic): + ax[n].imshow(image, *args, **kwargs) + kwargs['ax'] = axes + return fig + + +def imread(*args, **kwargs): + import matplotlib.image + + return matplotlib.image.imread(*args, **kwargs) + + +def _app_show(): + from matplotlib.pyplot import show + + show() diff --git a/envs/kitoverlay/skimage/io/_plugins/pil_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/pil_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..140344104141d7dc1e74676dd8eb84e7a426d47a --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/pil_plugin.ini @@ -0,0 +1,3 @@ +[pil] +description = Image reading via the Python Imaging Library +provides = imread, imsave diff --git a/envs/kitoverlay/skimage/io/_plugins/pil_plugin.py b/envs/kitoverlay/skimage/io/_plugins/pil_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..7a75c5fc0affda352d458c9df5f014c5cf79e091 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/pil_plugin.py @@ -0,0 +1,259 @@ +__all__ = ['imread', 'imsave'] + +import numpy as np +from PIL import Image + +from ...util import img_as_ubyte, img_as_uint + + +def imread(fname, dtype=None, img_num=None, **kwargs): + """Load an image from file. + + Parameters + ---------- + fname : str or file + File name or file-like-object. + dtype : numpy dtype object or string specifier + Specifies data type of array elements. + img_num : int, optional + Specifies which image to read in a file with multiple images + (zero-indexed). + kwargs : keyword pairs, optional + Addition keyword arguments to pass through. + + Notes + ----- + Files are read using the Python Imaging Library. + See PIL docs [1]_ for a list of supported formats. + + References + ---------- + .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html + """ + if isinstance(fname, str): + with open(fname, 'rb') as f: + im = Image.open(f) + return pil_to_ndarray(im, dtype=dtype, img_num=img_num) + else: + im = Image.open(fname) + return pil_to_ndarray(im, dtype=dtype, img_num=img_num) + + +def pil_to_ndarray(image, dtype=None, img_num=None): + """Import a PIL Image object to an ndarray, in memory. + + Parameters + ---------- + Refer to ``imread``. + + """ + try: + # this will raise an IOError if the file is not readable + image.getdata()[0] + except OSError as e: + site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" + pillow_error_message = str(e) + error_message = ( + f"Could not load '{image.filename}' \n" + f"Reason: '{pillow_error_message}'\n" + f"Please see documentation at: {site}" + ) + raise ValueError(error_message) + frames = [] + grayscale = None + i = 0 + while 1: + try: + image.seek(i) + except EOFError: + break + + frame = image + + if img_num is not None and img_num != i: + image.getdata()[0] + i += 1 + continue + + if image.format == 'PNG' and image.mode == 'I' and dtype is None: + dtype = 'uint16' + + if image.mode == 'P': + if grayscale is None: + grayscale = _palette_is_grayscale(image) + + if grayscale: + frame = image.convert('L') + else: + if image.format == 'PNG' and 'transparency' in image.info: + frame = image.convert('RGBA') + else: + frame = image.convert('RGB') + + elif image.mode == '1': + frame = image.convert('L') + + elif 'A' in image.mode: + frame = image.convert('RGBA') + + elif image.mode == 'CMYK': + frame = image.convert('RGB') + + if image.mode.startswith('I;16'): + shape = image.size + dtype = '>u2' if image.mode.endswith('B') else ' 1: + return np.array(frames) + elif frames: + return frames[0] + elif img_num: + raise IndexError(f'Could not find image #{img_num}') + + +def _palette_is_grayscale(pil_image): + """Return True if PIL image in palette mode is grayscale. + + Parameters + ---------- + pil_image : PIL image + PIL Image that is in Palette mode. + + Returns + ------- + is_grayscale : bool + True if all colors in image palette are gray. + """ + if pil_image.mode != 'P': + raise ValueError('pil_image.mode must be equal to "P".') + # get palette as an array with R, G, B columns + # Starting in pillow 9.1 palettes may have less than 256 entries + palette = np.asarray(pil_image.getpalette()).reshape((-1, 3)) + # Not all palette colors are used; unused colors have junk values. + start, stop = pil_image.getextrema() + valid_palette = palette[start : stop + 1] + # Image is grayscale if channel differences (R - G and G - B) + # are all zero. + return np.allclose(np.diff(valid_palette), 0) + + +def ndarray_to_pil(arr, format_str=None): + """Export an ndarray to a PIL object. + + Parameters + ---------- + Refer to ``imsave``. + + """ + if arr.ndim == 3: + arr = img_as_ubyte(arr) + mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] + + elif format_str in ['png', 'PNG']: + mode = 'I;16' + + if arr.dtype.kind == 'f': + arr = img_as_uint(arr) + + elif arr.max() < 256 and arr.min() >= 0: + arr = arr.astype(np.uint8) + mode = 'L' + + else: + arr = img_as_uint(arr) + + else: + arr = img_as_ubyte(arr) + mode = 'L' + + try: + array_buffer = arr.tobytes() + except AttributeError: + array_buffer = arr.tostring() # Numpy < 1.9 + + if arr.ndim == 2: + im = Image.new(mode, arr.T.shape) + try: + im.frombytes(array_buffer, 'raw', mode) + except AttributeError: + im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 + else: + image_shape = (arr.shape[1], arr.shape[0]) + try: + im = Image.frombytes(mode, image_shape, array_buffer) + except AttributeError: + im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 + return im + + +def imsave(fname, arr, format_str=None, **kwargs): + """Save an image to disk. + + Parameters + ---------- + fname : str or file-like object + Name of destination file. + arr : ndarray of uint8 or float + Array (image) to save. Arrays of data-type uint8 should have + values in [0, 255], whereas floating-point arrays must be + in [0, 1]. + format_str : str + Format to save as, this is defaulted to PNG if using a file-like + object; this will be derived from the extension if fname is a string + kwargs : dict + Keyword arguments to the Pillow save function (or tifffile save + function, for Tiff files). These are format dependent. For example, + Pillow's JPEG save function supports an integer ``quality`` argument + with values in [1, 95], while TIFFFile supports a ``compress`` + integer argument with values in [0, 9]. + + Notes + ----- + Use the Python Imaging Library. + See PIL docs [1]_ for a list of other supported formats. + All images besides single channel PNGs are converted using `img_as_uint8`. + Single Channel PNGs have the following behavior: + - Integer values in [0, 255] and Boolean types -> img_as_uint8 + - Floating point and other integers -> img_as_uint16 + + References + ---------- + .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html + """ + # default to PNG if file-like object + if not isinstance(fname, str) and format_str is None: + format_str = "PNG" + # Check for png in filename + if isinstance(fname, str) and fname.lower().endswith(".png"): + format_str = "PNG" + + arr = np.asanyarray(arr) + + if arr.dtype.kind == 'b': + arr = arr.astype(np.uint8) + + if arr.ndim not in (2, 3): + raise ValueError(f"Invalid shape for image array: {arr.shape}") + + if arr.ndim == 3: + if arr.shape[2] not in (3, 4): + raise ValueError("Invalid number of channels in image array.") + + img = ndarray_to_pil(arr, format_str=format_str) + img.save(fname, format=format_str, **kwargs) diff --git a/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..75a6d99584e24bc51fe4a75cb036967d106e9183 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.ini @@ -0,0 +1,3 @@ +[simpleitk] +description = Image reading and writing via SimpleITK +provides = imread, imsave diff --git a/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.py b/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0efc510b0dab73e7b5fcc94ff1f95c52007f37 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/simpleitk_plugin.py @@ -0,0 +1,23 @@ +__all__ = ['imread', 'imsave'] + +try: + import SimpleITK as sitk +except ImportError: + raise ImportError( + "SimpleITK could not be found. " + "Please try " + " easy_install SimpleITK " + "or refer to " + " http://simpleitk.org/ " + "for further instructions." + ) + + +def imread(fname): + sitk_img = sitk.ReadImage(fname) + return sitk.GetArrayFromImage(sitk_img) + + +def imsave(fname, arr): + sitk_img = sitk.GetImageFromArray(arr, isVector=True) + sitk.WriteImage(sitk_img, fname) diff --git a/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.ini b/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..bf83fce2640d0505aed01a40a65c01dd8f2ec23a --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.ini @@ -0,0 +1,3 @@ +[tifffile] +description = Load and save TIFF and TIFF-based images using tifffile.py +provides = imread, imsave diff --git a/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.py b/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..0df756cb8c29ce8bc1a1ee4230c1ae4d72fafed6 --- /dev/null +++ b/envs/kitoverlay/skimage/io/_plugins/tifffile_plugin.py @@ -0,0 +1,74 @@ +from tifffile import imread as tifffile_imread +from tifffile import imwrite as tifffile_imwrite + +__all__ = ['imread', 'imsave'] + + +def imsave(fname, arr, **kwargs): + """Load a tiff image to file. + + Parameters + ---------- + fname : str or file + File name or file-like object. + arr : ndarray + The array to write. + kwargs : keyword pairs, optional + Additional keyword arguments to pass through (see ``tifffile``'s + ``imwrite`` function). + + Notes + ----- + Provided by the tifffile library [1]_, and supports many + advanced image types including multi-page and floating-point. + + This implementation will set ``photometric='RGB'`` when writing if the first + or last axis of `arr` has length 3 or 4. To override this, explicitly + pass the ``photometric`` kwarg. + + This implementation will set ``planarconfig='SEPARATE'`` when writing if the + first axis of arr has length 3 or 4. To override this, explicitly + specify the ``planarconfig`` kwarg. + + References + ---------- + .. [1] https://pypi.org/project/tifffile/ + + """ + if arr.shape[0] in [3, 4]: + if 'planarconfig' not in kwargs: + kwargs['planarconfig'] = 'SEPARATE' + rgb = True + else: + rgb = arr.shape[-1] in [3, 4] + if rgb and 'photometric' not in kwargs: + kwargs['photometric'] = 'RGB' + + return tifffile_imwrite(fname, arr, **kwargs) + + +def imread(fname, **kwargs): + """Load a tiff image from file. + + Parameters + ---------- + fname : str or file + File name or file-like-object. + kwargs : keyword pairs, optional + Additional keyword arguments to pass through (see ``tifffile``'s + ``imread`` function). + + Notes + ----- + Provided by the tifffile library [1]_, and supports many + advanced image types including multi-page and floating point. + + References + ---------- + .. [1] https://pypi.org/project/tifffile/ + + """ + if 'img_num' in kwargs: + kwargs['key'] = kwargs.pop('img_num') + + return tifffile_imread(fname, **kwargs) diff --git a/envs/kitoverlay/skimage/io/collection.py b/envs/kitoverlay/skimage/io/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..c87c5a552b01349a30abec308c0eb65d1e079272 --- /dev/null +++ b/envs/kitoverlay/skimage/io/collection.py @@ -0,0 +1,493 @@ +"""Data structures to hold collections of images, with optional caching.""" + +import os +from glob import glob +import re +from collections.abc import Sequence +from copy import copy + +import numpy as np +from PIL import Image + +from tifffile import TiffFile + + +__all__ = [ + 'MultiImage', + 'ImageCollection', + 'concatenate_images', + 'imread_collection_wrapper', +] + + +def concatenate_images(ic): + """Concatenate all images in the image collection into an array. + + Parameters + ---------- + ic : an iterable of images + The images to be concatenated. + + Returns + ------- + array_cat : ndarray + An array having one more dimension than the images in `ic`. + + See Also + -------- + ImageCollection.concatenate + MultiImage.concatenate + + Raises + ------ + ValueError + If images in `ic` don't have identical shapes. + + Notes + ----- + ``concatenate_images`` receives any iterable object containing images, + including ImageCollection and MultiImage, and returns a NumPy array. + """ + all_images = [image[np.newaxis, ...] for image in ic] + try: + array_cat = np.concatenate(all_images) + except ValueError: + raise ValueError('Image dimensions must agree.') + return array_cat + + +def alphanumeric_key(s): + """Convert string to list of strings and ints that gives intuitive sorting. + + Parameters + ---------- + s : string + + Returns + ------- + k : a list of strings and ints + + Examples + -------- + >>> alphanumeric_key('z23a') + ['z', 23, 'a'] + >>> filenames = ['f9.10.png', 'e10.png', 'f9.9.png', 'f10.10.png', + ... 'f10.9.png'] + >>> sorted(filenames) + ['e10.png', 'f10.10.png', 'f10.9.png', 'f9.10.png', 'f9.9.png'] + >>> sorted(filenames, key=alphanumeric_key) + ['e10.png', 'f9.9.png', 'f9.10.png', 'f10.9.png', 'f10.10.png'] + """ + k = [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', s)] + return k + + +def _is_multipattern(input_pattern): + """Helping function. Returns True if pattern contains a tuple, list, or a + string separated with os.pathsep.""" + # Conditions to be accepted by ImageCollection: + has_str_ospathsep = isinstance(input_pattern, str) and os.pathsep in input_pattern + not_a_string = not isinstance(input_pattern, str) + has_iterable = isinstance(input_pattern, Sequence) + has_strings = all(isinstance(pat, str) for pat in input_pattern) + + is_multipattern = has_str_ospathsep or ( + not_a_string and has_iterable and has_strings + ) + return is_multipattern + + +class ImageCollection: + """Load and manage a collection of image files. + + Parameters + ---------- + load_pattern : str or list of str + Pattern string or list of strings to load. The filename path can be + absolute or relative. + conserve_memory : bool, optional + If True, :class:`skimage.io.ImageCollection` does not keep more than one in + memory at a specific time. Otherwise, images will be cached once they are loaded. + + Other parameters + ---------------- + load_func : callable + ``imread`` by default. See Notes below. + **load_func_kwargs : dict + Any other keyword arguments are passed to `load_func`. + + Attributes + ---------- + files : list of str + If a pattern string is given for `load_pattern`, this attribute + stores the expanded file list. Otherwise, this is equal to + `load_pattern`. + + Notes + ----- + Note that files are always returned in alphanumerical order. Also note that slicing + returns a new :class:`skimage.io.ImageCollection`, *not* a view into the data. + + ImageCollection image loading can be customized through + `load_func`. For an ImageCollection ``ic``, ``ic[5]`` calls + ``load_func(load_pattern[5])`` to load that image. + + For example, here is an ImageCollection that, for each video provided, + loads every second frame:: + + import imageio.v3 as iio3 + import itertools + + def vidread_step(f, step): + vid = iio3.imiter(f) + return list(itertools.islice(vid, None, None, step) + + video_file = 'no_time_for_that_tiny.gif' + ic = ImageCollection(video_file, load_func=vidread_step, step=2) + + ic # is an ImageCollection object of length 1 because 1 video is provided + + x = ic[0] + x[5] # the 10th frame of the first video + + Alternatively, if `load_func` is provided and `load_pattern` is a + sequence, an :class:`skimage.io.ImageCollection` of corresponding length will + be created, and the individual images will be loaded by calling `load_func` with the + matching element of the `load_pattern` as its first argument. In this + case, the elements of the sequence do not need to be names of existing + files (or strings at all). For example, to create an :class:`skimage.io.ImageCollection` + containing 500 images from a video:: + + class FrameReader: + def __init__ (self, f): + self.f = f + def __call__ (self, index): + return iio3.imread(self.f, index=index) + + ic = ImageCollection(range(500), load_func=FrameReader('movie.mp4')) + + ic # is an ImageCollection object of length 500 + + Another use of `load_func` would be to convert all images to ``uint8``:: + + def imread_convert(f): + return imread(f).astype(np.uint8) + + ic = ImageCollection('/tmp/*.png', load_func=imread_convert) + + Examples + -------- + >>> import imageio.v3 as iio3 + >>> import skimage.io as io + + # Where your images are located + >>> data_dir = os.path.join(os.path.dirname(__file__), '../data') + + >>> coll = io.ImageCollection(data_dir + '/chess*.png') + >>> len(coll) + 2 + >>> coll[0].shape + (200, 200) + + >>> image_col = io.ImageCollection([f'{data_dir}/*.png', '{data_dir}/*.jpg']) + + >>> class MultiReader: + ... def __init__ (self, f): + ... self.f = f + ... def __call__ (self, index): + ... return iio3.imread(self.f, index=index) + ... + >>> filename = data_dir + '/no_time_for_that_tiny.gif' + >>> ic = io.ImageCollection(range(24), load_func=MultiReader(filename)) + >>> len(image_col) + 23 + >>> isinstance(ic[0], np.ndarray) + True + """ + + def __init__( + self, load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs + ): + """Load and manage a collection of images.""" + self._files = [] + if _is_multipattern(load_pattern): + if isinstance(load_pattern, str): + load_pattern = load_pattern.split(os.pathsep) + for pattern in load_pattern: + self._files.extend(glob(pattern)) + self._files = sorted(self._files, key=alphanumeric_key) + elif isinstance(load_pattern, str): + self._files.extend(glob(load_pattern)) + self._files = sorted(self._files, key=alphanumeric_key) + elif isinstance(load_pattern, Sequence) and load_func is not None: + self._files = list(load_pattern) + else: + raise TypeError('Invalid pattern as input.') + + if load_func is None: + from ._io import imread + + self.load_func = imread + self._numframes = self._find_images() + else: + self.load_func = load_func + self._numframes = len(self._files) + self._frame_index = None + + if conserve_memory: + memory_slots = 1 + else: + memory_slots = self._numframes + + self._conserve_memory = conserve_memory + self._cached = None + + self.load_func_kwargs = load_func_kwargs + self.data = np.empty(memory_slots, dtype=object) + + @property + def files(self): + return self._files + + @property + def conserve_memory(self): + return self._conserve_memory + + def _find_images(self): + index = [] + for fname in self._files: + if fname.lower().endswith(('.tiff', '.tif')): + with open(fname, 'rb') as f: + img = TiffFile(f) + index += [(fname, i) for i in range(len(img.pages))] + else: + try: + im = Image.open(fname) + im.seek(0) + except OSError: + continue + i = 0 + while True: + try: + im.seek(i) + except EOFError: + break + index.append((fname, i)) + i += 1 + if hasattr(im, 'fp') and im.fp: + im.fp.close() + self._frame_index = index + return len(index) + + def __getitem__(self, n): + """Return selected image(s) in the collection. + + Loading is done on demand. + + Parameters + ---------- + n : int or slice + The image number to be returned, or a slice selecting the images + and ordering to be returned in a new ImageCollection. + + Returns + ------- + img : ndarray or :class:`skimage.io.ImageCollection` + The `n`-th image in the collection, or a new ImageCollection with + the selected images. + """ + if hasattr(n, '__index__'): + n = n.__index__() + + if not isinstance(n, (int, slice)): + raise TypeError('slicing must be with an int or slice object') + + if isinstance(n, int): + n = self._check_imgnum(n) + idx = n % len(self.data) + + if (self.conserve_memory and n != self._cached) or (self.data[idx] is None): + kwargs = self.load_func_kwargs + if self._frame_index: + fname, img_num = self._frame_index[n] + if img_num is not None: + kwargs['img_num'] = img_num + try: + self.data[idx] = self.load_func(fname, **kwargs) + # Account for functions that do not accept an img_num kwarg + except TypeError as e: + if "unexpected keyword argument 'img_num'" in str(e): + del kwargs['img_num'] + self.data[idx] = self.load_func(fname, **kwargs) + else: + raise + else: + self.data[idx] = self.load_func(self.files[n], **kwargs) + self._cached = n + + return self.data[idx] + else: + # A slice object was provided, so create a new ImageCollection + # object. Any loaded image data in the original ImageCollection + # will be copied by reference to the new object. Image data + # loaded after this creation is not linked. + fidx = range(self._numframes)[n] + new_ic = copy(self) + + if self._frame_index: + new_ic._files = [self._frame_index[i][0] for i in fidx] + new_ic._frame_index = [self._frame_index[i] for i in fidx] + else: + new_ic._files = [self._files[i] for i in fidx] + + new_ic._numframes = len(fidx) + + if self.conserve_memory: + if self._cached in fidx: + new_ic._cached = fidx.index(self._cached) + new_ic.data = np.copy(self.data) + else: + new_ic.data = np.empty(1, dtype=object) + else: + new_ic.data = self.data[fidx] + return new_ic + + def _check_imgnum(self, n): + """Check that the given image number is valid.""" + num = self._numframes + if -num <= n < num: + n = n % num + else: + raise IndexError(f"There are only {num} images in the collection") + return n + + def __iter__(self): + """Iterate over the images.""" + for i in range(len(self)): + yield self[i] + + def __len__(self): + """Number of images in collection.""" + return self._numframes + + def __str__(self): + return str(self.files) + + def reload(self, n=None): + """Clear the image cache. + + Parameters + ---------- + n : None or int + Clear the cache for this image only. By default, the + entire cache is erased. + + """ + self.data = np.empty_like(self.data) + + def concatenate(self): + """Concatenate all images in the collection into an array. + + Returns + ------- + ar : np.ndarray + An array having one more dimension than the images in `self`. + + See Also + -------- + skimage.io.concatenate_images + + Raises + ------ + ValueError + If images in the :class:`skimage.io.ImageCollection` do not have identical + shapes. + """ + return concatenate_images(self) + + +def imread_collection_wrapper(imread): + def imread_collection(load_pattern, conserve_memory=True): + """Return an `ImageCollection` from files matching the given pattern. + + Note that files are always stored in alphabetical order. Also note that + slicing returns a new ImageCollection, *not* a view into the data. + + See `skimage.io.ImageCollection` for details. + + Parameters + ---------- + load_pattern : str or list + Pattern glob or filenames to load. The path can be absolute or + relative. Multiple patterns should be separated by a colon, + e.g. ``/tmp/work/*.png:/tmp/other/*.jpg``. Also see + implementation notes below. + conserve_memory : bool, optional + If True, never keep more than one in memory at a specific + time. Otherwise, images will be cached once they are loaded. + + """ + return ImageCollection( + load_pattern, conserve_memory=conserve_memory, load_func=imread + ) + + return imread_collection + + +class MultiImage(ImageCollection): + """A class containing all frames from multi-frame TIFF images. + + Parameters + ---------- + load_pattern : str or list of str + Pattern glob or filenames to load. The path can be absolute or + relative. + conserve_memory : bool, optional + Whether to conserve memory by only caching the frames of a single + image. Default is True. + + Notes + ----- + `MultiImage` returns a list of image-data arrays. In this + regard, it is very similar to `ImageCollection`, but the two differ in + their treatment of multi-frame images. + + For a TIFF image containing N frames of size WxH, `MultiImage` stores + all frames of that image as a single element of shape `(N, W, H)` in the + list. `ImageCollection` instead creates N elements of shape `(W, H)`. + + For an animated GIF image, `MultiImage` reads only the first frame, while + `ImageCollection` reads all frames by default. + + Examples + -------- + # Where your images are located + >>> data_dir = os.path.join(os.path.dirname(__file__), '../data') + + >>> multipage_tiff = data_dir + '/multipage.tif' + >>> multi_img = MultiImage(multipage_tiff) + >>> len(multi_img) # multi_img contains one element + 1 + >>> multi_img[0].shape # this element is a two-frame image of shape: + (2, 15, 10) + + >>> image_col = ImageCollection(multipage_tiff) + >>> len(image_col) # image_col contains two elements + 2 + >>> for frame in image_col: + ... print(frame.shape) # each element is a frame of shape (15, 10) + ... + (15, 10) + (15, 10) + """ + + def __init__(self, filename, conserve_memory=True, dtype=None, **imread_kwargs): + """Load a multi-img.""" + from ._io import imread + + self._filename = filename + super().__init__(filename, conserve_memory, load_func=imread, **imread_kwargs) + + @property + def filename(self): + return self._filename diff --git a/envs/kitoverlay/skimage/io/manage_plugins.py b/envs/kitoverlay/skimage/io/manage_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..e1dccb78100e53b44ba68f8dc47a6317095b578a --- /dev/null +++ b/envs/kitoverlay/skimage/io/manage_plugins.py @@ -0,0 +1,405 @@ +"""Handle image reading, writing and plotting plugins. + +To improve performance, plugins are only loaded as needed. As a result, there +can be multiple states for a given plugin: + + available: Defined in an *ini file located in ``skimage.io._plugins``. + See also :func:`skimage.io.available_plugins`. + partial definition: Specified in an *ini file, but not defined in the + corresponding plugin module. This will raise an error when loaded. + available but not on this system: Defined in ``skimage.io._plugins``, but + a dependent library (e.g. Qt, PIL) is not available on your system. + This will raise an error when loaded. + loaded: The real availability is determined when it's explicitly loaded, + either because it's one of the default plugins, or because it's + loaded explicitly by the user. + +""" + +import os.path +import warnings +from configparser import ConfigParser +from glob import glob +from contextlib import contextmanager + +from .._shared.utils import deprecate_func +from .collection import imread_collection_wrapper + +__all__ = [ + 'use_plugin', + 'call_plugin', + 'plugin_info', + 'plugin_order', + 'reset_plugins', + 'find_available_plugins', + '_available_plugins', +] + +# The plugin store will save a list of *loaded* io functions for each io type +# (e.g. 'imread', 'imsave', etc.). Plugins are loaded as requested. +plugin_store = None +# Dictionary mapping plugin names to a list of functions they provide. +plugin_provides = {} +# The module names for the plugins in `skimage.io._plugins`. +plugin_module_name = {} +# Meta-data about plugins provided by *.ini files. +plugin_meta_data = {} +# For each plugin type, default to the first available plugin as defined by +# the following preferences. +preferred_plugins = { + # Default plugins for all types (overridden by specific types below). + 'all': ['imageio', 'pil', 'matplotlib'], + 'imshow': ['matplotlib'], + 'imshow_collection': ['matplotlib'], +} + + +@contextmanager +def _hide_plugin_deprecation_warnings(): + """Ignore warnings related to plugin infrastructure deprecation.""" + with warnings.catch_warnings(): + warnings.filterwarnings( + action="ignore", + message=".*use `imageio` or other I/O packages directly.*", + category=FutureWarning, + module="skimage", + ) + yield + + +def _clear_plugins(): + """Clear the plugin state to the default, i.e., where no plugins are loaded""" + global plugin_store + plugin_store = { + 'imread': [], + 'imsave': [], + 'imshow': [], + 'imread_collection': [], + 'imshow_collection': [], + '_app_show': [], + } + + +with _hide_plugin_deprecation_warnings(): + _clear_plugins() + + +def _load_preferred_plugins(): + # Load preferred plugin for each io function. + io_types = ['imsave', 'imshow', 'imread_collection', 'imshow_collection', 'imread'] + for p_type in io_types: + _set_plugin(p_type, preferred_plugins['all']) + + plugin_types = (p for p in preferred_plugins.keys() if p != 'all') + for p_type in plugin_types: + _set_plugin(p_type, preferred_plugins[p_type]) + + +def _set_plugin(plugin_type, plugin_list): + for plugin in plugin_list: + if plugin not in _available_plugins: + continue + try: + use_plugin(plugin, kind=plugin_type) + break + except (ImportError, RuntimeError, OSError): + pass + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def reset_plugins(): + with _hide_plugin_deprecation_warnings(): + _clear_plugins() + _load_preferred_plugins() + + +def _parse_config_file(filename): + """Return plugin name and meta-data dict from plugin config file.""" + parser = ConfigParser() + parser.read(filename) + name = parser.sections()[0] + + meta_data = {} + for opt in parser.options(name): + meta_data[opt] = parser.get(name, opt) + + return name, meta_data + + +def _scan_plugins(): + """Scan the plugins directory for .ini files and parse them + to gather plugin meta-data. + """ + pd = os.path.dirname(__file__) + config_files = glob(os.path.join(pd, '_plugins', '*.ini')) + + for filename in config_files: + name, meta_data = _parse_config_file(filename) + if 'provides' not in meta_data: + warnings.warn( + f'file {filename} not recognized as a scikit-image io plugin, skipping.' + ) + continue + plugin_meta_data[name] = meta_data + provides = [s.strip() for s in meta_data['provides'].split(',')] + valid_provides = [p for p in provides if p in plugin_store] + + for p in provides: + if p not in plugin_store: + print(f"Plugin `{name}` wants to provide non-existent `{p}`. Ignoring.") + + # Add plugins that provide 'imread' as provider of 'imread_collection'. + need_to_add_collection = ( + 'imread_collection' not in valid_provides and 'imread' in valid_provides + ) + if need_to_add_collection: + valid_provides.append('imread_collection') + + plugin_provides[name] = valid_provides + + plugin_module_name[name] = os.path.basename(filename)[:-4] + + +with _hide_plugin_deprecation_warnings(): + _scan_plugins() + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def find_available_plugins(loaded=False): + """List available plugins. + + Parameters + ---------- + loaded : bool + If True, show only those plugins currently loaded. By default, + all plugins are shown. + + Returns + ------- + p : dict + Dictionary with plugin names as keys and exposed functions as + values. + + """ + active_plugins = set() + for plugin_func in plugin_store.values(): + for plugin, func in plugin_func: + active_plugins.add(plugin) + + d = {} + for plugin in plugin_provides: + if not loaded or plugin in active_plugins: + d[plugin] = [f for f in plugin_provides[plugin] if not f.startswith('_')] + + return d + + +with _hide_plugin_deprecation_warnings(): + _available_plugins = find_available_plugins() + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def call_plugin(kind, *args, **kwargs): + """Find the appropriate plugin of 'kind' and execute it. + + Parameters + ---------- + kind : {'imshow', 'imsave', 'imread', 'imread_collection'} + Function to look up. + plugin : str, optional + Plugin to load. Defaults to None, in which case the first + matching plugin is used. + *args, **kwargs : arguments and keyword arguments + Passed to the plugin function. + + """ + if kind not in plugin_store: + raise ValueError(f'Invalid function ({kind}) requested.') + + plugin_funcs = plugin_store[kind] + if len(plugin_funcs) == 0: + msg = ( + f"No suitable plugin registered for {kind}.\n\n" + "You may load I/O plugins with the `skimage.io.use_plugin` " + "command. A list of all available plugins are shown in the " + "`skimage.io` docstring." + ) + raise RuntimeError(msg) + + plugin = kwargs.pop('plugin', None) + if plugin is None: + _, func = plugin_funcs[0] + else: + _load(plugin) + try: + func = [f for (p, f) in plugin_funcs if p == plugin][0] + except IndexError: + raise RuntimeError(f'Could not find the plugin "{plugin}" for {kind}.') + + return func(*args, **kwargs) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def use_plugin(name, kind=None): + """Set the default plugin for a specified operation. The plugin + will be loaded if it hasn't been already. + + Parameters + ---------- + name : str + Name of plugin. See ``skimage.io.available_plugins`` for a list of available + plugins. + kind : {'imsave', 'imread', 'imshow', 'imread_collection', 'imshow_collection'}, optional + Set the plugin for this function. By default, + the plugin is set for all functions. + + Examples + -------- + To use Matplotlib as the default image reader, you would write: + + >>> from skimage import io + >>> io.use_plugin('matplotlib', 'imread') # doctest: +SKIP + + To see a list of available plugins run ``skimage.io.available_plugins``. Note + that this lists plugins that are defined, but the full list may not be usable + if your system does not have the required libraries installed. + + """ + if kind is None: + kind = plugin_store.keys() + else: + if kind not in plugin_provides[name]: + raise RuntimeError(f"Plugin {name} does not support `{kind}`.") + + if kind == 'imshow': + kind = [kind, '_app_show'] + else: + kind = [kind] + + _load(name) + + for k in kind: + if k not in plugin_store: + raise RuntimeError(f"'{k}' is not a known plugin function.") + + funcs = plugin_store[k] + + # Shuffle the plugins so that the requested plugin stands first + # in line + funcs = [(n, f) for (n, f) in funcs if n == name] + [ + (n, f) for (n, f) in funcs if n != name + ] + + plugin_store[k] = funcs + + +def _inject_imread_collection_if_needed(module): + """Add `imread_collection` to module if not already present.""" + if not hasattr(module, 'imread_collection') and hasattr(module, 'imread'): + imread = getattr(module, 'imread') + func = imread_collection_wrapper(imread) + setattr(module, 'imread_collection', func) + + +@_hide_plugin_deprecation_warnings() +def _load(plugin): + """Load the given plugin. + + Parameters + ---------- + plugin : str + Name of plugin to load. + + See Also + -------- + plugins : List of available plugins + + """ + if plugin in find_available_plugins(loaded=True): + return + if plugin not in plugin_module_name: + raise ValueError(f"Plugin {plugin} not found.") + else: + modname = plugin_module_name[plugin] + plugin_module = __import__('skimage.io._plugins.' + modname, fromlist=[modname]) + + provides = plugin_provides[plugin] + for p in provides: + if p == 'imread_collection': + _inject_imread_collection_if_needed(plugin_module) + elif not hasattr(plugin_module, p): + print(f"Plugin {plugin} does not provide {p} as advertised. Ignoring.") + continue + + store = plugin_store[p] + func = getattr(plugin_module, p) + if (plugin, func) not in store: + store.append((plugin, func)) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def plugin_info(plugin): + """Return plugin meta-data. + + Parameters + ---------- + plugin : str + Name of plugin. + + Returns + ------- + m : dict + Meta data as specified in plugin ``.ini``. + + """ + try: + return plugin_meta_data[plugin] + except KeyError: + raise ValueError(f'No information on plugin "{plugin}"') + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="The plugin infrastructure of `skimage.io` is deprecated. " + "Instead, use `imageio` or other I/O packages directly.", +) +def plugin_order(): + """Return the currently preferred plugin order. + + Returns + ------- + p : dict + Dictionary of preferred plugin order, with function name as key and + plugins (in order of preference) as value. + + """ + p = {} + for func in plugin_store: + p[func] = [plugin_name for (plugin_name, f) in plugin_store[func]] + return p diff --git a/envs/kitoverlay/skimage/io/sift.py b/envs/kitoverlay/skimage/io/sift.py new file mode 100644 index 0000000000000000000000000000000000000000..d3789678260160dc9d980701ed31b3e063e630f7 --- /dev/null +++ b/envs/kitoverlay/skimage/io/sift.py @@ -0,0 +1,93 @@ +import numpy as np + +__all__ = ['load_sift', 'load_surf'] + + +def _sift_read(filelike, mode='SIFT'): + """Read SIFT or SURF features from externally generated file. + + This routine reads SIFT or SURF files generated by binary utilities from + http://people.cs.ubc.ca/~lowe/keypoints/ and + http://www.vision.ee.ethz.ch/~surf/. + + This routine *does not* generate SIFT/SURF features from an image. These + algorithms are patent encumbered. Please use :obj:`skimage.feature.CENSURE` + instead. + + Parameters + ---------- + filelike : string or open file + Input file generated by the feature detectors from + http://people.cs.ubc.ca/~lowe/keypoints/ or + http://www.vision.ee.ethz.ch/~surf/ . + mode : {'SIFT', 'SURF'}, optional + Kind of descriptor used to generate `filelike`. + + Returns + ------- + data : record array with fields + - row: int + row position of feature + - column: int + column position of feature + - scale: float + feature scale + - orientation: float + feature orientation + - data: array + feature values + + """ + if isinstance(filelike, str): + f = open(filelike) + filelike_is_str = True + else: + f = filelike + filelike_is_str = False + + if mode == 'SIFT': + nr_features, feature_len = map(int, f.readline().split()) + datatype = np.dtype( + [ + ('row', float), + ('column', float), + ('scale', float), + ('orientation', float), + ('data', (float, feature_len)), + ] + ) + else: + mode = 'SURF' + feature_len = int(f.readline()) - 1 + nr_features = int(f.readline()) + datatype = np.dtype( + [ + ('column', float), + ('row', float), + ('second_moment', (float, 3)), + ('sign', float), + ('data', (float, feature_len)), + ] + ) + + data = np.fromfile(f, sep=' ') + if data.size != nr_features * datatype.itemsize / np.dtype(float).itemsize: + raise OSError(f'Invalid {mode} feature file.') + + # If `filelike` is passed to the function as filename - close the file + if filelike_is_str: + f.close() + + return data.view(datatype) + + +def load_sift(f): + return _sift_read(f, mode='SIFT') + + +def load_surf(f): + return _sift_read(f, mode='SURF') + + +load_sift.__doc__ = _sift_read.__doc__ +load_surf.__doc__ = _sift_read.__doc__ diff --git a/envs/kitoverlay/skimage/io/util.py b/envs/kitoverlay/skimage/io/util.py new file mode 100644 index 0000000000000000000000000000000000000000..921e22a4e2cf01224ab78246e6bccac538807707 --- /dev/null +++ b/envs/kitoverlay/skimage/io/util.py @@ -0,0 +1,41 @@ +import urllib.parse +import urllib.request +from urllib.error import URLError, HTTPError + +import os +import re +import tempfile +from contextlib import contextmanager + + +URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') + + +def is_url(filename): + """Return True if string is an http or ftp path.""" + return isinstance(filename, str) and URL_REGEX.match(filename) is not None + + +@contextmanager +def file_or_url_context(resource_name): + """Yield name of file from the given resource (i.e. file or url).""" + if is_url(resource_name): + url_components = urllib.parse.urlparse(resource_name) + _, ext = os.path.splitext(url_components.path) + try: + with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: + with urllib.request.urlopen(resource_name) as u: + f.write(u.read()) + # f must be closed before yielding + yield f.name + except (URLError, HTTPError): + # could not open URL + os.remove(f.name) + raise + except (FileNotFoundError, FileExistsError, PermissionError, BaseException): + # could not create temporary file + raise + else: + os.remove(f.name) + else: + yield resource_name diff --git a/envs/kitoverlay/skimage/measure/__init__.py b/envs/kitoverlay/skimage/measure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08699c314daf0df76637ee2573b621c91722aae7 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/__init__.py @@ -0,0 +1,5 @@ +"""Measurement of image properties, e.g., region properties, contours.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/measure/__init__.pyi b/envs/kitoverlay/skimage/measure/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3d7cf00148b6d7ec92bbc226134f4d110f993ea9 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/__init__.pyi @@ -0,0 +1,76 @@ +# 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__ = [ + 'find_contours', + 'regionprops', + 'regionprops_table', + 'perimeter', + 'perimeter_crofton', + 'euler_number', + 'approximate_polygon', + 'subdivide_polygon', + 'LineModelND', + 'CircleModel', + 'EllipseModel', + 'RansacModelProtocol', + 'ransac', + 'block_reduce', + 'moments', + 'moments_central', + 'moments_coords', + 'moments_coords_central', + 'moments_normalized', + 'moments_hu', + 'inertia_tensor', + 'inertia_tensor_eigvals', + 'marching_cubes', + 'mesh_surface_area', + 'profile_line', + 'label', + 'points_in_poly', + 'grid_points_in_poly', + 'shannon_entropy', + 'blur_effect', + 'pearson_corr_coeff', + 'manders_coloc_coeff', + 'manders_overlap_coeff', + 'intersection_coeff', + 'centroid', +] + +from ._find_contours import find_contours +from ._marching_cubes_lewiner import marching_cubes, mesh_surface_area +from ._regionprops import ( + regionprops, + perimeter, + perimeter_crofton, + euler_number, + regionprops_table, +) +from ._polygon import approximate_polygon, subdivide_polygon +from .pnpoly import points_in_poly, grid_points_in_poly +from ._moments import ( + moments, + moments_central, + moments_coords, + moments_coords_central, + moments_normalized, + centroid, + moments_hu, + inertia_tensor, + inertia_tensor_eigvals, +) +from .profile import profile_line +from .fit import LineModelND, CircleModel, EllipseModel, ransac, RansacModelProtocol +from .block import block_reduce +from ._label import label +from .entropy import shannon_entropy +from ._blur_effect import blur_effect +from ._colocalization import ( + pearson_corr_coeff, + manders_coloc_coeff, + manders_overlap_coeff, + intersection_coeff, +) diff --git a/envs/kitoverlay/skimage/measure/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb24d1e16488d7b1a17b816a240631a58cae23e4 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_blur_effect.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_blur_effect.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..075738ff47cc8578a1f995e4e09d2b8164ad0946 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_blur_effect.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_colocalization.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_colocalization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735830511226dc2eb3269905a69a06bf5d744cd4 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_colocalization.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_find_contours.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_find_contours.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d6bac2fc7acf79601ce90253119ec1eb9cd34b9 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_find_contours.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_label.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_label.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8afa43ab928b767da82728c24b93f8fadf13090 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_label.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae0da7cda3735abac563ad27ff6f4201bbd4d29 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_marching_cubes_lewiner.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_moments_analytical.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_moments_analytical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d68f699615c59c9bfc878ede7b4f43e05f094ee1 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_moments_analytical.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_polygon.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_polygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2972d039c1184e4c3f2f6c59f08bd09d4a8cb381 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_polygon.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/_regionprops.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/_regionprops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fc088caaf075ddfb782f68e4478b9d1b204408c Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/_regionprops.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/block.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/block.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3040cd97bc7bb1080f9b61f8cba227a6338bbb0f Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/block.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/fit.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/fit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4229bd18d8e28f6126253a40de2016ed75289f7 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/fit.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/pnpoly.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/pnpoly.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c28fda820241936d806ec557df62d0b2ef9443d Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/pnpoly.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/__pycache__/profile.cpython-311.pyc b/envs/kitoverlay/skimage/measure/__pycache__/profile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21f6fb0055b873bccfff20c0bbed4ac98ccd0424 Binary files /dev/null and b/envs/kitoverlay/skimage/measure/__pycache__/profile.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/measure/_blur_effect.py b/envs/kitoverlay/skimage/measure/_blur_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cead0070a5841ca2fb256531cae1fe31f02333 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_blur_effect.py @@ -0,0 +1,98 @@ +import numpy as np +import scipy.ndimage as ndi + +from ..color import rgb2gray +from ..util import img_as_float + +# TODO: when minimum numpy dependency is 1.25 use: +# np..exceptions.AxisError instead of AxisError +# and remove this try-except +try: + from numpy import AxisError +except ImportError: + from numpy.exceptions import AxisError + + +__all__ = ['blur_effect'] + + +_EPSILON = np.spacing(np.float64(1)) + + +def blur_effect(image, h_size=11, channel_axis=None, reduce_func=np.max): + """Compute a metric that indicates the strength of blur in an image + (0 for no blur, 1 for maximal blur). + + Parameters + ---------- + image : ndarray + RGB or grayscale nD image. The input image is converted to grayscale + before computing the blur metric. + h_size : int, optional + Size of the re-blurring filter. + channel_axis : int or None, optional + If None, the image is assumed to be grayscale (single-channel). + Otherwise, this parameter indicates which axis of the array + corresponds to color channels. + reduce_func : callable, optional + Function used to calculate the aggregation of blur metrics along all + axes. If set to None, the entire list is returned, where the i-th + element is the blur metric along the i-th axis. + + Returns + ------- + blur : float (0 to 1) or list of floats + Blur metric: by default, the maximum of blur metrics along all axes. + + Notes + ----- + `h_size` must keep the same value in order to compare results between + images. Most of the time, the default size (11) is enough. This means that + the metric can clearly discriminate blur up to an average 11x11 filter; if + blur is higher, the metric still gives good results but its values tend + towards an asymptote. + + References + ---------- + .. [1] Frederique Crete, Thierry Dolmiere, Patricia Ladret, and Marina + Nicolas "The blur effect: perception and estimation with a new + no-reference perceptual blur metric" Proc. SPIE 6492, Human Vision and + Electronic Imaging XII, 64920I (2007) + https://hal.archives-ouvertes.fr/hal-00232709 + :DOI:`10.1117/12.702790` + """ + + if channel_axis is not None: + try: + # ensure color channels are in the final dimension + image = np.moveaxis(image, channel_axis, -1) + except AxisError: + print('channel_axis must be one of the image array dimensions') + raise + except TypeError: + print('channel_axis must be an integer') + raise + image = rgb2gray(image) + n_axes = image.ndim + image = img_as_float(image) + shape = image.shape + B = [] + + from ..filters import sobel + + slices = tuple([slice(2, s - 1) for s in shape]) + for ax in range(n_axes): + filt_im = ndi.uniform_filter1d(image, h_size, axis=ax) + im_sharp = np.abs(sobel(image, axis=ax)) + im_blur = np.abs(sobel(filt_im, axis=ax)) + + # avoid numerical instabilities + im_sharp = np.maximum(_EPSILON, im_sharp) + im_blur = np.maximum(_EPSILON, im_blur) + + T = np.maximum(0, im_sharp - im_blur) + M1 = np.sum(im_sharp[slices]) + M2 = np.sum(T[slices]) + B.append(np.abs(M1 - M2) / M1) + + return B if reduce_func is None else reduce_func(B) diff --git a/envs/kitoverlay/skimage/measure/_colocalization.py b/envs/kitoverlay/skimage/measure/_colocalization.py new file mode 100644 index 0000000000000000000000000000000000000000..731409d7ed380c1c9cd91de02ba422a376d3b474 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_colocalization.py @@ -0,0 +1,305 @@ +import numpy as np +from scipy.stats import pearsonr + +from .._shared.utils import check_shape_equality, as_binary_ndarray + +__all__ = [ + 'pearson_corr_coeff', + 'manders_coloc_coeff', + 'manders_overlap_coeff', + 'intersection_coeff', +] + + +def pearson_corr_coeff(image0, image1, mask=None): + r"""Calculate Pearson's Correlation Coefficient between pixel intensities + in channels. + + Parameters + ---------- + image0 : (M, N) ndarray + Image of channel A. + image1 : (M, N) ndarray + Image of channel 2 to be correlated with channel B. + Must have same dimensions as `image0`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0` and `image1` pixels within this region of interest mask + are included in the calculation. Must have same dimensions as `image0`. + + Returns + ------- + pcc : float + Pearson's correlation coefficient of the pixel intensities between + the two images, within the mask if provided. + p-value : float + Two-tailed p-value. + + Notes + ----- + Pearson's Correlation Coefficient (PCC) measures the linear correlation + between the pixel intensities of the two images. Its value ranges from -1 + for perfect linear anti-correlation to +1 for perfect linear correlation. + The calculation of the p-value assumes that the intensities of pixels in + each input image are normally distributed. + + Scipy's implementation of Pearson's correlation coefficient is used. Please + refer to it for further information and caveats [1]_. + + .. math:: + r = \frac{\sum (A_i - m_A_i) (B_i - m_B_i)} + {\sqrt{\sum (A_i - m_A_i)^2 \sum (B_i - m_B_i)^2}} + + where + :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0` + :math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`, + :math:`m_A_i` is the mean of the pixel values in `image0` + :math:`m_B_i` is the mean of the pixel values in `image1` + + A low PCC value does not necessarily mean that there is no correlation + between the two channel intensities, just that there is no linear + correlation. You may wish to plot the pixel intensities of each of the two + channels in a 2D scatterplot and use Spearman's rank correlation if a + non-linear correlation is visually identified [2]_. Also consider if you + are interested in correlation or co-occurence, in which case a method + involving segmentation masks (e.g. MCC or intersection coefficient) may be + more suitable [3]_ [4]_. + + Providing the mask of only relevant sections of the image (e.g., cells, or + particular cellular compartments) and removing noise is important as the + PCC is sensitive to these measures [3]_ [4]_. + + References + ---------- + .. [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html + .. [2] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html + .. [3] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + .. [4] Bolte, S. and Cordelières, F.P. (2006), A guided tour into + subcellular colocalization analysis in light microscopy. Journal of + Microscopy, 224: 213-232. + https://doi.org/10.1111/j.1365-2818.2006.01706.x + """ + image0 = np.asarray(image0) + image1 = np.asarray(image1) + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1, mask) + image0 = image0[mask] + image1 = image1[mask] + else: + check_shape_equality(image0, image1) + # scipy pearsonr function only takes flattened arrays + image0 = image0.reshape(-1) + image1 = image1.reshape(-1) + + return tuple(float(v) for v in pearsonr(image0, image1)) + + +def manders_coloc_coeff(image0, image1_mask, mask=None): + r"""Manders' colocalization coefficient between two image channels. + + Parameters + ---------- + image0 : (M, N) ndarray + Input image (first channel). All pixel values should be non-negative. + image1_mask : (M, N) ndarray of dtype bool + Binary image giving the regions of interest in the second channel. + Must have same shape as `image0`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0` pixel values within `mask` are included in the calculation. + Must have same shape as `image0`. + + Returns + ------- + mcc : float + Manders' colocalization coefficient. + + Notes + ----- + Manders' colocalization coefficient (MCC) was developed in the context of + confocal biological microscopy, to measure the fraction of colocalizing + objects in each component of a dual-channel image. Out of the total + intensity of, say, channel A, how much is found within the features + (objects) of, say, channel B [1]_? The measure thus ranges from 0 for no + colocalization to 1 for complete colocalization. + + MCC is commonly used to measure the colocalization of a particular protein + in a subcelullar compartment. Typically, the mask for channel B is + obtained by thresholding, to segment the features from the background. + In this implementation, channel B is passed directly as a mask + (`image1_mask`), leaving the segmentation step to the user (upstream). + + The implemented equation is: + + .. math:: + + mcc = \frac{\sum_i A_{i,coloc}}{\sum_i A_i} + + where + + - :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`, and + - :math:`A_{i, coloc} = A_i B_i`, considering that :math:`B_i` is the + (``True`` or ``False``) value of the :math:`i^{th}` pixel in + `image1_mask` cast into int or float (``1`` or ``0``, respectively). + + MCC is sensitive to noise, with diffuse signal in the first channel + inflating its value. Therefore, images should be processed beforehand to + remove out-of-focus and background light [2]_. + + References + ---------- + .. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of + co-localization of objects in dual-colour confocal images. Journal + of Microscopy, 169: 375-382. + https://doi.org/10.1111/j.1365-2818.1993.tb03313.x + https://imagej.net/media/manders.pdf + .. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + + """ + image0 = np.asarray(image0) + image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask") + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1_mask, mask) + image0 = image0[mask] + image1_mask = image1_mask[mask] + else: + check_shape_equality(image0, image1_mask) + # check non-negative image + if image0.min() < 0: + raise ValueError("image contains negative values") + + sum = np.sum(image0) + if sum == 0: + return 0 + return np.sum(image0 * image1_mask) / sum + + +def manders_overlap_coeff(image0, image1, mask=None): + r"""Manders' overlap coefficient + + Parameters + ---------- + image0 : (M, N) ndarray + Image of channel A. All pixel values should be non-negative. + image1 : (M, N) ndarray + Image of channel B. All pixel values should be non-negative. + Must have same dimensions as `image0` + mask : (M, N) ndarray of dtype bool, optional + Only `image0` and `image1` pixel values within this region of interest + mask are included in the calculation. + Must have ♣same dimensions as `image0`. + + Returns + ------- + moc: float + Manders' Overlap Coefficient of pixel intensities between the two + images. + + Notes + ----- + Manders' Overlap Coefficient (MOC) is given by the equation [1]_: + + .. math:: + r = \frac{\sum A_i B_i}{\sqrt{\sum A_i^2 \sum B_i^2}} + + where + :math:`A_i` is the value of the :math:`i^{th}` pixel in `image0` + :math:`B_i` is the value of the :math:`i^{th}` pixel in `image1` + + It ranges between 0 for no colocalization and 1 for complete colocalization + of all pixels. + + MOC does not take into account pixel intensities, just the fraction of + pixels that have positive values for both channels[2]_ [3]_. Its usefulness + has been criticized as it changes in response to differences in both + co-occurence and correlation and so a particular MOC value could indicate + a wide range of colocalization patterns [4]_ [5]_. + + References + ---------- + .. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of + co-localization of objects in dual-colour confocal images. Journal + of Microscopy, 169: 375-382. + https://doi.org/10.1111/j.1365-2818.1993.tb03313.x + https://imagej.net/media/manders.pdf + .. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical + guide to evaluating colocalization in biological microscopy. + American journal of physiology. Cell physiology, 300(4), C723–C742. + https://doi.org/10.1152/ajpcell.00462.2010 + .. [3] Bolte, S. and Cordelières, F.P. (2006), A guided tour into + subcellular colocalization analysis in light microscopy. Journal of + Microscopy, 224: 213-232. + https://doi.org/10.1111/j.1365-2818.2006.01 + .. [4] Adler J, Parmryd I. (2010), Quantifying colocalization by + correlation: the Pearson correlation coefficient is + superior to the Mander's overlap coefficient. Cytometry A. + Aug;77(8):733-42.https://doi.org/10.1002/cyto.a.20896 + .. [5] Adler, J, Parmryd, I. Quantifying colocalization: The case for + discarding the Manders overlap coefficient. Cytometry. 2021; 99: + 910– 920. https://doi.org/10.1002/cyto.a.24336 + + """ + image0 = np.asarray(image0) + image1 = np.asarray(image1) + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0, image1, mask) + image0 = image0[mask] + image1 = image1[mask] + else: + check_shape_equality(image0, image1) + + # check non-negative image + if image0.min() < 0: + raise ValueError("image0 contains negative values") + if image1.min() < 0: + raise ValueError("image1 contains negative values") + + denom = (np.sum(np.square(image0)) * (np.sum(np.square(image1)))) ** 0.5 + return np.sum(np.multiply(image0, image1)) / denom + + +def intersection_coeff(image0_mask, image1_mask, mask=None): + r"""Fraction of a channel's segmented binary mask that overlaps with a + second channel's segmented binary mask. + + Parameters + ---------- + image0_mask : (M, N) ndarray of dtype bool + Image mask of channel A. + image1_mask : (M, N) ndarray of dtype bool + Image mask of channel B. + Must have same dimensions as `image0_mask`. + mask : (M, N) ndarray of dtype bool, optional + Only `image0_mask` and `image1_mask` pixels within this region of + interest + mask are included in the calculation. + Must have same dimensions as `image0_mask`. + + Returns + ------- + Intersection coefficient, float + Fraction of `image0_mask` that overlaps with `image1_mask`. + + """ + image0_mask = as_binary_ndarray(image0_mask, variable_name="image0_mask") + image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask") + if mask is not None: + mask = as_binary_ndarray(mask, variable_name="mask") + check_shape_equality(image0_mask, image1_mask, mask) + image0_mask = image0_mask[mask] + image1_mask = image1_mask[mask] + else: + check_shape_equality(image0_mask, image1_mask) + + nonzero_image0 = np.count_nonzero(image0_mask) + if nonzero_image0 == 0: + return 0 + nonzero_joint = np.count_nonzero(np.logical_and(image0_mask, image1_mask)) + return nonzero_joint / nonzero_image0 diff --git a/envs/kitoverlay/skimage/measure/_find_contours.py b/envs/kitoverlay/skimage/measure/_find_contours.py new file mode 100644 index 0000000000000000000000000000000000000000..c32fa743b237f20a0a513c1addff50a3e0fdb1cf --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_find_contours.py @@ -0,0 +1,218 @@ +import numpy as np + +from ._find_contours_cy import _get_contour_segments + +from collections import deque + +_param_options = ('high', 'low') + + +def find_contours( + image, level=None, fully_connected='low', positive_orientation='low', *, mask=None +): + """Find iso-valued contours in a 2D array for a given level value. + + Uses the "marching squares" method to compute the iso-valued contours of + the input 2D array for a particular level value. Array values are linearly + interpolated to provide better precision for the output contours. + + Parameters + ---------- + image : (M, N) ndarray of double + Input image in which to find contours. + level : float, optional + Value along which to find contours in the array. By default, the level + is set to (max(image) + min(image)) / 2 + + .. versionchanged:: 0.18 + This parameter is now optional. + fully_connected : str, {'low', 'high'} + Indicates whether array elements below the given level value are to be + considered fully-connected (and hence elements above the value will + only be face connected), or vice-versa. (See notes below for details.) + positive_orientation : str, {'low', 'high'} + Indicates whether the output contours will produce positively-oriented + polygons around islands of low- or high-valued elements. If 'low' then + contours will wind counter-clockwise around elements below the + iso-value. Alternately, this means that low-valued elements are always + on the left of the contour. (See below for details.) + mask : (M, N) ndarray of bool or None + A boolean mask, True where we want to draw contours. + Note that NaN values are always excluded from the considered region + (``mask`` is set to ``False`` wherever ``array`` is ``NaN``). + + Returns + ------- + contours : list of (K, 2) ndarrays + Each contour is a ndarray of ``(row, column)`` coordinates along the contour. + + See Also + -------- + skimage.measure.marching_cubes + + Notes + ----- + The marching squares algorithm is a special case of the marching cubes + algorithm [1]_. A simple explanation is available here: + + https://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html + + There is a single ambiguous case in the marching squares algorithm: when + a given ``2 x 2``-element square has two high-valued and two low-valued + elements, each pair diagonally adjacent. (Where high- and low-valued is + with respect to the contour value sought.) In this case, either the + high-valued elements can be 'connected together' via a thin isthmus that + separates the low-valued elements, or vice-versa. When elements are + connected together across a diagonal, they are considered 'fully + connected' (also known as 'face+vertex-connected' or '8-connected'). Only + high-valued or low-valued elements can be fully-connected, the other set + will be considered as 'face-connected' or '4-connected'. By default, + low-valued elements are considered fully-connected; this can be altered + with the 'fully_connected' parameter. + + Output contours are not guaranteed to be closed: contours which intersect + the array edge or a masked-off region (either where mask is False or where + array is NaN) will be left open. All other contours will be closed. (The + closed-ness of a contours can be tested by checking whether the beginning + point is the same as the end point.) + + Contours are oriented. By default, array values lower than the contour + value are to the left of the contour and values greater than the contour + value are to the right. This means that contours will wind + counter-clockwise (i.e. in 'positive orientation') around islands of + low-valued pixels. This behavior can be altered with the + 'positive_orientation' parameter. + + The order of the contours in the output list is determined by the position + of the smallest ``x,y`` (in lexicographical order) coordinate in the + contour. This is a side effect of how the input array is traversed, but + can be relied upon. + + .. warning:: + + Array coordinates/values are assumed to refer to the *center* of the + array element. Take a simple example input: ``[0, 1]``. The interpolated + position of 0.5 in this array is midway between the 0-element (at + ``x=0``) and the 1-element (at ``x=1``), and thus would fall at + ``x=0.5``. + + This means that to find reasonable contours, it is best to find contours + midway between the expected "light" and "dark" values. In particular, + given a binarized array, *do not* choose to find contours at the low or + high value of the array. This will often yield degenerate contours, + especially around structures that are a single array element wide. Instead, + choose a middle value, as above. + + References + ---------- + .. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High + Resolution 3D Surface Construction Algorithm. Computer Graphics + (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). + :DOI:`10.1145/37401.37422` + + Examples + -------- + >>> a = np.zeros((3, 3)) + >>> a[0, 0] = 1 + >>> a + array([[1., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> find_contours(a, 0.5) + [array([[0. , 0.5], + [0.5, 0. ]])] + """ + if fully_connected not in _param_options: + raise ValueError( + 'Parameters "fully_connected" must be either ' '"high" or "low".' + ) + if positive_orientation not in _param_options: + raise ValueError( + 'Parameters "positive_orientation" must be either ' '"high" or "low".' + ) + if image.shape[0] < 2 or image.shape[1] < 2: + raise ValueError("Input array must be at least 2x2.") + if image.ndim != 2: + raise ValueError('Only 2D arrays are supported.') + if mask is not None: + if mask.shape != image.shape: + raise ValueError('Parameters "array" and "mask"' ' must have same shape.') + if not np.can_cast(mask.dtype, bool, casting='safe'): + raise TypeError('Parameter "mask" must be a binary array.') + mask = mask.astype(np.uint8, copy=False) + if level is None: + level = (np.nanmin(image) + np.nanmax(image)) / 2.0 + + segments = _get_contour_segments( + image.astype(np.float64), float(level), fully_connected == 'high', mask=mask + ) + contours = _assemble_contours(segments) + if positive_orientation == 'high': + contours = [c[::-1] for c in contours] + return contours + + +def _assemble_contours(segments): + current_index = 0 + contours = {} + starts = {} + ends = {} + for from_point, to_point in segments: + # Ignore degenerate segments. + # This happens when (and only when) one vertex of the square is + # exactly the contour level, and the rest are above or below. + # This degenerate vertex will be picked up later by neighboring + # squares. + if from_point == to_point: + continue + + tail, tail_num = starts.pop(to_point, (None, None)) + head, head_num = ends.pop(from_point, (None, None)) + + if tail is not None and head is not None: + # We need to connect these two contours. + if tail is head: + # We need to closed a contour: add the end point + head.append(to_point) + else: # tail is not head + # We need to join two distinct contours. + # We want to keep the first contour segment created, so that + # the final contours are ordered left->right, top->bottom. + if tail_num > head_num: + # tail was created second. Append tail to head. + head.extend(tail) + # Remove tail from the detected contours + contours.pop(tail_num, None) + # Update starts and ends + starts[head[0]] = (head, head_num) + ends[head[-1]] = (head, head_num) + else: # tail_num <= head_num + # head was created second. Prepend head to tail. + tail.extendleft(reversed(head)) + # Remove head from the detected contours + starts.pop(head[0], None) # head[0] can be == to_point! + contours.pop(head_num, None) + # Update starts and ends + starts[tail[0]] = (tail, tail_num) + ends[tail[-1]] = (tail, tail_num) + elif tail is None and head is None: + # We need to add a new contour + new_contour = deque((from_point, to_point)) + contours[current_index] = new_contour + starts[from_point] = (new_contour, current_index) + ends[to_point] = (new_contour, current_index) + current_index += 1 + elif head is None: # tail is not None + # tail first element is to_point: the new segment should be + # prepended. + tail.appendleft(from_point) + # Update starts + starts[from_point] = (tail, tail_num) + else: # tail is None and head is not None: + # head last element is from_point: the new segment should be + # appended + head.append(to_point) + # Update ends + ends[to_point] = (head, head_num) + + return [np.array(contour) for _, contour in sorted(contours.items())] diff --git a/envs/kitoverlay/skimage/measure/_label.py b/envs/kitoverlay/skimage/measure/_label.py new file mode 100644 index 0000000000000000000000000000000000000000..786b99a24f130c2c06d3533dfcb497602d980441 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_label.py @@ -0,0 +1,125 @@ +from scipy import ndimage +from ._ccomp import label_cython as clabel + + +def _label_bool(image, background=None, return_num=False, connectivity=None): + """Faster implementation of clabel for boolean input. + + See context: https://github.com/scikit-image/scikit-image/issues/4833 + """ + from ..morphology._util import _resolve_neighborhood + + if background == 1: + image = ~image + + if connectivity is None: + connectivity = image.ndim + + if not 1 <= connectivity <= image.ndim: + raise ValueError( + f'Connectivity for {image.ndim}D image should ' + f'be in [1, ..., {image.ndim}]. Got {connectivity}.' + ) + + footprint = _resolve_neighborhood(None, connectivity, image.ndim) + result = ndimage.label(image, structure=footprint) + + if return_num: + return result + else: + return result[0] + + +def label(label_image, background=None, return_num=False, connectivity=None): + r"""Label connected regions of an integer array. + + Two pixels are connected when they are neighbors and have the same value. + In 2D, they can be neighbors either in a 1- or 2-connected sense. + The value refers to the maximum number of orthogonal hops to consider a + pixel/voxel a neighbor:: + + 1-connectivity 2-connectivity diagonal connection close-up + + [ ] [ ] [ ] [ ] [ ] + | \ | / | <- hop 2 + [ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ] + | / | \ hop 1 + [ ] [ ] [ ] [ ] + + Parameters + ---------- + label_image : ndarray of dtype int + Image to label. + background : int, optional + Consider all pixels with this value as background pixels, and label + them as 0. By default, 0-valued pixels are considered as background + pixels. + return_num : bool, optional + Whether to return the number of assigned labels. + connectivity : int, optional + Maximum number of orthogonal hops to consider a pixel/voxel + as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. + + Returns + ------- + labels : ndarray of dtype int + Labeled array, where all connected regions are assigned the + same integer value. + num : int, optional + Number of labels, which equals the maximum label index and is only + returned if return_num is `True`. + + See Also + -------- + skimage.measure.regionprops + skimage.measure.regionprops_table + + References + ---------- + .. [1] Christophe Fiorio and Jens Gustedt, "Two linear time Union-Find + strategies for image processing", Theoretical Computer Science + 154 (1996), pp. 165-181. + .. [2] Kensheng Wu, Ekow Otoo and Arie Shoshani, "Optimizing connected + component labeling algorithms", Paper LBNL-56864, 2005, + Lawrence Berkeley National Laboratory (University of California), + http://repositories.cdlib.org/lbnl/LBNL-56864 + + Examples + -------- + >>> import numpy as np + >>> x = np.eye(3).astype(int) + >>> print(x) + [[1 0 0] + [0 1 0] + [0 0 1]] + >>> print(label(x, connectivity=1)) + [[1 0 0] + [0 2 0] + [0 0 3]] + >>> print(label(x, connectivity=2)) + [[1 0 0] + [0 1 0] + [0 0 1]] + >>> print(label(x, background=-1)) + [[1 2 2] + [2 1 2] + [2 2 1]] + >>> x = np.array([[1, 0, 0], + ... [1, 1, 5], + ... [0, 0, 0]]) + >>> print(label(x)) + [[1 0 0] + [1 1 2] + [0 0 0]] + """ + if label_image.dtype == bool: + return _label_bool( + label_image, + background=background, + return_num=return_num, + connectivity=connectivity, + ) + else: + return clabel(label_image, background, return_num, connectivity) diff --git a/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner.py b/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner.py new file mode 100644 index 0000000000000000000000000000000000000000..eac02bfd3163f87ca68fcf268002f79422be5fe9 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner.py @@ -0,0 +1,352 @@ +import base64 + +import numpy as np + +from . import _marching_cubes_lewiner_luts as mcluts +from . import _marching_cubes_lewiner_cy + + +def marching_cubes( + volume, + level=None, + *, + spacing=(1.0, 1.0, 1.0), + gradient_direction='descent', + step_size=1, + allow_degenerate=True, + method='lewiner', + mask=None, +): + """Marching cubes algorithm to find surfaces in 3d volumetric data. + + In contrast with Lorensen et al. approach [2]_, Lewiner et + al. algorithm is faster, resolves ambiguities, and guarantees + topologically correct results. Therefore, this algorithm generally + a better choice. + + Parameters + ---------- + volume : (M, N, P) ndarray + Input data volume to find isosurfaces. Will internally be + converted to float32 if necessary. + level : float, optional + Contour value to search for isosurfaces in `volume`. If not + given or None, the average of the min and max of vol is used. + spacing : length-3 tuple of floats, optional + Voxel spacing in spatial dimensions corresponding to numpy array + indexing dimensions (M, N, P) as in `volume`. + gradient_direction : {'descent', 'ascent'}, optional + Controls if the mesh was generated from an isosurface with gradient + descent toward objects of interest (the default), or the opposite, + considering the *left-hand* rule. + The two options are: + * descent : Object was greater than exterior + * ascent : Exterior was greater than object + step_size : int, optional + Step size in voxels. Default 1. Larger steps yield faster but + coarser results. The result will always be topologically correct + though. + allow_degenerate : bool, optional + Whether to allow degenerate (i.e. zero-area) triangles in the + end-result. Default True. If False, degenerate triangles are + removed, at the cost of making the algorithm slower. + method : {'lewiner', 'lorensen'}, optional + Whether the method of Lewiner et al. or Lorensen et al. will be used. + mask : (M, N, P) array, optional + Boolean array. The marching cube algorithm will be computed only on + True elements. This will save computational time when interfaces + are located within certain region of the volume M, N, P-e.g. the top + half of the cube-and also allow to compute finite surfaces-i.e. open + surfaces that do not end at the border of the cube. + + Returns + ------- + verts : (V, 3) array + Spatial coordinates for V unique mesh vertices. Coordinate order + matches input `volume` (M, N, P). If ``allow_degenerate`` is set to + True, then the presence of degenerate triangles in the mesh can make + this array have duplicate vertices. + faces : (F, 3) array + Define triangular faces via referencing vertex indices from ``verts``. + This algorithm specifically outputs triangles, so each face has + exactly three indices. + normals : (V, 3) array + The normal direction at each vertex, as calculated from the + data. + values : (V,) array + Gives a measure for the maximum value of the data in the local region + near each vertex. This can be used by visualization tools to apply + a colormap to the mesh. + + See Also + -------- + skimage.measure.mesh_surface_area + skimage.measure.find_contours + + Notes + ----- + The algorithm [1]_ is an improved version of Chernyaev's Marching + Cubes 33 algorithm. It is an efficient algorithm that relies on + heavy use of lookup tables to handle the many different cases, + keeping the algorithm relatively easy. This implementation is + written in Cython, ported from Lewiner's C++ implementation. + + To quantify the area of an isosurface generated by this algorithm, pass + verts and faces to `skimage.measure.mesh_surface_area`. + + Regarding visualization of algorithm output, to contour a volume + named `myvolume` about the level 0.0, using the ``mayavi`` package:: + + >>> + >> from mayavi import mlab + >> verts, faces, _, _ = marching_cubes(myvolume, 0.0) + >> mlab.triangular_mesh([vert[0] for vert in verts], + [vert[1] for vert in verts], + [vert[2] for vert in verts], + faces) + >> mlab.show() + + Similarly using the ``visvis`` package:: + + >>> + >> import visvis as vv + >> verts, faces, normals, values = marching_cubes(myvolume, 0.0) + >> vv.mesh(np.fliplr(verts), faces, normals, values) + >> vv.use().Run() + + To reduce the number of triangles in the mesh for better performance, + see this `example + `_ + using the ``mayavi`` package. + + References + ---------- + .. [1] Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan + Tavares. Efficient implementation of Marching Cubes' cases with + topological guarantees. Journal of Graphics Tools 8(2) + pp. 1-15 (december 2003). + :DOI:`10.1080/10867651.2003.10487582` + .. [2] Lorensen, William and Harvey E. Cline. Marching Cubes: A High + Resolution 3D Surface Construction Algorithm. Computer Graphics + (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). + :DOI:`10.1145/37401.37422` + """ + use_classic = False + if method == 'lorensen': + use_classic = True + elif method != 'lewiner': + raise ValueError("method should be either 'lewiner' or 'lorensen'") + return _marching_cubes_lewiner( + volume, + level, + spacing, + gradient_direction, + step_size, + allow_degenerate, + use_classic=use_classic, + mask=mask, + ) + + +def _marching_cubes_lewiner( + volume, + level, + spacing, + gradient_direction, + step_size, + allow_degenerate, + use_classic, + mask, +): + """Lewiner et al. algorithm for marching cubes. See + marching_cubes_lewiner for documentation. + + """ + + # Check volume and ensure its in the format that the alg needs + if not isinstance(volume, np.ndarray) or (volume.ndim != 3): + raise ValueError('Input volume should be a 3D numpy array.') + if volume.shape[0] < 2 or volume.shape[1] < 2 or volume.shape[2] < 2: + raise ValueError("Input array must be at least 2x2x2.") + volume = np.ascontiguousarray(volume, np.float32) # no copy if not necessary + + # Check/convert other inputs: + # level + if level is None: + level = 0.5 * (volume.min() + volume.max()) + else: + level = float(level) + if level < volume.min() or level > volume.max(): + raise ValueError("Surface level must be within volume data range.") + # spacing + if len(spacing) != 3: + raise ValueError("`spacing` must consist of three floats.") + # step_size + step_size = int(step_size) + if step_size < 1: + raise ValueError('step_size must be at least one.') + # use_classic + use_classic = bool(use_classic) + + # Get LutProvider class (reuse if possible) + L = _get_mc_luts() + + # Check if a mask array is passed + if mask is not None: + if not mask.shape == volume.shape: + raise ValueError('volume and mask must have the same shape.') + + # Apply algorithm + func = _marching_cubes_lewiner_cy.marching_cubes + vertices, faces, normals, values = func( + volume, level, L, step_size, use_classic, mask + ) + + if not len(vertices): + raise RuntimeError('No surface found at the given iso value.') + + # Output in z-y-x order, as is common in skimage + vertices = np.fliplr(vertices) + normals = np.fliplr(normals) + + # Finishing touches to output + faces.shape = -1, 3 + if gradient_direction == 'descent': + # MC implementation is right-handed, but gradient_direction is + # left-handed + faces = np.fliplr(faces) + elif not gradient_direction == 'ascent': + raise ValueError( + f"Incorrect input {gradient_direction} in `gradient_direction`, " + "see docstring." + ) + if not np.array_equal(spacing, (1, 1, 1)): + vertices = vertices * np.r_[spacing] + + if allow_degenerate: + return vertices, faces, normals, values + else: + fun = _marching_cubes_lewiner_cy.remove_degenerate_faces + return fun(vertices.astype(np.float32), faces, normals, values) + + +def _to_array(args): + shape, text = args + byts = base64.decodebytes(text.encode('utf-8')) + ar = np.frombuffer(byts, dtype='int8') + ar.shape = shape + return ar + + +# Map an edge-index to two relative pixel positions. The edge index +# represents a point that lies somewhere in between these pixels. +# Linear interpolation should be used to determine where it is exactly. +# 0 +# 3 1 -> 0x +# 2 xx + +# fmt: off +EDGETORELATIVEPOSX = np.array([ [0,1],[1,1],[1,0],[0,0], [0,1],[1,1],[1,0],[0,0], [0,0],[1,1],[1,1],[0,0] ], 'int8') +EDGETORELATIVEPOSY = np.array([ [0,0],[0,1],[1,1],[1,0], [0,0],[0,1],[1,1],[1,0], [0,0],[0,0],[1,1],[1,1] ], 'int8') +EDGETORELATIVEPOSZ = np.array([ [0,0],[0,0],[0,0],[0,0], [1,1],[1,1],[1,1],[1,1], [0,1],[0,1],[0,1],[0,1] ], 'int8') +# fmt: on + + +def _get_mc_luts(): + """Kind of lazy obtaining of the luts.""" + if not hasattr(mcluts, 'THE_LUTS'): + mcluts.THE_LUTS = _marching_cubes_lewiner_cy.LutProvider( + EDGETORELATIVEPOSX, + EDGETORELATIVEPOSY, + EDGETORELATIVEPOSZ, + _to_array(mcluts.CASESCLASSIC), + _to_array(mcluts.CASES), + _to_array(mcluts.TILING1), + _to_array(mcluts.TILING2), + _to_array(mcluts.TILING3_1), + _to_array(mcluts.TILING3_2), + _to_array(mcluts.TILING4_1), + _to_array(mcluts.TILING4_2), + _to_array(mcluts.TILING5), + _to_array(mcluts.TILING6_1_1), + _to_array(mcluts.TILING6_1_2), + _to_array(mcluts.TILING6_2), + _to_array(mcluts.TILING7_1), + _to_array(mcluts.TILING7_2), + _to_array(mcluts.TILING7_3), + _to_array(mcluts.TILING7_4_1), + _to_array(mcluts.TILING7_4_2), + _to_array(mcluts.TILING8), + _to_array(mcluts.TILING9), + _to_array(mcluts.TILING10_1_1), + _to_array(mcluts.TILING10_1_1_), + _to_array(mcluts.TILING10_1_2), + _to_array(mcluts.TILING10_2), + _to_array(mcluts.TILING10_2_), + _to_array(mcluts.TILING11), + _to_array(mcluts.TILING12_1_1), + _to_array(mcluts.TILING12_1_1_), + _to_array(mcluts.TILING12_1_2), + _to_array(mcluts.TILING12_2), + _to_array(mcluts.TILING12_2_), + _to_array(mcluts.TILING13_1), + _to_array(mcluts.TILING13_1_), + _to_array(mcluts.TILING13_2), + _to_array(mcluts.TILING13_2_), + _to_array(mcluts.TILING13_3), + _to_array(mcluts.TILING13_3_), + _to_array(mcluts.TILING13_4), + _to_array(mcluts.TILING13_5_1), + _to_array(mcluts.TILING13_5_2), + _to_array(mcluts.TILING14), + _to_array(mcluts.TEST3), + _to_array(mcluts.TEST4), + _to_array(mcluts.TEST6), + _to_array(mcluts.TEST7), + _to_array(mcluts.TEST10), + _to_array(mcluts.TEST12), + _to_array(mcluts.TEST13), + _to_array(mcluts.SUBCONFIG13), + ) + + return mcluts.THE_LUTS + + +def mesh_surface_area(verts, faces): + """Compute surface area, given vertices and triangular faces. + + Parameters + ---------- + verts : (V, 3) array of floats + Array containing coordinates for V unique mesh vertices. + faces : (F, 3) array of ints + List of length-3 lists of integers, referencing vertex coordinates as + provided in `verts`. + + Returns + ------- + area : float + Surface area of mesh. Units now [coordinate units] ** 2. + + Notes + ----- + The arguments expected by this function are the first two outputs from + `skimage.measure.marching_cubes`. For unit correct output, ensure correct + `spacing` was passed to `skimage.measure.marching_cubes`. + + This algorithm works properly only if the ``faces`` provided are all + triangles. + + See Also + -------- + skimage.measure.marching_cubes + + """ + # Fancy indexing to define two vector arrays from triangle vertices + actual_verts = verts[faces] + a = actual_verts[:, 0, :] - actual_verts[:, 1, :] + b = actual_verts[:, 0, :] - actual_verts[:, 2, :] + del actual_verts + + # Area of triangle in 3D = 1/2 * Euclidean norm of cross product + return ((np.cross(a, b) ** 2).sum(axis=1) ** 0.5).sum() / 2.0 diff --git a/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner_luts.py b/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner_luts.py new file mode 100644 index 0000000000000000000000000000000000000000..afe5f7c9058b2040d897362411a6a47a63d2b29e --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_marching_cubes_lewiner_luts.py @@ -0,0 +1,672 @@ +# This file was auto-generated from `mc_meta/LookUpTable.h` by +# `mc_meta/createluts.py`. The `mc_meta` scripts are not +# distributed with scikit-image, but are available in the +# repository under tools/precompute/mc_meta. + +# static const char casesClassic[256][16] +CASESCLASSIC = ( + (256, 16), + """ +/////////////////////wAIA/////////////////8AAQn/////////////////AQgDCQgB//// +/////////wECCv////////////////8ACAMBAgr/////////////CQIKAAIJ/////////////wII +AwIKCAoJCP////////8DCwL/////////////////AAsCCAsA/////////////wEJAAIDC/////// +//////8BCwIBCQsJCAv/////////AwoBCwoD/////////////wAKAQAICggLCv////////8DCQAD +CwkLCgn/////////CQgKCggL/////////////wQHCP////////////////8EAwAHAwT///////// +////AAEJCAQH/////////////wQBCQQHAQcDAf////////8BAgoIBAf/////////////AwQHAwAE +AQIK/////////wkCCgkAAggEB/////////8CCgkCCQcCBwMHCQT/////CAQHAwsC//////////// +/wsEBwsCBAIABP////////8JAAEIBAcCAwv/////////BAcLCQQLCQsCCQIB/////wMKAQMLCgcI +BP////////8BCwoBBAsBAAQHCwT/////BAcICQALCQsKCwAD/////wQHCwQLCQkLCv////////8J +BQT/////////////////CQUEAAgD/////////////wAFBAEFAP////////////8IBQQIAwUDAQX/ +////////AQIKCQUE/////////////wMACAECCgQJBf////////8FAgoFBAIEAAL/////////AgoF +AwIFAwUEAwQI/////wkFBAIDC/////////////8ACwIACAsECQX/////////AAUEAAEFAgML//// +/////wIBBQIFCAIICwQIBf////8KAwsKAQMJBQT/////////BAkFAAgBCAoBCAsK/////wUEAAUA +CwULCgsAA/////8FBAgFCAoKCAv/////////CQcIBQcJ/////////////wkDAAkFAwUHA/////// +//8ABwgAAQcBBQf/////////AQUDAwUH/////////////wkHCAkFBwoBAv////////8KAQIJBQAF +AwAFBwP/////CAACCAIFCAUHCgUC/////wIKBQIFAwMFB/////////8HCQUHCAkDCwL///////// +CQUHCQcCCQIAAgcL/////wIDCwABCAEHCAEFB/////8LAgELAQcHAQX/////////CQUICAUHCgED +CgML/////wUHAAUACQcLAAEACgsKAP8LCgALAAMKBQAIAAcFBwD/CwoFBwsF/////////////woG +Bf////////////////8ACAMFCgb/////////////CQABBQoG/////////////wEIAwEJCAUKBv// +//////8BBgUCBgH/////////////AQYFAQIGAwAI/////////wkGBQkABgACBv////////8FCQgF +CAIFAgYDAgj/////AgMLCgYF/////////////wsACAsCAAoGBf////////8AAQkCAwsFCgb///// +////BQoGAQkCCQsCCQgL/////wYDCwYFAwUBA/////////8ACAsACwUABQEFCwb/////AwsGAAMG +AAYFAAUJ/////wYFCQYJCwsJCP////////8FCgYEBwj/////////////BAMABAcDBgUK//////// +/wEJAAUKBggEB/////////8KBgUBCQcBBwMHCQT/////BgECBgUBBAcI/////////wECBQUCBgMA +BAMEB/////8IBAcJAAUABgUAAgb/////BwMJBwkEAwIJBQkGAgYJ/wMLAgcIBAoGBf////////8F +CgYEBwIEAgACBwv/////AAEJBAcIAgMLBQoG/////wkCAQkLAgkECwcLBAUKBv8IBAcDCwUDBQEF +Cwb/////BQELBQsGAQALBwsEAAQL/wAFCQAGBQADBgsGAwgEB/8GBQkGCQsEBwkHCwn/////CgQJ +BgQK/////////////wQKBgQJCgAIA/////////8KAAEKBgAGBAD/////////CAMBCAEGCAYEBgEK +/////wEECQECBAIGBP////////8DAAgBAgkCBAkCBgT/////AAIEBAIG/////////////wgDAggC +BAQCBv////////8KBAkKBgQLAgP/////////AAgCAggLBAkKBAoG/////wMLAgABBgAGBAYBCv// +//8GBAEGAQoECAECAQsICwH/CQYECQMGCQEDCwYD/////wgLAQgBAAsGAQkBBAYEAf8DCwYDBgAA +BgT/////////BgQICwYI/////////////wcKBgcICggJCv////////8ABwMACgcACQoGBwr///// +CgYHAQoHAQcIAQgA/////woGBwoHAQEHA/////////8BAgYBBggBCAkIBgf/////AgYJAgkBBgcJ +AAkDBwMJ/wcIAAcABgYAAv////////8HAwIGBwL/////////////AgMLCgYICggJCAYH/////wIA +BwIHCwAJBwYHCgkKB/8BCAABBwgBCgcGBwoCAwv/CwIBCwEHCgYBBgcB/////wgJBggGBwkBBgsG +AwEDBv8ACQELBgf/////////////BwgABwAGAwsACwYA/////wcLBv////////////////8HBgv/ +////////////////AwAICwcG/////////////wABCQsHBv////////////8IAQkIAwELBwb///// +////CgECBgsH/////////////wECCgMACAYLB/////////8CCQACCgkGCwf/////////BgsHAgoD +CggDCgkI/////wcCAwYCB/////////////8HAAgHBgAGAgD/////////AgcGAgMHAAEJ//////// +/wEGAgEIBgEJCAgHBv////8KBwYKAQcBAwf/////////CgcGAQcKAQgHAQAI/////wADBwAHCgAK +CQYKB/////8HBgoHCggICgn/////////BggECwgG/////////////wMGCwMABgAEBv////////8I +BgsIBAYJAAH/////////CQQGCQYDCQMBCwMG/////wYIBAYLCAIKAf////////8BAgoDAAsABgsA +BAb/////BAsIBAYLAAIJAgoJ/////woJAwoDAgkEAwsDBgQGA/8IAgMIBAIEBgL/////////AAQC +BAYC/////////////wEJAAIDBAIEBgQDCP////8BCQQBBAICBAb/////////CAEDCAYBCAQGBgoB +/////woBAAoABgYABP////////8EBgMEAwgGCgMAAwkKCQP/CgkEBgoE/////////////wQJBQcG +C/////////////8ACAMECQULBwb/////////BQABBQQABwYL/////////wsHBggDBAMFBAMBBf// +//8JBQQKAQIHBgv/////////BgsHAQIKAAgDBAkF/////wcGCwUECgQCCgQAAv////8DBAgDBQQD +AgUKBQILBwb/BwIDBwYCBQQJ/////////wkFBAAIBgAGAgYIB/////8DBgIDBwYBBQAFBAD///// +BgIIBggHAgEIBAgFAQUI/wkFBAoBBgEHBgEDB/////8BBgoBBwYBAAcIBwAJBQT/BAAKBAoFAAMK +BgoHAwcK/wcGCgcKCAUECgQICv////8GCQUGCwkLCAn/////////AwYLAAYDAAUGAAkF/////wAL +CAAFCwABBQUGC/////8GCwMGAwUFAwH/////////AQIKCQULCQsICwUG/////wALAwAGCwAJBgUG +CQECCv8LCAULBQYIAAUKBQIAAgX/BgsDBgMFAgoDCgUD/////wUICQUCCAUGAgMIAv////8JBQYJ +BgAABgL/////////AQUIAQgABQYIAwgCBgII/wEFBgIBBv////////////8BAwYBBgoDCAYFBgkI +CQb/CgEACgAGCQUABQYA/////wADCAUGCv////////////8KBQb/////////////////CwUKBwUL +/////////////wsFCgsHBQgDAP////////8FCwcFCgsBCQD/////////CgcFCgsHCQgBCAMB//// +/wsBAgsHAQcFAf////////8ACAMBAgcBBwUHAgv/////CQcFCQIHCQACAgsH/////wcFAgcCCwUJ +AgMCCAkIAv8CBQoCAwUDBwX/////////CAIACAUCCAcFCgIF/////wkAAQUKAwUDBwMKAv////8J +CAIJAgEIBwIKAgUHBQL/AQMFAwcF/////////////wAIBwAHAQEHBf////////8JAAMJAwUFAwf/ +////////CQgHBQkH/////////////wUIBAUKCAoLCP////////8FAAQFCwAFCgsLAwD/////AAEJ +CAQKCAoLCgQF/////woLBAoEBQsDBAkEAQMBBP8CBQECCAUCCwgEBQj/////AAQLAAsDBAULAgsB +BQEL/wACBQAFCQILBQQFCAsIBf8JBAUCCwP/////////////AgUKAwUCAwQFAwgE/////wUKAgUC +BAQCAP////////8DCgIDBQoDCAUEBQgAAQn/BQoCBQIEAQkCCQQC/////wgEBQgFAwMFAf////// +//8ABAUBAAX/////////////CAQFCAUDCQAFAAMF/////wkEBf////////////////8ECwcECQsJ +Cgv/////////AAgDBAkHCQsHCQoL/////wEKCwELBAEEAAcEC/////8DAQQDBAgBCgQHBAsKCwT/ +BAsHCQsECQILCQEC/////wkHBAkLBwkBCwILAQAIA/8LBwQLBAICBAD/////////CwcECwQCCAME +AwIE/////wIJCgIHCQIDBwcECf////8JCgcJBwQKAgcIBwACAAf/AwcKAwoCBwQKAQoABAAK/wEK +AggHBP////////////8ECQEEAQcHAQP/////////BAkBBAEHAAgBCAcB/////wQAAwcEA/////// +//////8ECAf/////////////////CQoICgsI/////////////wMACQMJCwsJCv////////8AAQoA +CggICgv/////////AwEKCwMK/////////////wECCwELCQkLCP////////8DAAkDCQsBAgkCCwn/ +////AAILCAAL/////////////wMCC/////////////////8CAwgCCAoKCAn/////////CQoCAAkC +/////////////wIDCAIICgABCAEKCP////8BCgL/////////////////AQMICQEI//////////// +/wAJAf////////////////8AAwj//////////////////////////////////////w== +""", +) + +# static const char cases[256][2] +CASES = ( + (256, 2), + """ +AP8BAAEBAgABAgMAAgMFAAEDAgEDAwUBAgUFBAUJCAABBAICAwQFAgQCBgIGCQsAAwgFBQcDCQEG +EA4DDAwFGAEFAwECBAUDAwYHAAUKCQAEAwYEBgsOAQYRDAQLBgUZAggFBwUMCAEGEgwFDgcFHAYV +CwQMDwUeCgUGIAYnAgwBBgQAAwUGAAIGBgMFCw4AAwkGBQcEDAEFDgsDCQQFGgMKBgYHBQwCBhMK +AQwNBhgHBwwJDQEHCQwUBiEHDQMMAgoGBwUNCwIFEAwHCAMFHQYWCgIMEQYbDgkGIgUnAg4FFA4F +CQUFIAsKBiMFKQIQDBcGJQcOAxAGLgQGAxUBCAEHAwIEAQYBAwcHAQYKDAACBwUGBgwLAQUPCQIO +BgUbAgkFCAYNDgIGFAwGCgMGGQUSCAIMEAUfCwkFIgYoAg0DCwcCBg4MAwcGDQAMDgcIBhcMCgoE +BhwMFQcKBikDDQUVCQMLCAUhDBYHCwYqAw4OCwUkBiwCEQYvAxIEBwEJAgsGCAYPCgAFEQwICwcG +GgUTDgQMEgYdCAQFIwUoAg8FFgsFDBMGHg4KBiQGKwQECQcFJQcPAxEFLAITAxYBCgUXDAsOCAYf +CQYHDAUqAw8LCwYmBi0EBQUtAxMCFQELCAUFJgUrAhIFLgMUAhYBDAUvAhQDFwENAhcBDgEPAP8= +""", +) + +# static const char tiling1[16][3] +TILING1 = ( + (16, 3), + """ +AAgDAAEJAQIKAwsCBAcICQUECgYFBwYLBwsGCgUGCQQFBAgHAwILAQoCAAkBAAMI +""", +) + +# static const char tiling2[24][6] +TILING2 = ( + (24, 6), + """ +AQgDCQgBAAsCCAsABAMABwMECQIKAAIJAAUEAQUAAwoBCwoDAQYFAgYBBwIDBgIHCQcIBQcJBggE +CwgGCgQJBgQKCwUKBwULCwoFBwsFCgkEBgoEBgQICwYICQgHBQkHBwMCBgcCAQUGAgEGAwEKCwMK +AAQFAQAFCQoCAAkCBAADBwQDAAILCAALAQMICQEI +""", +) + +# static const char tiling3_1[24][6] +TILING3_1 = ( + (24, 6), + """ +AAgDAQIKCQUEAAgDAwAICwcGAQkAAgMLAAEJCAQHCQABBQoGAQIKCQUECgECBgsHCAQHAwsCAgML +CgYFBQoGBAcIBAkFBwYLBQkECwYHBgoFCAcECwMCBQYKBwQIAgsDAgEKBwsGCgIBBAUJAQAJBgoF +CQEABwQIAAkBCwMCCAADBgcLBAUJAwgAAwgACgIB +""", +) + +# static const char tiling3_2[24][12] +TILING3_2 = ( + (24, 12), + """ +CgMCCggDCgEACAoAAwQIAwUEAwAJBQMJBggHBgAIBgsDAAYDCwADCwkACwIBCQsBBwkEBwEJBwgA +AQcABgEKBgABCQAGCQYFBAoFBAIKBAkBAgQBBwILBwECBwYKAQcKAgcLAgQHAgMIBAIIBQsGBQML +BQoCAwUCCAYHCAoGCAQFCggFCwUGCwkFCwcECQsEBgULBQkLBAcLBAsJBwYIBgoIBQQIBQgKBgsF +CwMFAgoFAgUDCwcCBwQCCAMCCAIECwIHAgEHCgYHCgcBBQoECgIEAQkEAQQCCgEGAQAGBgAJBQYJ +BAkHCQEHAAgHAAcBAwALAAkLAQILAQsJBwgGCAAGAwsGAwYACAQDBAUDCQADCQMFAgMKAwgKAAEK +AAoI +""", +) + +# static const char tiling4_1[8][6] +TILING4_1 = ( + (8, 6), + """ +AAgDBQoGAAEJCwcGAQIKCAQHCQUEAgMLBAUJCwMCCgIBBwQICQEABgcLAwgABgoF +""", +) + +# static const char tiling4_2[8][18] +TILING4_2 = ( + (8, 18), + """ +CAUABQgGAwYIBgMKAAoDCgAFCQYBBgkHAAcJBwALAQsACwEGCgcCBwoEAQQKBAEIAggBCAIHCwQD +BAsFAgULBQIJAwkCCQMEAwQLBQsECwUCCQIFAgkDBAMJAgcKBAoHCgQBCAEEAQgCBwIIAQYJBwkG +CQcACwAHAAsBBgELAAUIBggFCAYDCgMGAwoABQAK +""", +) + +# static const char tiling5[48][9] +TILING5 = ( + (48, 9), + """ +AggDAgoICgkIAQsCAQkLCQgLBAEJBAcBBwMBCAUECAMFAwEFAAoBAAgKCAsKCwQHCwIEAgAEBwAI +BwYABgIACQMACQUDBQcDAwYLAwAGAAQGAwkAAwsJCwoJBQIKBQQCBAACCQYFCQAGAAIGAAcIAAEH +AQUHCgABCgYABgQABgMLBgUDBQEDCgcGCgEHAQMHAQQJAQIEAgYECwECCwcBBwUBCAIDCAQCBAYC +AgUKAgMFAwcFBwoGBwgKCAkKBgkFBgsJCwgJBQgEBQoICgsIBAsHBAkLCQoLBAcLBAsJCQsKBQQI +BQgKCggLBgUJBgkLCwkIBwYKBwoICAoJAgoFAgUDAwUHCAMCCAIEBAIGCwIBCwEHBwEFAQkEAQQC +AgQGCgYHCgcBAQcDBgsDBgMFBQMBCgEACgAGBgAEAAgHAAcBAQcFCQUGCQYAAAYCBQoCBQIEBAIA +AwAJAwkLCwkKAwsGAwYAAAYECQADCQMFBQMHBwgABwAGBgACCwcECwQCAgQAAAEKAAoICAoLCAQF +CAUDAwUBBAkBBAEHBwEDAQILAQsJCQsIAgMIAggKCggJ +""", +) + +# static const char tiling6_1_1[48][9] +TILING6_1_1 = ( + (48, 9), + """ +BgUKAwEICQgBCwcGCQMBAwkIAQIKBwAEAAcDAwAIBQIGAgUBBQQJAgALCAsACgYFCAIAAggLCgYF +AAQDBwMEAwAIBgQKCQoECAMACgcFBwoLCAQHCgACAAoJBwYLAAIJCgkCAgMLBAEFAQQAAAEJBgMH +AwYCCQABCwQGBAsICwcGAQUABAAFAAEJBwULCgsFBAcIAQMKCwoDCQUECwEDAQsKCgECCAUHBQgJ +CAQHAgYBBQEGAQIKBAYICwgGAgMLBQcJCAkHCwIDCQYEBgkKCQUEAwcCBgIHBAUJAgcDBwIGAwIL +BAYJCgkGCwMCCQcFBwkICgIBCAYEBggLBwQIAQYCBgEFAgEKBwUICQgFBAUJAwELCgsBCAcECgMB +AwoLCQEACwUHBQsKBgcLAAUBBQAEAQAJBgQLCAsECQEABwMGAgYDCwMCBQEEAAQBCwYHCQIAAgkK +BwQIAgAKCQoAAAMIBQcKCwoHCAADCgQGBAoJBQYKAwQABAMHBQYKAAIICwgCCQQFCwACAAsICAAD +BgIFAQUCCgIBBAAHAwcABgcLAQMJCAkDCgUGCAEDAQgJ +""", +) + +# static const char tiling6_1_2[48][27] +TILING6_1_2 = ( + (48, 27), + """ +AQwDDAoDBgMKAwYIBQgGCAUMDAkIAQkMDAUKAQwDAQsMCwEGCQYBBgkHDAcJCQgMDAgDCwcMBAwA +BAEMAQQKBwoECgcCDAIHBwMMDAMAAQIMBgwCBgMMAwYIBQgGCAUADAAFBQEMDAECAwAMAAwCDAkC +BQIJAgULBAsFCwQMDAgLAAgMDAQJAAwCAAoMCgAFCAUABQgGDAYICAsMDAsCCgYMBAwADAUACgAF +AAoDBgMKAwYMDAcDBAcMDAYFBAwGDAgGAwYIBgMKAAoDCgAMDAkKBAkMDAAIBQwHBQgMCAUACgAF +AAoDDAMKCgsMDAsHCAMMAgwAAggMCAIHCgcCBwoEDAQKCgkMDAkACAQMAgwADAsABwALAAcJBgkH +CQYMDAoJAgoMDAYLBQwBBQIMAgULBAsFCwQDDAMEBAAMDAABAgMMBwwDBwAMAAcJBgkHCQYBDAEG +BgIMDAIDAAEMBgwEBgkMCQYBCwEGAQsADAALCwgMDAgECQAMBQwBDAYBCwEGAQsABwALAAcMDAQA +BQQMDAcGBQwHDAkHAAcJBwALAQsACwEMDAoLBQoMDAEJAwwBDAgBBAEIAQQKBwoECgcMDAsKAwsM +DAcIAwwBAwkMCQMECwQDBAsFDAULCwoMDAoBCQUMBwwFBwoMCgcCCAIHAggBDAEICAkMDAkFCgEM +BgwCDAcCCAIHAggBBAEIAQQMDAUBBgUMDAQHBgwEDAoEAQQKBAEIAggBCAIMDAsIBgsMDAIKBwwF +DAsFAgULBQIJAwkCCQMMDAgJBwgMDAMLBAwGBAsMCwQDCQMEAwkCDAIJCQoMDAoGCwIMBwwDDAQD +CQMEAwkCBQIJAgUMDAYCBwYMDAUEAwwHAwQMBAMJAgkDCQIFDAUCAgYMDAYHBAUMBgwEDAsEAwQL +BAMJAgkDCQIMDAoJBgoMDAILBQwHBQsMCwUCCQIFAgkDDAMJCQgMDAgHCwMMBAwGBAoMCgQBCAEE +AQgCDAIICAsMDAsGCgIMAgwGAgcMBwIIAQgCCAEEDAQBAQUMDAUGBwQMBQwHDAoHAgcKBwIIAQgC +CAEMDAkIBQkMDAEKAQwDDAkDBAMJAwQLBQsECwUMDAoLAQoMDAUJAQwDAQgMCAEECgQBBAoHDAcK +CgsMDAsDCAcMBwwFBwkMCQcACwAHAAsBDAELCwoMDAoFCQEMAQwFAQYMBgELAAsBCwAHDAcAAAQM +DAQFBgcMBAwGDAkGAQYJBgELAAsBCwAMDAgLBAgMDAAJAwwHDAAHCQcABwkGAQYJBgEMDAIGAwIM +DAEAAQwFDAIFCwUCBQsEAwQLBAMMDAAEAQAMDAMCAAwCAAsMCwAHCQcABwkGDAYJCQoMDAoCCwYM +AAwCDAgCBwIIAgcKBAoHCgQMDAkKAAkMDAQIBwwFDAgFAAUIBQAKAwoACgMMDAsKBwsMDAMIBgwE +BggMCAYDCgMGAwoADAAKCgkMDAkECAAMAAwEAAUMBQAKAwoACgMGDAYDAwcMDAcEBQYMAgwADAoA +BQAKAAUIBggFCAYMDAsIAgsMDAYKAgwAAgkMCQIFCwUCBQsEDAQLCwgMDAgACQQMAgwGDAMGCAYD +BggFAAUIBQAMDAEFAgEMDAADAAwEDAEECgQBBAoHAgcKBwIMDAMHAAMMDAIBAwwBDAsBBgELAQYJ +BwkGCQcMDAgJAwgMDAcLAwwBAwoMCgMGCAYDBggFDAUICAkMDAkBCgUM +""", +) + +# static const char tiling6_2[48][15] +TILING6_2 = ( + (48, 15), + """ +AQoDBgMKAwYIBQgGCAUJAQsDCwEGCQYBBgkHCAcJBAEAAQQKBwoECgcCAwIHBgMCAwYIBQgGCAUA +AQAFAAkCBQIJAgULBAsFCwQIAAoCCgAFCAUABQgGCwYIBAUACgAFAAoDBgMKAwYHBAgGAwYIBgMK +AAoDCgAJBQgHCAUACgAFAAoDCwMKAggACAIHCgcCBwoECQQKAgsABwALAAcJBgkHCQYKBQIBAgUL +BAsFCwQDAAMEBwADAAcJBgkHCQYBAgEGBgkECQYBCwEGAQsACAALBQYBCwEGAQsABwALAAcEBQkH +AAcJBwALAQsACwEKAwgBBAEIAQQKBwoECgcLAwkBCQMECwQDBAsFCgULBwoFCgcCCAIHAggBCQEI +BgcCCAIHAggBBAEIAQQFBgoEAQQKBAEIAggBCAILBwsFAgULBQIJAwkCCQMIBAsGCwQDCQMEAwkC +CgIJBwQDCQMEAwkCBQIJAgUGAwQHBAMJAgkDCQIFBgUCBgsEAwQLBAMJAgkDCQIKBQsHCwUCCQIF +AgkDCAMJBAoGCgQBCAEEAQgCCwIIAgcGBwIIAQgCCAEEBQQBBQoHAgcKBwIIAQgCCAEJAQkDBAMJ +AwQLBQsECwUKAQgDCAEECgQBBAoHCwcKBwkFCQcACwAHAAsBCgELAQYFBgELAAsBCwAHBAcABAkG +AQYJBgELAAsBCwAIAwAHCQcABwkGAQYJBgECAQIFCwUCBQsEAwQLBAMAAAsCCwAHCQcABwkGCgYJ +AAgCBwIIAgcKBAoHCgQJBwgFAAUIBQAKAwoACgMLBggECAYDCgMGAwoACQAKAAUEBQAKAwoACgMG +BwYDAgoABQAKAAUIBggFCAYLAgkACQIFCwUCBQsECAQLAgMGCAYDBggFAAUIBQABAAEECgQBBAoH +AgcKBwIDAwsBBgELAQYJBwkGCQcIAwoBCgMGCAYDBggFCQUI +""", +) + +# static const char tiling7_1[16][9] +TILING7_1 = ( + (16, 9), + """ +CQUECgECCAMACwcGCAMACgECAwAIBQQJBwYLCAQHCQABCwIDCgYFCwIDCQABAAEJBgUKBAcIAQIK +BwYLBQQJAgMLBAcIBgUKCwMCCAcECgUGCgIBCwYHCQQFCQEACgUGCAcEBQYKAwILAQAJBwQIAQAJ +AwILCAADCQQFCwYHBgcLAAMIAgEKBAUJAgEKAAMI +""", +) + +# static const char tiling7_2[16][3][15] +TILING7_2 = ( + (16, 3, 15), + """ +AQIKAwQIBAMFAAUDBQAJAwAICQEEAgQBBAIFCgUCCQUEAAoBCgAICggCAwIIAwAIAQYKBgEHAgcB +BwILAQIKCwMGAAYDBgAHCAcACwcGAggDCAIKCAoAAQAKCQUECwMGAAYDBgAHCAcACwcGAwQIBAMF +AAUDBQAJAwAIBAkHCwcJBQsJCwUGAAEJAgcLBwIEAwQCBAMIAgMLCAAHAQcABwEECQQBCAQHAwkA +CQMLCQsBAgELAgMLAAUJBQAGAQYABgEKAAEJCgIFAwUCBQMGCwYDBgUKAQsCCwEJCwkDAAMJBgUK +CAAHAQcABwEECQQBCAQHAAUJBQAGAQYABgEKAAEJBQoECAQKBggKCAYHCwcGCQEEAgQBBAIFCgUC +CQUEAQYKBgEHAgcBBwILAQIKBgsFCQULBwkLCQcECAQHCgIFAwUCBQMGCwYDBgUKAgcLBwIEAwQC +BAMIAgMLBwgGCgYIBAoICgQFBwQIBQIKAgUDBgMFAwYLCgUGCwcCBAIHAgQDCAMECwMCBggHCAYK +CAoEBQQKBgcLBAEJAQQCBQIEAgUKBAUJCgYBBwEGAQcCCwIHCgIBBQsGCwUJCwkHBAcJCgUGBwAI +AAcBBAEHAQQJBwQICQUABgAFAAYBCgEGCQEABAoFCgQICggGBwYICwMCCQUABgAFAAYBCgEGCQEA +BQIKAgUDBgMFAwYLCgUGAgsBCQELAwkLCQMACQEACwcCBAIHAgQDCAMECwMCBwAIAAcBBAEHAQQJ +BwQIAAkDCwMJAQsJCwECBAUJBgMLAwYABwAGAAcIBgcLCAQDBQMEAwUACQAFCAADBwkECQcLCQsF +BgULCAADCgYBBwEGAQcCCwIHCgIBBgMLAwYABwAGAAcIBgcLAwgCCgIIAAoICgABCgIBCAQDBQME +AwUACQAFCAADBAEJAQQCBQIEAgUKBAUJAQoACAAKAggKCAID +""", +) + +# static const char tiling7_3[16][3][27] +TILING7_3 = ( + (16, 3, 27), + """ +DAIKDAoFDAUEDAQIDAgDDAMADAAJDAkBDAECDAUEDAQIDAgDDAMCDAIKDAoBDAEADAAJDAkFBQQM +CgUMAgoMAwIMCAMMAAgMAQAMCQEMBAkMDAAIDAgHDAcGDAYKDAoBDAECDAILDAsDDAMADAcGDAYK +DAoBDAEADAAIDAgDDAMCDAILDAsHBwYMCAcMAAgMAQAMCgEMAgoMAwIMCwMMBgsMCQUMAAkMAwAM +CwMMBgsMBwYMCAcMBAgMBQQMAwAMCwMMBgsMBQYMCQUMBAkMBwQMCAcMAAgMDAMADAAJDAkFDAUG +DAYLDAsHDAcEDAQIDAgDDAEJDAkEDAQHDAcLDAsCDAIDDAMIDAgADAABDAQHDAcLDAsCDAIBDAEJ +DAkADAADDAMIDAgEBAcMCQQMAQkMAgEMCwIMAwsMAAMMCAAMBwgMDAMLDAsGDAYFDAUJDAkADAAB +DAEKDAoCDAIDDAYFDAUJDAkADAADDAMLDAsCDAIBDAEKDAoGBgUMCwYMAwsMAAMMCQAMAQkMAgEM +CgIMBQoMCgYMAQoMAAEMCAAMBwgMBAcMCQQMBQkMBgUMAAEMCAAMBwgMBgcMCgYMBQoMBAUMCQQM +AQkMDAABDAEKDAoGDAYHDAcIDAgEDAQFDAUJDAkACwcMAgsMAQIMCQEMBAkMBQQMCgUMBgoMBwYM +AQIMCQEMBAkMBwQMCwcMBgsMBQYMCgUMAgoMDAECDAILDAsHDAcEDAQJDAkFDAUGDAYKDAoBCAQM +AwgMAgMMCgIMBQoMBgUMCwYMBwsMBAcMAgMMCgIMBQoMBAUMCAQMBwgMBgcMCwYMAwsMDAIDDAMI +DAgEDAQFDAUKDAoGDAYHDAcLDAsCDAQIDAgDDAMCDAIKDAoFDAUGDAYLDAsHDAcEDAMCDAIKDAoF +DAUEDAQIDAgHDAcGDAYLDAsDAwIMCAMMBAgMBQQMCgUMBgoMBwYMCwcMAgsMDAcLDAsCDAIBDAEJ +DAkEDAQFDAUKDAoGDAYHDAIBDAEJDAkEDAQHDAcLDAsGDAYFDAUKDAoCAgEMCwIMBwsMBAcMCQQM +BQkMBgUMCgYMAQoMDAYKDAoBDAEADAAIDAgHDAcEDAQJDAkFDAUGDAEADAAIDAgHDAcGDAYKDAoF +DAUEDAQJDAkBAQAMCgEMBgoMBwYMCAcMBAgMBQQMCQUMAAkMCwMMBgsMBQYMCQUMAAkMAQAMCgEM +AgoMAwIMBQYMCQUMAAkMAwAMCwMMAgsMAQIMCgEMBgoMDAUGDAYLDAsDDAMADAAJDAkBDAECDAIK +DAoFCQEMBAkMBwQMCwcMAgsMAwIMCAMMAAgMAQAMBwQMCwcMAgsMAQIMCQEMAAkMAwAMCAMMBAgM +DAcEDAQJDAkBDAECDAILDAsDDAMADAAIDAgHDAUJDAkADAADDAMLDAsGDAYHDAcIDAgEDAQFDAAD +DAMLDAsGDAYFDAUJDAkEDAQHDAcIDAgAAAMMCQAMBQkMBgUMCwYMBwsMBAcMCAQMAwgMCAAMBwgM +BgcMCgYMAQoMAgEMCwIMAwsMAAMMBgcMCgYMAQoMAAEMCAAMAwgMAgMMCwIMBwsMDAYHDAcIDAgA +DAABDAEKDAoCDAIDDAMLDAsGCgIMBQoMBAUMCAQMAwgMAAMMCQAMAQkMAgEMBAUMCAQMAwgMAgMM +CgIMAQoMAAEMCQAMBQkMDAQFDAUKDAoCDAIDDAMIDAgADAABDAEJDAkE +""", +) + +# static const char tiling7_4_1[16][15] +TILING7_4_1 = ( + (16, 15), + """ +AwQIBAMKAgoDBAoFCQEAAQYKBgEIAAgBBggHCwMCCwMGCQYDBgkFAAkDBwQIAgcLBwIJAQkCBwkE +CAADAAUJBQALAwsABQsGCgIBCAAHCgcABwoGAQoABAUJCQEECwQBBAsHAgsBBQYKCgIFCAUCBQgE +AwgCBgcLBQIKAgUIBAgFAggDCwcGBAEJAQQLBwsEAQsCCgYFBwAIAAcKBgoHAAoBCQUECQUACwAF +AAsDBgsFAQIKCwcCCQIHAgkBBAkHAwAIBgMLAwYJBQkGAwkACAQHCgYBCAEGAQgABwgGAgMLCAQD +CgMEAwoCBQoEAAEJ +""", +) + +# static const char tiling7_4_2[16][27] +TILING7_4_2 = ( + (16, 27), + """ +CQQIBAkFCgUJAQoJCgECAAIBAgADCAMACQgACwYKBgsHCAcLAwgLCAMAAgADAAIBCgECCwoCCwMI +AAgDCAAJCAkEBQQJBAUHBgcFBwYLBwsICAcLBwgECQQIAAkICQABAwEAAQMCCwIDCAsDCgUJBQoG +CwYKAgsKCwIDAQMCAwEACQABCgkBCAAJAQkACQEKCQoFBgUKBQYEBwQGBAcIBAgJCQEKAgoBCgIL +CgsGBwYLBgcFBAUHBQQJBQkKCgILAwsCCwMICwgHBAcIBwQGBQYEBgUKBgoLCwIKAgsDCAMLBwgL +CAcEBgQHBAYFCgUGCwoGCgEJAQoCCwIKBgsKCwYHBQcGBwUECQQFCgkFCQAIAAkBCgEJBQoJCgUG +BAYFBgQHCAcECQgECQUKBgoFCgYLCgsCAwILAgMBAAEDAQAJAQkKCwcIBAgHCAQJCAkAAQAJAAED +AgMBAwILAwsICAMLAwgACQAIBAkICQQFBwUEBQcGCwYHCAsHCgYLBwsGCwcICwgDAAMIAwACAQIA +AgEKAgoLCAQJBQkECQUKCQoBAgEKAQIAAwACAAMIAAgJ +""", +) + +# static const char tiling8[6][6] +TILING8 = ( + (6, 6), + """ +CQgKCggLAQUDAwUHAAQCBAYCAAIEBAIGAQMFAwcFCQoICgsI +""", +) + +# static const char tiling9[8][12] +TILING9 = ( + (8, 12), + """ +AgoFAwIFAwUEAwQIBAcLCQQLCQsCCQIBCgcGAQcKAQgHAQAIAwYLAAYDAAUGAAkFAwsGAAMGAAYF +AAUJCgYHAQoHAQcIAQgABAsHCQsECQILCQECAgUKAwUCAwQFAwgE +""", +) + +# static const char tiling10_1_1[6][12] +TILING10_1_1 = ( + (6, 12), + """ +BQoHCwcKCAEJAQgDAQIFBgUCBAMAAwQHCwAIAAsCBAkGCgYJCQAKAgoABggECAYLBwIDAgcGAAEE +BQQBBwkFCQcICgELAwsB +""", +) + +# static const char tiling10_1_1_[6][12] +TILING10_1_1_ = ( + (6, 12), + """ +BQkHCAcJCwEKAQsDAwIHBgcCBAEAAQQFCgAJAAoCBAgGCwYICAALAgsABgkECQYKBQIBAgUGAAME +BwQDBwoFCgcLCQEIAwgB +""", +) + +# static const char tiling10_1_2[6][24] +TILING10_1_2 = ( + (6, 24), + """ +AwsHAwcICQgHBQkHCQUKCQoBAwEKCwMKBwYFBwUEAAQFAQAFAAECAAIDBwMCBgcCCwIKBgsKCwYE +CwQIAAgECQAEAAkKAAoCCwIKCwoGBAYKCQQKBAkABAAICwgAAgsABwYFBAcFBwQABwADAgMAAQIA +AgEFAgUGBwgDCwcDBwsKBwoFCQUKAQkKCQEDCQMI +""", +) + +# static const char tiling10_2[6][24] +TILING10_2 = ( + (6, 24), + """ +DAUJDAkIDAgDDAMBDAEKDAoLDAsHDAcFDAEADAAEDAQHDAcDDAMCDAIGDAYFDAUBBAgMBgQMCgYM +CQoMAAkMAgAMCwIMCAsMDAkEDAQGDAYLDAsIDAgADAACDAIKDAoJAAMMBAAMBQQMAQUMAgEMBgIM +BwYMAwcMCgUMCwoMAwsMAQMMCQEMCAkMBwgMBQcM +""", +) + +# static const char tiling10_2_[6][24] +TILING10_2_ = ( + (6, 24), + """ +CAcMCQgMAQkMAwEMCwMMCgsMBQoMBwUMBAUMAAQMAwAMBwMMBgcMAgYMAQIMBQEMDAsGDAYEDAQJ +DAkKDAoCDAIADAAIDAgLBgoMBAYMCAQMCwgMAgsMAAIMCQAMCgkMDAcEDAQADAABDAEFDAUGDAYC +DAIDDAMHDAcLDAsKDAoBDAEDDAMIDAgJDAkFDAUH +""", +) + +# static const char tiling11[12][12] +TILING11 = ( + (12, 12), + """ +AgoJAgkHAgcDBwkEAQYCAQgGAQkICAcGCAMBCAEGCAYEBgEKAAgLAAsFAAUBBQsGCQUHCQcCCQIA +AgcLBQAEBQsABQoLCwMABQQABQALBQsKCwADCQcFCQIHCQACAgsHAAsIAAULAAEFBQYLCAEDCAYB +CAQGBgoBAQIGAQYIAQgJCAYHAgkKAgcJAgMHBwQJ +""", +) + +# static const char tiling12_1_1[24][12] +TILING12_1_1 = ( + (24, 12), + """ +BwYLCgMCAwoICQgKBgUKCQIBAgkLCAsJCgYFBwkECQcBAwEHBwYLBAgFAwUIBQMBBQQJCAEAAQgK +CwoIAQIKAAkDBQMJAwUHCgECAAsDCwAGBAYACAMAAgkBCQIEBgQCAwAIAgsBBwELAQcFBgUKBwsE +AgQLBAIACQUEBggHCAYAAgAGCAMABwQLCQsECwkKBAcICwADAAsJCgkLBAcIBQkGAAYJBgACCwcG +BAoFCgQCAAIECwIDAQgACAEHBQcBAAEJAwgCBAIIAgQGAgMLAQoABgAKAAYECQABAwoCCgMFBwUD +CQABBAUICggFCAoLCAQHBQsGCwUDAQMFBQQJBgoHAQcKBwEDCgECBQYJCwkGCQsICwIDBgcKCAoH +CggJ +""", +) + +# static const char tiling12_1_1_[24][12] +TILING12_1_1_ = ( + (24, 12), + """ +AwILCgcGBwoICQgKAgEKCQYFBgkLCAsJCQQFBwoGCgcBAwEHBwQIBgsFAwULBQMBAQAJCAUEBQgK +CwoIAQAJAgoDBQMKAwUHCwMCAAoBCgAGBAYACQEAAggDCAIEBgQCAwILAAgBBwEIAQcFBgcLBQoE +AgQKBAIACAcEBgkFCQYAAgAGCAcEAwALCQsACwkKAAMICwQHBAsJCgkLBAUJBwgGAAYIBgACCgUG +BAsHCwQCAAIECAADAQsCCwEHBQcBAAMIAQkCBAIJAgQGAgEKAwsABgALAAYECgIBAwkACQMFBwUD +CQQFAAEICggBCAoLCwYHBQgECAUDAQMFBQYKBAkHAQcJBwEDCgUGAQIJCwkCCQsICwYHAgMKCAoD +CggJ +""", +) + +# static const char tiling12_1_2[24][24] +TILING12_1_2 = ( + (24, 24), + """ +BwMLAwcICQgHBgkHCQYKAgoGCwIGAgsDBgIKAgYLCAsGBQgGCAUJAQkFCgEFAQoCCgkFCQoBAwEK +BgMKAwYHBAcGBQQGBAUJBwgLAwsICwMBCwEGBQYBBgUEBgQHCAcEBQEJAQUKCwoFBAsFCwQIAAgE +CQAEAAkBAQkKBQoJCgUHCgcCAwIHAgMAAgABCQEACgsCCwoGBAYKAQQKBAEAAwABAgMBAwILCAkA +CQgEBgQIAwYIBgMCAQIDAAEDAQAJAwsIBwgLCAcFCAUAAQAFAAECAAIDCwMCBgsKAgoLCgIACgAF +BAUABQQHBQcGCwYHCQgECAkAAgAJBQIJAgUGBwYFBAcFBwQICAQACQAEAAkKAAoDCwMKAwsHAwcI +BAgHBAAIAAQJCgkEBwoECgcLAwsHCAMHAwgABAkIAAgJCAACCAIHBgcCBwYFBwUECQQFCwoGCgsC +AAILBwALAAcEBQQHBgUHBQYKCwgDCAsHBQcLAgULBQIBAAECAwACAAMIAAgJBAkICQQGCQYBAgEG +AQIDAQMACAADAgoLBgsKCwYECwQDAAMEAwABAwECCgIBCQoBCgkFBwUJAAcJBwADAgMAAQIAAgEK +CQUBCgEFAQoLAQsACAALAAgEAAQJBQkECAsHCwgDAQMIBAEIAQQFBgUEBwYEBgcLBQoJAQkKCQED +CQMEBwQDBAcGBAYFCgUGCgYCCwIGAgsIAggBCQEIAQkFAQUKBgoFCwcDCAMHAwgJAwkCCgIJAgoG +AgYLBwsG +""", +) + +# static const char tiling12_2[24][24] +TILING12_2 = ( + (24, 24), + """ +CQgMCgkMAgoMAwIMCwMMBgsMBwYMCAcMCAsMCQgMAQkMAgEMCgIMBQoMBgUMCwYMAwEMBwMMBAcM +CQQMBQkMBgUMCgYMAQoMDAMBDAEFDAUGDAYLDAsHDAcEDAQIDAgDCwoMCAsMAAgMAQAMCQEMBAkM +BQQMCgUMDAUHDAcDDAMCDAIKDAoBDAEADAAJDAkFBAYMAAQMAQAMCgEMAgoMAwIMCwMMBgsMBgQM +AgYMAwIMCAMMAAgMAQAMCQEMBAkMDAcFDAUBDAEADAAIDAgDDAMCDAILDAsHDAIADAAEDAQFDAUK +DAoGDAYHDAcLDAsCAgAMBgIMBwYMCAcMBAgMBQQMCQUMAAkMDAkKDAoLDAsHDAcEDAQIDAgDDAMA +DAAJCgkMCwoMBwsMBAcMCAQMAwgMAAMMCQAMDAACDAIGDAYHDAcIDAgEDAQFDAUJDAkAAAIMBAAM +BQQMCgUMBgoMBwYMCwcMAgsMBQcMAQUMAAEMCAAMAwgMAgMMCwIMBwsMDAQGDAYCDAIDDAMIDAgA +DAABDAEJDAkEDAYEDAQADAABDAEKDAoCDAIDDAMLDAsGBwUMAwcMAgMMCgIMAQoMAAEMCQAMBQkM +DAoLDAsIDAgADAABDAEJDAkEDAQFDAUKAQMMBQEMBgUMCwYMBwsMBAcMCAQMAwgMDAEDDAMHDAcE +DAQJDAkFDAUGDAYKDAoBDAsIDAgJDAkBDAECDAIKDAoFDAUGDAYLDAgJDAkKDAoCDAIDDAMLDAsG +DAYHDAcI +""", +) + +# static const char tiling12_2_[24][24] +TILING12_2_ = ( + (24, 24), + """ +DAILDAsHDAcGDAYKDAoJDAkIDAgDDAMCDAEKDAoGDAYFDAUJDAkIDAgLDAsCDAIBDAQFDAUKDAoG +DAYHDAcDDAMBDAEJDAkEBwYMCAcMBAgMBQQMAQUMAwEMCwMMBgsMDAAJDAkFDAUEDAQIDAgLDAsK +DAoBDAEAAQIMCQEMAAkMAwAMBwMMBQcMCgUMAgoMDAECDAILDAsDDAMADAAEDAQGDAYKDAoBDAMA +DAAJDAkBDAECDAIGDAYEDAQIDAgDAwAMCwMMAgsMAQIMBQEMBwUMCAcMAAgMBgUMCwYMBwsMBAcM +AAQMAgAMCgIMBQoMDAcEDAQJDAkFDAUGDAYCDAIADAAIDAgHCAcMAAgMAwAMCwMMCgsMCQoMBAkM +BwQMDAcIDAgADAADDAMLDAsKDAoJDAkEDAQHBAcMCQQMBQkMBgUMAgYMAAIMCAAMBwgMDAUGDAYL +DAsHDAcEDAQADAACDAIKDAoFDAADDAMLDAsCDAIBDAEFDAUHDAcIDAgAAAMMCQAMAQkMAgEMBgIM +BAYMCAQMAwgMAgEMCwIMAwsMAAMMBAAMBgQMCgYMAQoMDAIBDAEJDAkADAADDAMHDAcFDAUKDAoC +CQAMBQkMBAUMCAQMCwgMCgsMAQoMAAEMDAYHDAcIDAgEDAQFDAUBDAEDDAMLDAsGBQQMCgUMBgoM +BwYMAwcMAQMMCQEMBAkMCgEMBgoMBQYMCQUMCAkMCwgMAgsMAQIMCwIMBwsMBgcMCgYMCQoMCAkM +AwgMAgMM +""", +) + +# static const char tiling13_1[2][12] +TILING13_1 = ( + (2, 12), + """ +CwcGAQIKCAMACQUECAQHAgMLCQABCgYF +""", +) + +# static const char tiling13_1_[2][12] +TILING13_1_ = ( + (2, 12), + """ +BwQICwMCAQAJBQYKBgcLCgIBAAMIBAUJ +""", +) + +# static const char tiling13_2[2][6][18] +TILING13_2 = ( + (2, 6, 18), + """ +AQIKCwcGAwQIBAMFAAUDBQAJCAMACwcGCQEEAgQBBAIFCgUCCQUECAMAAQYKBgEHAgcBBwILCQUE +AQIKCwMGAAYDBgAHCAcACQUECwcGAAoBCgAICggCAwIIAQIKAwAIBAkHCwcJBQsJCwUGAgMLCAQH +AAUJBQAGAQYABgEKCQABCAQHCgIFAwUCBQMGCwYDBgUKCQABAgcLBwIEAwQCBAMIBgUKAgMLCAAH +AQcABwEECQQBBgUKCAQHAQsCCwEJCwkDAAMJAgMLAAEJBQoECAQKBggKCAYH +""", +) + +# static const char tiling13_2_[2][6][18] +TILING13_2_ = ( + (2, 6, 18), + """ +CgUGCwMCBwAIAAcBBAEHAQQJCwMCBwQICQUABgAFAAYBCgEGAQAJBwQIBQIKAgUDBgMFAwYLCgUG +AQAJCwcCBAIHAgQDCAMECgUGBwQIAgsBCQELAwkLCQMACwMCCQEABAoFCgQICggGBwYIBgcLCAAD +BAEJAQQCBQIEAgUKCAADBAUJCgYBBwEGAQcCCwIHAgEKBAUJBgMLAwYABwAGAAcIBgcLAgEKCAQD +BQMEAwUACQAFBgcLBAUJAwgCCgIIAAoICgABCAADCgIBBQsGCwUJCwkHBAcJ +""", +) + +# static const char tiling13_3[2][12][30] +TILING13_3 = ( + (2, 12, 30), + """ +CwcGDAIKDAoFDAUEDAQIDAgDDAMADAAJDAkBDAECAQIKCQUMAAkMAwAMCwMMBgsMBwYMCAcMBAgM +BQQMCwcGDAUEDAQIDAgDDAMCDAIKDAoBDAEADAAJDAkFAQIKDAMADAAJDAkFDAUGDAYLDAsHDAcE +DAQIDAgDCAMACwcMAgsMAQIMCQEMBAkMBQQMCgUMBgoMBwYMCwcGBQQMCgUMAgoMAwIMCAMMAAgM +AQAMCQEMBAkMCAMAAQIMCQEMBAkMBwQMCwcMBgsMBQYMCgUMAgoMCQUEDAAIDAgHDAcGDAYKDAoB +DAECDAILDAsDDAMACQUEDAcGDAYKDAoBDAEADAAIDAgDDAMCDAILDAsHCAMADAECDAILDAsHDAcE +DAQJDAkFDAUGDAYKDAoBCQUEBwYMCAcMAAgMAQAMCgEMAgoMAwIMCwMMBgsMAQIKAwAMCwMMBgsM +BQYMCQUMBAkMBwQMCAcMAAgMCAQHDAMLDAsGDAYFDAUJDAkADAABDAEKDAoCDAIDAgMLCgYMAQoM +AAEMCAAMBwgMBAcMCQQMBQkMBgUMCAQHDAYFDAUJDAkADAADDAMLDAsCDAIBDAEKDAoGAgMLDAAB +DAEKDAoGDAYHDAcIDAgEDAQFDAUJDAkAAAEJCAQMAwgMAgMMCgIMBQoMBgUMCwYMBwsMBAcMCAQH +BgUMCwYMAwsMAAMMCQAMAQkMAgEMCgIMBQoMCQABAgMMCgIMBQoMBAUMCAQMBwgMBgcMCwYMAwsM +BgUKDAEJDAkEDAQHDAcLDAsCDAIDDAMIDAgADAABBgUKDAQHDAcLDAsCDAIBDAEJDAkADAADDAMI +DAgECQABDAIDDAMIDAgEDAQFDAUKDAoGDAYHDAcLDAsCBgUKBAcMCQQMAQkMAgEMCwIMAwsMAAMM +CAAMBwgMAgMLAAEMCAAMBwgMBgcMCgYMBQoMBAUMCQQMAQkM +""", +) + +# static const char tiling13_3_[2][12][30] +TILING13_3_ = ( + (2, 12, 30), + """ +AwILCAcMAAgMAQAMCgEMBgoMBQYMCQUMBAkMBwQMBQYKDAILDAsHDAcEDAQJDAkBDAEADAAIDAgD +DAMCCgUGDAcEDAQJDAkBDAECDAILDAsDDAMADAAIDAgHCwMCDAEADAAIDAgHDAcGDAYKDAoFDAUE +DAQJDAkBBwQICwMMBgsMBQYMCQUMAAkMAQAMCgEMAgoMAwIMBwQIBQYMCQUMAAkMAwAMCwMMAgsM +AQIMCgEMBgoMCwMCAQAMCgEMBgoMBwYMCAcMBAgMBQQMCQUMAAkMAQAJDAQIDAgDDAMCDAIKDAoF +DAUGDAYLDAsHDAcEBwQIDAUGDAYLDAsDDAMADAAJDAkBDAECDAIKDAoFAQAJDAMCDAIKDAoFDAUE +DAQIDAgHDAcGDAYLDAsDCgUGBwQMCwcMAgsMAQIMCQEMAAkMAwAMCAMMBAgMCQEAAwIMCAMMBAgM +BQQMCgUMBgoMBwYMCwcMAgsMAAMICQQMAQkMAgEMCwIMBwsMBgcMCgYMBQoMBAUMCwYHDAMIDAgE +DAQFDAUKDAoCDAIBDAEJDAkADAADBgcLDAQFDAUKDAoCDAIDDAMIDAgADAABDAEJDAkECAADDAIB +DAEJDAkEDAQHDAcLDAsGDAYFDAUKDAoCBAUJCAAMBwgMBgcMCgYMAQoMAgEMCwIMAwsMAAMMBAUJ +BgcMCgYMAQoMAAEMCAAMAwgMAgMMCwIMBwsMCAADAgEMCwIMBwsMBAcMCQQMBQkMBgUMCgYMAQoM +AgEKDAUJDAkADAADDAMLDAsGDAYHDAcIDAgEDAQFBAUJDAYHDAcIDAgADAABDAEKDAoCDAIDDAML +DAsGAgEKDAADDAMLDAsGDAYFDAUJDAkEDAQHDAcIDAgABgcLBAUMCAQMAwgMAgMMCgIMAQoMAAEM +CQAMBQkMCgIBAAMMCQAMBQkMBgUMCwYMBwsMBAcMCAQMAwgM +""", +) + +# static const char tiling13_4[2][4][36] +TILING13_4 = ( + (2, 4, 36), + """ +DAIKDAoFDAUGDAYLDAsHDAcEDAQIDAgDDAMADAAJDAkBDAECCwMMBgsMBwYMCAcMBAgMBQQMCQUM +AAkMAQAMCgEMAgoMAwIMCQEMBAkMBQQMCgUMBgoMBwYMCwcMAgsMAwIMCAMMAAgMAQAMDAAIDAgH +DAcEDAQJDAkFDAUGDAYKDAoBDAECDAILDAsDDAMADAMLDAsGDAYHDAcIDAgEDAQFDAUJDAkADAAB +DAEKDAoCDAIDCAAMBwgMBAcMCQQMBQkMBgUMCgYMAQoMAgEMCwIMAwsMAAMMCgIMBQoMBgUMCwYM +BwsMBAcMCAQMAwgMAAMMCQAMAQkMAgEMDAEJDAkEDAQFDAUKDAoGDAYHDAcLDAsCDAIDDAMIDAgA +DAAB +""", +) + +# static const char tiling13_5_1[2][4][18] +TILING13_5_1 = ( + (2, 4, 18), + """ +BwYLAQAJCgMCAwoFAwUIBAgFAQIKBwQIAwALBgsACQYABgkFAwAIBQYKAQIJBAkCCwQCBAsHBQQJ +AwILCAEAAQgHAQcKBgoHBAcIAgEKCwADAAsGAAYJBQkGAgMLBAUJAAEIBwgBCgcBBwoGAAEJBgcL +AgMKBQoDCAUDBQgEBgUKAAMICQIBAgkEAgQLBwsE +""", +) + +# static const char tiling13_5_2[2][4][30] +TILING13_5_2 = ( + (2, 4, 30), + """ +AQAJBwQIBwgDBwMLAgsDCwIKCwoGBQYKBgUHBAcFBwQICwMCBgsCCgYCBgoFCQUKAQkKCQEAAgAB +AAIDBQYKCQEABAkACAQABAgHCwcIAwsICwMCAAIDAgABAwILBQYKBQoBBQEJAAkBCQAICQgEBAgH +BAcFBgUHAgEKBAUJBAkABAAIAwgACAMLCAsHBgcLBwYEBQQGBAUJCAADBwgDCwcDBwsGCgYLAgoL +CgIBAwECAQMABgcLCgIBBQoBCQUBBQkECAQJAAgJCAADAQMAAwECAAMIBgcLBgsCBgIKAQoCCgEJ +CgkFBQkEBQQGBwYE +""", +) + +# static const char tiling14[12][12] +TILING14 = ( + (12, 12), + """ +BQkIBQgCBQIGAwIIAgEFAgUIAggLBAgFCQQGCQYDCQMBCwMGAQsKAQQLAQAEBwsECAIACAUCCAcF +CgIFAAcDAAoHAAkKBgcKAAMHAAcKAAoJBgoHCAACCAIFCAUHCgUCAQoLAQsEAQQABwQLCQYECQMG +CQEDCwYDAgUBAggFAgsIBAUIBQgJBQIIBQYCAwgC +""", +) + +# static const char test3[24] +TEST3 = ( + (24,), + """ +BQEEBQECAgMEAwYG+vr9/P3+/v/7/P/7 +""", +) + +# static const char test4[8] +TEST4 = ( + (8,), + """ +BwcHB/n5+fk= +""", +) + +# static const char test6[48][3] +TEST6 = ( + (48, 3), + """ +AgcKBAcLBQcBBQcDAQcJAwcKBgcFAQcIBAcIAQcIAwcLBQcCBQcAAQcJBgcGAgcJBAcIAgcJAgcK +BgcHAwcKBAcLAwcLBgcE+vkE/fkL/PkL/fkK+vkH/vkK/vkJ/PkI/vkJ+vkG//kJ+/kA+/kC/fkL +//kI/PkI//kI+vkF/fkK//kJ+/kD+/kB/PkL/vkK +""", +) + +# static const char test7[16][5] +TEST7 = ( + (16, 5), + """ +AQIFBwEDBAUHAwQBBgcEBAEFBwACAwUHAgECBgcFAgMGBwYDBAYHB/38+vkH/v36+Qb//vr5Bf79 ++/kC/P/7+QD8//r5BP38+/kD//77+QE= +""", +) + +# static const char test10[6][3] +TEST10 = ( + (6, 3), + """ +AgQHBQYHAQMHAQMHBQYHAgQH +""", +) + +# static const char test12[24][4] +TEST12 = ( + (24, 4), + """ +BAMHCwMCBwoCBgcFBgQHBwIBBwkFAgcBBQMHAgUBBwAFBAcDBgMHBgEGBwQBBAcIBAEHCAYBBwQD +BgcGBAUHAwEFBwADBQcCAgUHAQECBwkEBgcHBgIHBQIDBwoDBAcL +""", +) + +# static const char test13[2][7] +TEST13 = ( + (2, 7), + """ +AQIDBAUGBwIDBAEFBgc= +""", +) + +# static const char subconfig13[64] +SUBCONFIG13 = ( + (64,), + """ +AAECBwP/C/8ECP//Dv///wUJDBcP/xUmERT/JBohHiwGCg0TEP8ZJRIY/yMWIB0r////Iv//HCr/ +H/8pGygnLQ== +""", +) diff --git a/envs/kitoverlay/skimage/measure/_moments.py b/envs/kitoverlay/skimage/measure/_moments.py new file mode 100644 index 0000000000000000000000000000000000000000..612ab94080eed75b94f767de29d85f3964c868a7 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_moments.py @@ -0,0 +1,513 @@ +import itertools + +import numpy as np + +from .._shared.utils import _supported_float_type, check_nD +from . import _moments_cy +from ._moments_analytical import moments_raw_to_central + + +def moments_coords(coords, order=3): + """Calculate all raw image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale, nor rotation + invariant. + + Parameters + ---------- + coords : (N, D) double or uint8 array + Array of N points that describe an image of D dimensionality in + Cartesian space. + order : int, optional + Maximum order of moments. Default is 3. + + Returns + ------- + M : (``order + 1``, ``order + 1``, ...) array + Raw image moments. (D dimensions) + + References + ---------- + .. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham + University, version 0.2, Durham, 2001. + + Examples + -------- + >>> coords = np.array([[row, col] + ... for row in range(13, 17) + ... for col in range(14, 18)], dtype=np.float64) + >>> M = moments_coords(coords) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> centroid + (14.5, 15.5) + """ + return moments_coords_central(coords, 0, order=order) + + +def moments_coords_central(coords, center=None, order=3): + """Calculate all central image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale nor rotation + invariant. + + Parameters + ---------- + coords : (N, D) double or uint8 array + Array of N points that describe an image of D dimensionality in + Cartesian space. A tuple of coordinates as returned by + ``np.nonzero`` is also accepted as input. + center : tuple of float, optional + Coordinates of the image centroid. This will be computed if it + is not provided. + order : int, optional + Maximum order of moments. Default is 3. + + Returns + ------- + Mc : (``order + 1``, ``order + 1``, ...) array + Central image moments. (D dimensions) + + References + ---------- + .. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham + University, version 0.2, Durham, 2001. + + Examples + -------- + >>> coords = np.array([[row, col] + ... for row in range(13, 17) + ... for col in range(14, 18)]) + >>> moments_coords_central(coords) + array([[16., 0., 20., 0.], + [ 0., 0., 0., 0.], + [20., 0., 25., 0.], + [ 0., 0., 0., 0.]]) + + As seen above, for symmetric objects, odd-order moments (columns 1 and 3, + rows 1 and 3) are zero when centered on the centroid, or center of mass, + of the object (the default). If we break the symmetry by adding a new + point, this no longer holds: + + >>> coords2 = np.concatenate((coords, [[17, 17]]), axis=0) + >>> np.round(moments_coords_central(coords2), + ... decimals=2) # doctest: +NORMALIZE_WHITESPACE + array([[17. , 0. , 22.12, -2.49], + [ 0. , 3.53, 1.73, 7.4 ], + [25.88, 6.02, 36.63, 8.83], + [ 4.15, 19.17, 14.8 , 39.6 ]]) + + Image moments and central image moments are equivalent (by definition) + when the center is (0, 0): + + >>> np.allclose(moments_coords(coords), + ... moments_coords_central(coords, (0, 0))) + True + """ + if isinstance(coords, tuple): + # This format corresponds to coordinate tuples as returned by + # e.g. np.nonzero: (row_coords, column_coords). + # We represent them as an npoints x ndim array. + coords = np.stack(coords, axis=-1) + check_nD(coords, 2) + ndim = coords.shape[1] + + float_type = _supported_float_type(coords.dtype) + if center is None: + center = np.mean(coords, axis=0, dtype=float) + + # center the coordinates + coords = coords.astype(float_type, copy=False) - center + + # generate all possible exponents for each axis in the given set of points + # produces a matrix of shape (N, D, order + 1) + coords = np.stack([coords**c for c in range(order + 1)], axis=-1) + + # add extra dimensions for proper broadcasting + coords = coords.reshape(coords.shape + (1,) * (ndim - 1)) + + calc = 1 + + for axis in range(ndim): + # isolate each point's axis + isolated_axis = coords[:, axis] + + # rotate orientation of matrix for proper broadcasting + isolated_axis = np.moveaxis(isolated_axis, 1, 1 + axis) + + # calculate the moments for each point, one axis at a time + calc = calc * isolated_axis + + # sum all individual point moments to get our final answer + Mc = np.sum(calc, axis=0) + + return Mc + + +def moments(image, order=3, *, spacing=None): + """Calculate all raw image moments up to a certain order. + + The following properties can be calculated from raw image moments: + * Area as: ``M[0, 0]``. + * Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that raw moments are neither translation, scale nor rotation + invariant. + + Parameters + ---------- + image : (N[, ...]) double or uint8 array + Rasterized shape as image. + order : int, optional + Maximum order of moments. Default is 3. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + m : (``order + 1``, ``order + 1``) array + Raw image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> M = moments(image) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> centroid + (14.5, 14.5) + """ + return moments_central(image, (0,) * image.ndim, order=order, spacing=spacing) + + +def moments_central(image, center=None, order=3, *, spacing=None, **kwargs): + """Calculate all central image moments up to a certain order. + + The center coordinates (cr, cc) can be calculated from the raw moments as: + {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}. + + Note that central moments are translation invariant but not scale and + rotation invariant. + + Parameters + ---------- + image : (N[, ...]) double or uint8 array + Rasterized shape as image. + center : tuple of float, optional + Coordinates of the image centroid. This will be computed if it + is not provided. + order : int, optional + The maximum order of moments computed. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + mu : (``order + 1``, ``order + 1``) array + Central image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> M = moments(image) + >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) + >>> moments_central(image, centroid) + array([[16., 0., 20., 0.], + [ 0., 0., 0., 0.], + [20., 0., 25., 0.], + [ 0., 0., 0., 0.]]) + """ + if center is None: + # Note: No need for an explicit call to centroid. + # The centroid will be obtained from the raw moments. + moments_raw = moments(image, order=order, spacing=spacing) + return moments_raw_to_central(moments_raw) + float_dtype = _supported_float_type(image.dtype) + if spacing is None: + spacing = np.ones(image.ndim, dtype=float_dtype) + calc = image.astype(float_dtype, copy=False) + L = list(range(image.ndim)) # Starting axis labels for einsum. + sum_label = image.ndim # Label for axes over which to do dot product. + order_label = sum_label + 1 # Label for output coord / order axis. + orders = np.arange(order + 1, dtype=float_dtype) + for dim, dim_length in enumerate(image.shape): + delta = np.arange(dim_length, dtype=float_dtype) * spacing[dim] - center[dim] + powers_of_delta = delta[:, np.newaxis] ** orders + # Take dot product over `dim` axis of image, and coord axis of + # powers_of_delta. Label axes to dot product with `sum_label`. Put + # resulting order dimension at position of the `dim` axis. + calc = np.einsum( + calc, + L[:dim] + [sum_label] + L[dim + 1 :], # Input axis labels. + powers_of_delta, + [sum_label, order_label], # Coord, order axis labels. + L[:dim] + [order_label] + L[dim + 1 :], # Output axis labels. + optimize='greedy', + ) + return calc + + +def moments_normalized(mu, order=3, spacing=None): + """Calculate all normalized central image moments up to a certain order. + + Note that normalized central moments are translation and scale invariant + but not rotation invariant. + + Parameters + ---------- + mu : (M[, ...], M) array + Central image moments, where M must be greater than or equal + to ``order``. + order : int, optional + Maximum order of moments. Default is 3. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + nu : (``order + 1``[, ...], ``order + 1``) array + Normalized central image moments. + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 1 + >>> m = moments(image) + >>> centroid = (m[0, 1] / m[0, 0], m[1, 0] / m[0, 0]) + >>> mu = moments_central(image, centroid) + >>> moments_normalized(mu) + array([[ nan, nan, 0.078125 , 0. ], + [ nan, 0. , 0. , 0. ], + [0.078125 , 0. , 0.00610352, 0. ], + [0. , 0. , 0. , 0. ]]) + """ + if np.any(np.array(mu.shape) <= order): + raise ValueError("Shape of image moments must be >= `order`") + if spacing is None: + spacing = np.ones(mu.ndim) + nu = np.zeros_like(mu) + mu0 = mu.ravel()[0] + scale = min(spacing) + for powers in itertools.product(range(order + 1), repeat=mu.ndim): + if sum(powers) < 2: + nu[powers] = np.nan + else: + nu[powers] = (mu[powers] / scale ** sum(powers)) / ( + mu0 ** (sum(powers) / nu.ndim + 1) + ) + return nu + + +def moments_hu(nu): + """Calculate Hu's set of image moments (2D-only). + + Note that this set of moments is proved to be translation, scale and + rotation invariant. + + Parameters + ---------- + nu : (M, M) array + Normalized central image moments, where M must be >= 4. + + Returns + ------- + nu : (7,) array + Hu's set of image moments. + + References + ---------- + .. [1] M. K. Hu, "Visual Pattern Recognition by Moment Invariants", + IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962 + .. [2] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [3] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [4] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [5] https://en.wikipedia.org/wiki/Image_moment + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 0.5 + >>> image[10:12, 10:12] = 1 + >>> mu = moments_central(image) + >>> nu = moments_normalized(mu) + >>> np.round(moments_hu(nu), 4) # doctest: +FLOAT_CMP + array([0.7454, 0.3512, 0.104 , 0.0406, 0.0026, 0.0241, 0. ]) + """ + dtype = np.float32 if nu.dtype == 'float32' else np.float64 + return _moments_cy.moments_hu(nu.astype(dtype, copy=False)) + + +def centroid(image, *, spacing=None): + """Return the (weighted) centroid of an image. + + Parameters + ---------- + image : array + The input image. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + center : tuple of float, length ``image.ndim`` + The centroid of the (nonzero) pixels in ``image``. + + Examples + -------- + >>> image = np.zeros((20, 20), dtype=np.float64) + >>> image[13:17, 13:17] = 0.5 + >>> image[10:12, 10:12] = 1 + >>> centroid(image) + array([13.16666667, 13.16666667]) + """ + M = moments_central(image, center=(0,) * image.ndim, order=1, spacing=spacing) + center = ( + M[tuple(np.eye(image.ndim, dtype=int))] # array of weighted sums + # for each axis + / M[(0,) * image.ndim] + ) # weighted sum of all points + return center + + +def inertia_tensor(image, mu=None, *, spacing=None): + """Compute the inertia tensor of the input image. + + Parameters + ---------- + image : array + The input image. + mu : array, optional + The pre-computed central moments of ``image``. The inertia tensor + computation requires the central moments of the image. If an + application requires both the central moments and the inertia tensor + (for example, `skimage.measure.regionprops`), then it is more + efficient to pre-compute them and pass them to the inertia tensor + call. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + T : array, shape ``(image.ndim, image.ndim)`` + The inertia tensor of the input image. :math:`T_{i, j}` contains + the covariance of image intensity along axes :math:`i` and :math:`j`. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor + .. [2] Bernd Jähne. Spatio-Temporal Image Processing: Theory and + Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993. + """ + if mu is None: + mu = moments_central( + image, order=2, spacing=spacing + ) # don't need higher-order moments + mu0 = mu[(0,) * image.ndim] + result = np.zeros((image.ndim, image.ndim), dtype=mu.dtype) + + # nD expression to get coordinates ([2, 0], [0, 2]) (2D), + # ([2, 0, 0], [0, 2, 0], [0, 0, 2]) (3D), etc. + corners2 = tuple(2 * np.eye(image.ndim, dtype=int)) + d = np.diag(result) + d.flags.writeable = True + # See https://ocw.mit.edu/courses/aeronautics-and-astronautics/ + # 16-07-dynamics-fall-2009/lecture-notes/MIT16_07F09_Lec26.pdf + # Iii is the sum of second-order moments of every axis *except* i, not the + # second order moment of axis i. + # See also https://github.com/scikit-image/scikit-image/issues/3229 + d[:] = (np.sum(mu[corners2]) - mu[corners2]) / mu0 + + for dims in itertools.combinations(range(image.ndim), 2): + mu_index = np.zeros(image.ndim, dtype=int) + mu_index[list(dims)] = 1 + result[dims] = -mu[tuple(mu_index)] / mu0 + result.T[dims] = -mu[tuple(mu_index)] / mu0 + return result + + +def inertia_tensor_eigvals(image, mu=None, T=None, *, spacing=None): + """Compute the eigenvalues of the inertia tensor of the image. + + The inertia tensor measures covariance of the image intensity along + the image axes. (See `inertia_tensor`.) The relative magnitude of the + eigenvalues of the tensor is thus a measure of the elongation of a + (bright) object in the image. + + Parameters + ---------- + image : array + The input image. + mu : array, optional + The pre-computed central moments of ``image``. + T : array, shape ``(image.ndim, image.ndim)`` + The pre-computed inertia tensor. If ``T`` is given, ``mu`` and + ``image`` are ignored. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + eigvals : list of float, length ``image.ndim`` + The eigenvalues of the inertia tensor of ``image``, in descending + order. + + Notes + ----- + Computing the eigenvalues requires the inertia tensor of the input image. + This is much faster if the central moments (``mu``) are provided, or, + alternatively, one can provide the inertia tensor (``T``) directly. + """ + if T is None: + T = inertia_tensor(image, mu, spacing=spacing) + eigvals = np.linalg.eigvalsh(T) + # Floating point precision problems could make a positive + # semidefinite matrix have an eigenvalue that is very slightly + # negative. This can cause problems down the line, so set values + # very near zero to zero. + eigvals = np.clip(eigvals, 0, None, out=eigvals) + return sorted(eigvals, reverse=True) diff --git a/envs/kitoverlay/skimage/measure/_moments_analytical.py b/envs/kitoverlay/skimage/measure/_moments_analytical.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6ff130f033e23cbe1fffe96e45ca0dafcfb0f0 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_moments_analytical.py @@ -0,0 +1,171 @@ +"""Analytical transformations from raw image moments to central moments. + +The expressions for the 2D central moments of order <=2 are often given in +textbooks. Expressions for higher orders and dimensions were generated in SymPy +using ``tools/precompute/moments_sympy.py`` in the GitHub repository. + +""" + +import itertools +import math + +import numpy as np + + +def _moments_raw_to_central_fast(moments_raw): + """Analytical formulae for 2D and 3D central moments of order < 4. + + `moments_raw_to_central` will automatically call this function when + ndim < 4 and order < 4. + + Parameters + ---------- + moments_raw : ndarray + The raw moments. + + Returns + ------- + moments_central : ndarray + The central moments. + """ + ndim = moments_raw.ndim + order = moments_raw.shape[0] - 1 + float_dtype = moments_raw.dtype + # convert to float64 during the computation for better accuracy + moments_raw = moments_raw.astype(np.float64, copy=False) + moments_central = np.zeros_like(moments_raw) + if order >= 4 or ndim not in [2, 3]: + raise ValueError("This function only supports 2D or 3D moments of order < 4.") + m = moments_raw + if ndim == 2: + cx = m[1, 0] / m[0, 0] + cy = m[0, 1] / m[0, 0] + moments_central[0, 0] = m[0, 0] + # Note: 1st order moments are both 0 + if order > 1: + # 2nd order moments + moments_central[1, 1] = m[1, 1] - cx * m[0, 1] + moments_central[2, 0] = m[2, 0] - cx * m[1, 0] + moments_central[0, 2] = m[0, 2] - cy * m[0, 1] + if order > 2: + # 3rd order moments + moments_central[2, 1] = ( + m[2, 1] + - 2 * cx * m[1, 1] + - cy * m[2, 0] + + cx**2 * m[0, 1] + + cy * cx * m[1, 0] + ) + moments_central[1, 2] = ( + m[1, 2] - 2 * cy * m[1, 1] - cx * m[0, 2] + 2 * cy * cx * m[0, 1] + ) + moments_central[3, 0] = m[3, 0] - 3 * cx * m[2, 0] + 2 * cx**2 * m[1, 0] + moments_central[0, 3] = m[0, 3] - 3 * cy * m[0, 2] + 2 * cy**2 * m[0, 1] + else: + # 3D case + cx = m[1, 0, 0] / m[0, 0, 0] + cy = m[0, 1, 0] / m[0, 0, 0] + cz = m[0, 0, 1] / m[0, 0, 0] + moments_central[0, 0, 0] = m[0, 0, 0] + # Note: all first order moments are 0 + if order > 1: + # 2nd order moments + moments_central[0, 0, 2] = -cz * m[0, 0, 1] + m[0, 0, 2] + moments_central[0, 1, 1] = -cy * m[0, 0, 1] + m[0, 1, 1] + moments_central[0, 2, 0] = -cy * m[0, 1, 0] + m[0, 2, 0] + moments_central[1, 0, 1] = -cx * m[0, 0, 1] + m[1, 0, 1] + moments_central[1, 1, 0] = -cx * m[0, 1, 0] + m[1, 1, 0] + moments_central[2, 0, 0] = -cx * m[1, 0, 0] + m[2, 0, 0] + if order > 2: + # 3rd order moments + moments_central[0, 0, 3] = ( + 2 * cz**2 * m[0, 0, 1] - 3 * cz * m[0, 0, 2] + m[0, 0, 3] + ) + moments_central[0, 1, 2] = ( + -cy * m[0, 0, 2] + 2 * cz * (cy * m[0, 0, 1] - m[0, 1, 1]) + m[0, 1, 2] + ) + moments_central[0, 2, 1] = ( + cy**2 * m[0, 0, 1] + - 2 * cy * m[0, 1, 1] + + cz * (cy * m[0, 1, 0] - m[0, 2, 0]) + + m[0, 2, 1] + ) + moments_central[0, 3, 0] = ( + 2 * cy**2 * m[0, 1, 0] - 3 * cy * m[0, 2, 0] + m[0, 3, 0] + ) + moments_central[1, 0, 2] = ( + -cx * m[0, 0, 2] + 2 * cz * (cx * m[0, 0, 1] - m[1, 0, 1]) + m[1, 0, 2] + ) + moments_central[1, 1, 1] = ( + -cx * m[0, 1, 1] + + cy * (cx * m[0, 0, 1] - m[1, 0, 1]) + + cz * (cx * m[0, 1, 0] - m[1, 1, 0]) + + m[1, 1, 1] + ) + moments_central[1, 2, 0] = ( + -cx * m[0, 2, 0] - 2 * cy * (-cx * m[0, 1, 0] + m[1, 1, 0]) + m[1, 2, 0] + ) + moments_central[2, 0, 1] = ( + cx**2 * m[0, 0, 1] + - 2 * cx * m[1, 0, 1] + + cz * (cx * m[1, 0, 0] - m[2, 0, 0]) + + m[2, 0, 1] + ) + moments_central[2, 1, 0] = ( + cx**2 * m[0, 1, 0] + - 2 * cx * m[1, 1, 0] + + cy * (cx * m[1, 0, 0] - m[2, 0, 0]) + + m[2, 1, 0] + ) + moments_central[3, 0, 0] = ( + 2 * cx**2 * m[1, 0, 0] - 3 * cx * m[2, 0, 0] + m[3, 0, 0] + ) + + return moments_central.astype(float_dtype, copy=False) + + +def moments_raw_to_central(moments_raw): + ndim = moments_raw.ndim + order = moments_raw.shape[0] - 1 + if ndim in [2, 3] and order < 4: + return _moments_raw_to_central_fast(moments_raw) + + moments_central = np.zeros_like(moments_raw) + m = moments_raw + # centers as computed in centroid above + centers = tuple(m[tuple(np.eye(ndim, dtype=int))] / m[(0,) * ndim]) + + if ndim == 2: + # This is the general 2D formula from + # https://en.wikipedia.org/wiki/Image_moment#Central_moments + for p in range(order + 1): + for q in range(order + 1): + if p + q > order: + continue + for i in range(p + 1): + term1 = math.comb(p, i) + term1 *= (-centers[0]) ** (p - i) + for j in range(q + 1): + term2 = math.comb(q, j) + term2 *= (-centers[1]) ** (q - j) + moments_central[p, q] += term1 * term2 * m[i, j] + return moments_central + + # The nested loops below are an n-dimensional extension of the 2D formula + # given at https://en.wikipedia.org/wiki/Image_moment#Central_moments + + # iterate over all [0, order] (inclusive) on each axis + for orders in itertools.product(*((range(order + 1),) * ndim)): + # `orders` here is the index into the `moments_central` output array + if sum(orders) > order: + # skip any moment that is higher than the requested order + continue + # loop over terms from `m` contributing to `moments_central[orders]` + for idxs in itertools.product(*[range(o + 1) for o in orders]): + val = m[idxs] + for i_order, c, idx in zip(orders, centers, idxs): + val *= math.comb(i_order, idx) + val *= (-c) ** (i_order - idx) + moments_central[orders] += val + + return moments_central diff --git a/envs/kitoverlay/skimage/measure/_polygon.py b/envs/kitoverlay/skimage/measure/_polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..23aa1cea463226d06ab91f9ef602032bbcf8eead --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_polygon.py @@ -0,0 +1,168 @@ +import numpy as np +from scipy import signal + + +def approximate_polygon(coords, tolerance): + """Approximate a polygonal chain with the specified tolerance. + + It is based on the Douglas-Peucker algorithm. + + Note that the approximated polygon is always within the convex hull of the + original polygon. + + Parameters + ---------- + coords : (K, 2) array + Coordinate array. + tolerance : float + Maximum distance from original points of polygon to approximated + polygonal chain. If tolerance is 0, the original coordinate array + is returned. + + Returns + ------- + coords : (L, 2) array + Approximated polygonal chain where L <= K. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm + """ + if tolerance <= 0: + return coords + + chain = np.zeros(coords.shape[0], 'bool') + # pre-allocate distance array for all points + dists = np.zeros(coords.shape[0]) + chain[0] = True + chain[-1] = True + pos_stack = [(0, chain.shape[0] - 1)] + end_of_chain = False + + while not end_of_chain: + start, end = pos_stack.pop() + # determine properties of current line segment + r0, c0 = coords[start, :] + r1, c1 = coords[end, :] + dr = r1 - r0 + dc = c1 - c0 + segment_angle = -np.arctan2(dr, dc) + segment_dist = c0 * np.sin(segment_angle) + r0 * np.cos(segment_angle) + + # select points in-between line segment + segment_coords = coords[start + 1 : end, :] + segment_dists = dists[start + 1 : end] + + # check whether to take perpendicular or euclidean distance with + # inner product of vectors + + # vectors from points -> start and end + dr0 = segment_coords[:, 0] - r0 + dc0 = segment_coords[:, 1] - c0 + dr1 = segment_coords[:, 0] - r1 + dc1 = segment_coords[:, 1] - c1 + # vectors points -> start and end projected on start -> end vector + projected_lengths0 = dr0 * dr + dc0 * dc + projected_lengths1 = -dr1 * dr - dc1 * dc + perp = np.logical_and(projected_lengths0 > 0, projected_lengths1 > 0) + eucl = np.logical_not(perp) + segment_dists[perp] = np.abs( + segment_coords[perp, 0] * np.cos(segment_angle) + + segment_coords[perp, 1] * np.sin(segment_angle) + - segment_dist + ) + segment_dists[eucl] = np.minimum( + # distance to start point + np.sqrt(dc0[eucl] ** 2 + dr0[eucl] ** 2), + # distance to end point + np.sqrt(dc1[eucl] ** 2 + dr1[eucl] ** 2), + ) + + if np.any(segment_dists > tolerance): + # select point with maximum distance to line + new_end = start + np.argmax(segment_dists) + 1 + pos_stack.append((new_end, end)) + pos_stack.append((start, new_end)) + chain[new_end] = True + + if len(pos_stack) == 0: + end_of_chain = True + + return coords[chain, :] + + +# B-Spline subdivision +_SUBDIVISION_MASKS = { + # degree: (mask_even, mask_odd) + # extracted from (degree + 2)th row of Pascal's triangle + 1: ([1, 1], [1, 1]), + 2: ([3, 1], [1, 3]), + 3: ([1, 6, 1], [0, 4, 4]), + 4: ([5, 10, 1], [1, 10, 5]), + 5: ([1, 15, 15, 1], [0, 6, 20, 6]), + 6: ([7, 35, 21, 1], [1, 21, 35, 7]), + 7: ([1, 28, 70, 28, 1], [0, 8, 56, 56, 8]), +} + + +def subdivide_polygon(coords, degree=2, preserve_ends=False): + """Subdivision of polygonal curves using B-Splines. + + Note that the resulting curve is always within the convex hull of the + original polygon. Circular polygons stay closed after subdivision. + + Parameters + ---------- + coords : (K, 2) array + Coordinate array. + degree : {1, 2, 3, 4, 5, 6, 7}, optional + Degree of B-Spline. Default is 2. + preserve_ends : bool, optional + Preserve first and last coordinate of non-circular polygon. Default is + False. + + Returns + ------- + coords : (L, 2) array + Subdivided coordinate array. + + References + ---------- + .. [1] http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf + """ + if degree not in _SUBDIVISION_MASKS: + raise ValueError("Invalid B-Spline degree. Only degree 1 - 7 is " "supported.") + + circular = np.all(coords[0, :] == coords[-1, :]) + + method = 'valid' + if circular: + # remove last coordinate because of wrapping + coords = coords[:-1, :] + # circular convolution by wrapping boundaries + method = 'same' + + mask_even, mask_odd = _SUBDIVISION_MASKS[degree] + # divide by total weight + mask_even = np.array(mask_even, float) / (2**degree) + mask_odd = np.array(mask_odd, float) / (2**degree) + + even = signal.convolve2d( + coords.T, np.atleast_2d(mask_even), mode=method, boundary='wrap' + ) + odd = signal.convolve2d( + coords.T, np.atleast_2d(mask_odd), mode=method, boundary='wrap' + ) + + out = np.zeros((even.shape[1] + odd.shape[1], 2)) + out[1::2] = even.T + out[::2] = odd.T + + if circular: + # close polygon + out = np.vstack([out, out[0, :]]) + + if preserve_ends and not circular: + out = np.vstack([coords[0, :], out, coords[-1, :]]) + + return out diff --git a/envs/kitoverlay/skimage/measure/_regionprops.py b/envs/kitoverlay/skimage/measure/_regionprops.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe5e7b9b03624cd0e0f3146bbec1529c368340f --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_regionprops.py @@ -0,0 +1,1498 @@ +import inspect +import sys +from functools import wraps +from math import atan2, sqrt +from math import pi as PI +from warnings import warn + +import numpy as np +from scipy import ndimage as ndi +from scipy.spatial.distance import pdist + +from . import _moments +from ._find_contours import find_contours +from ._marching_cubes_lewiner import marching_cubes +from ._regionprops_utils import ( + _normalize_spacing, + euler_number, + perimeter, + perimeter_crofton, +) + +__all__ = ['regionprops', 'euler_number', 'perimeter', 'perimeter_crofton'] + + +# All values in this PROPS dict correspond to current scikit-image property +# names. The keys in this PROPS dict correspond to deprecated names used in +# prior releases +PROPS = { + 'Area': 'area', + 'BoundingBox': 'bbox', + 'BoundingBoxArea': 'area_bbox', + 'bbox_area': 'area_bbox', + 'CentralMoments': 'moments_central', + 'Centroid': 'centroid', + 'ConvexArea': 'area_convex', + 'convex_area': 'area_convex', + # 'ConvexHull', + 'ConvexImage': 'image_convex', + 'convex_image': 'image_convex', + 'Coordinates': 'coords', + 'Eccentricity': 'eccentricity', + 'EquivDiameter': 'equivalent_diameter_area', + 'equivalent_diameter': 'equivalent_diameter_area', + 'EulerNumber': 'euler_number', + 'Extent': 'extent', + # 'Extrema', + 'FeretDiameter': 'feret_diameter_max', + 'FeretDiameterMax': 'feret_diameter_max', + 'FilledArea': 'area_filled', + 'filled_area': 'area_filled', + 'FilledImage': 'image_filled', + 'filled_image': 'image_filled', + 'HuMoments': 'moments_hu', + 'Image': 'image', + 'InertiaTensor': 'inertia_tensor', + 'InertiaTensorEigvals': 'inertia_tensor_eigvals', + 'IntensityImage': 'image_intensity', + 'intensity_image': 'image_intensity', + 'Label': 'label', + 'LocalCentroid': 'centroid_local', + 'local_centroid': 'centroid_local', + 'MajorAxisLength': 'axis_major_length', + 'major_axis_length': 'axis_major_length', + 'MaxIntensity': 'intensity_max', + 'max_intensity': 'intensity_max', + 'MeanIntensity': 'intensity_mean', + 'mean_intensity': 'intensity_mean', + 'MinIntensity': 'intensity_min', + 'min_intensity': 'intensity_min', + 'std_intensity': 'intensity_std', + 'MinorAxisLength': 'axis_minor_length', + 'minor_axis_length': 'axis_minor_length', + 'Moments': 'moments', + 'NormalizedMoments': 'moments_normalized', + 'Orientation': 'orientation', + 'Perimeter': 'perimeter', + 'CroftonPerimeter': 'perimeter_crofton', + # 'PixelIdxList', + # 'PixelList', + 'Slice': 'slice', + 'Solidity': 'solidity', + # 'SubarrayIdx' + 'WeightedCentralMoments': 'moments_weighted_central', + 'weighted_moments_central': 'moments_weighted_central', + 'WeightedCentroid': 'centroid_weighted', + 'weighted_centroid': 'centroid_weighted', + 'WeightedHuMoments': 'moments_weighted_hu', + 'weighted_moments_hu': 'moments_weighted_hu', + 'WeightedLocalCentroid': 'centroid_weighted_local', + 'weighted_local_centroid': 'centroid_weighted_local', + 'WeightedMoments': 'moments_weighted', + 'weighted_moments': 'moments_weighted', + 'WeightedNormalizedMoments': 'moments_weighted_normalized', + 'weighted_moments_normalized': 'moments_weighted_normalized', +} + +COL_DTYPES = { + 'area': float, + 'area_bbox': float, + 'area_convex': float, + 'area_filled': float, + 'axis_major_length': float, + 'axis_minor_length': float, + 'bbox': int, + 'centroid': float, + 'centroid_local': float, + 'centroid_weighted': float, + 'centroid_weighted_local': float, + 'coords': object, + 'coords_scaled': object, + 'eccentricity': float, + 'equivalent_diameter_area': float, + 'euler_number': int, + 'extent': float, + 'feret_diameter_max': float, + 'image': object, + 'image_convex': object, + 'image_filled': object, + 'image_intensity': object, + 'inertia_tensor': float, + 'inertia_tensor_eigvals': float, + 'intensity_max': float, + 'intensity_mean': float, + 'intensity_median': float, + 'intensity_min': float, + 'intensity_std': float, + 'label': int, + 'moments': float, + 'moments_central': float, + 'moments_hu': float, + 'moments_normalized': float, + 'moments_weighted': float, + 'moments_weighted_central': float, + 'moments_weighted_hu': float, + 'moments_weighted_normalized': float, + 'num_pixels': int, + 'orientation': float, + 'perimeter': float, + 'perimeter_crofton': float, + 'slice': object, + 'solidity': float, +} + +OBJECT_COLUMNS = [col for col, dtype in COL_DTYPES.items() if dtype == object] + +PROP_VALS = set(PROPS.values()) + +_require_intensity_image = ( + 'image_intensity', + 'intensity_max', + 'intensity_mean', + 'intensity_median', + 'intensity_min', + 'intensity_std', + 'moments_weighted', + 'moments_weighted_central', + 'centroid_weighted', + 'centroid_weighted_local', + 'moments_weighted_hu', + 'moments_weighted_normalized', +) + + +def _infer_number_of_required_args(func): + """Infer the number of required arguments for a given function. + + Parameters + ---------- + func : callable + The function that is being inspected. + + Returns + ------- + n_args : int + The number of required arguments for `func`. + """ + argspec = inspect.getfullargspec(func) + n_args = len(argspec.args) + if argspec.defaults is not None: + n_args -= len(argspec.defaults) + return n_args + + +def _infer_regionprop_dtype(func, *, intensity, ndim): + """Infer the dtype of a region property calculated by `func`. + + If a region property function always returns the same shape and type of + output regardless of input size, then the dtype is the dtype of the + returned array. Otherwise, the property has object dtype. + + Parameters + ---------- + func : callable + Function to be tested. The signature should be array[bool] -> Any if + `intensity` is False, or *(array[bool], array[float]) -> Any otherwise. + intensity : bool + Whether the regionprop is calculated using an intensity image. + ndim : int + The number of dimensions for which to check `func`. + + Returns + ------- + dtype : NumPy data type + The data type of the returned property. + """ + mask_1 = np.ones((1,) * ndim, dtype=bool) + mask_1 = np.pad(mask_1, (0, 1), constant_values=False) + mask_2 = np.ones((2,) * ndim, dtype=bool) + mask_2 = np.pad(mask_2, (1, 0), constant_values=False) + propmasks = [mask_1, mask_2] + + rng = np.random.default_rng() + + if intensity and _infer_number_of_required_args(func) == 2: + + def _func(mask): + return func(mask, rng.random(mask.shape)) + + else: + _func = func + props1, props2 = map(_func, propmasks) + if ( + np.isscalar(props1) + and np.isscalar(props2) + or np.array(props1).shape == np.array(props2).shape + ): + dtype = np.array(props1).dtype.type + else: + dtype = np.object_ + return dtype + + +def _cached(f): + @wraps(f) + def wrapper(obj): + cache = obj._cache + prop = f.__name__ + + if not obj._cache_active: + return f(obj) + + if prop not in cache: + cache[prop] = f(obj) + + return cache[prop] + + return wrapper + + +def only2d(method): + @wraps(method) + def func2d(self, *args, **kwargs): + if self._ndim > 2: + raise NotImplementedError( + f"Property {method.__name__} is not implemented for 3D images" + ) + return method(self, *args, **kwargs) + + return func2d + + +def _inertia_eigvals_to_axes_lengths_3D(inertia_tensor_eigvals): + """Compute ellipsoid axis lengths from inertia tensor eigenvalues. + + Parameters + ---------- + inertia_tensor_eigvals : sequence of float + A sequence of 3 floating point eigenvalues, sorted in descending order. + + Returns + ------- + axis_lengths : list of float + The ellipsoid axis lengths sorted in descending order. + + Notes + ----- + Let a >= b >= c be the ellipsoid semi-axes and s1 >= s2 >= s3 be the + inertia tensor eigenvalues. + + The inertia tensor eigenvalues are given for a solid ellipsoid in [1]_. + s1 = 1 / 5 * (a**2 + b**2) + s2 = 1 / 5 * (a**2 + c**2) + s3 = 1 / 5 * (b**2 + c**2) + + Rearranging to solve for a, b, c in terms of s1, s2, s3 gives + a = math.sqrt(5 / 2 * ( s1 + s2 - s3)) + b = math.sqrt(5 / 2 * ( s1 - s2 + s3)) + c = math.sqrt(5 / 2 * (-s1 + s2 + s3)) + + We can then simply replace sqrt(5/2) by sqrt(10) to get the full axes + lengths rather than the semi-axes lengths. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors + """ + axis_lengths = [] + for ax in range(2, -1, -1): + w = sum(v * -1 if i == ax else v for i, v in enumerate(inertia_tensor_eigvals)) + w = max(0, w) # numerical errors can lead to small negative values + axis_lengths.append(sqrt(10 * w)) + return axis_lengths + + +class RegionProperties: + """Provides properties of a labeled image region. + + Please refer to `skimage.measure.regionprops` for more information + on the available region properties. + + Examples + -------- + >>> RegionProperties( + ... slice=(slice(0, 2), slice(0, 4)), + ... label=2, + ... label_image=np.array([[0, 1, 1, 2, 0], [2, 2, 2, 2, 0]]), + ... intensity_image=None, + ... cache_active=False, + ... ) + + """ + + def __init__( + self, + slice, + label, + label_image, + intensity_image, + cache_active, + *, + extra_properties=None, + spacing=None, + offset=None, + ): + if intensity_image is not None: + ndim = label_image.ndim + if not ( + intensity_image.shape[:ndim] == label_image.shape + and intensity_image.ndim in [ndim, ndim + 1] + ): + raise ValueError( + 'Label and intensity image shapes must match,' + ' except for channel (last) axis.' + ) + multichannel = label_image.shape < intensity_image.shape + else: + multichannel = False + + self.label = label + if offset is None: + offset = np.zeros((label_image.ndim,), dtype=int) + self._offset = np.array(offset) + + self._slice = slice + self.slice = slice + self._label_image = label_image + self._intensity_image = intensity_image + + self._cache_active = cache_active + self._cache = {} + self._ndim = label_image.ndim + self._multichannel = multichannel + self._spatial_axes = tuple(range(self._ndim)) + if spacing is None: + spacing = np.full(self._ndim, 1.0) + self._spacing = _normalize_spacing(spacing, self._ndim) + self._pixel_area = np.prod(self._spacing) + + self._extra_properties = {} + if extra_properties is not None: + for func in extra_properties: + name = func.__name__ + if hasattr(self, name): + msg = ( + f"Extra property '{name}' is shadowed by existing " + f"property and will be inaccessible. Consider " + f"renaming it." + ) + warn(msg) + self._extra_properties = {func.__name__: func for func in extra_properties} + + def __getattr__(self, attr): + if attr == "__setstate__": + # When deserializing this object with pickle, `__setstate__` + # is accessed before any other attributes like `self._intensity_image` + # are available which leads to a RecursionError when trying to + # access them later on in this function. So guard against this by + # provoking the default AttributeError (gh-6465). + return self.__getattribute__(attr) + + if self._intensity_image is None and attr in _require_intensity_image: + raise AttributeError( + f"Attribute '{attr}' unavailable when `intensity_image` " + f"has not been specified." + ) + if attr in self._extra_properties: + func = self._extra_properties[attr] + n_args = _infer_number_of_required_args(func) + # determine whether func requires intensity image + if n_args == 2: + if self._intensity_image is not None: + if self._multichannel: + multichannel_list = [ + func(self.image, self.image_intensity[..., i]) + for i in range(self.image_intensity.shape[-1]) + ] + return np.stack(multichannel_list, axis=-1) + else: + return func(self.image, self.image_intensity) + else: + raise AttributeError( + f'intensity image required to calculate {attr}' + ) + elif n_args == 1: + return func(self.image) + else: + raise AttributeError( + f'Custom regionprop function\'s number of arguments must ' + f'be 1 or 2, but {attr} takes {n_args} arguments.' + ) + elif attr in PROPS and attr.lower() == attr: + if ( + self._intensity_image is None + and PROPS[attr] in _require_intensity_image + ): + raise AttributeError( + f"Attribute '{attr}' unavailable when `intensity_image` " + f"has not been specified." + ) + warn( + f"`RegionProperties.{attr}` is deprecated starting in " + "version 0.26 and will be removed in version 2.0. Use " + f"`RegionProperties.{PROPS[attr]}` instead. ", + category=FutureWarning, + stacklevel=2, + ) + # retrieve deprecated property (excluding old CamelCase ones) + return getattr(self, PROPS[attr]) + + # Fallback to default behavior, potentially raising an attribute error + return self.__getattribute__(attr) + + def __setattr__(self, name, value): + if name in PROPS: + super().__setattr__(PROPS[name], value) + else: + super().__setattr__(name, value) + + @property + @_cached + def num_pixels(self): + return np.sum(self.image) + + @property + @_cached + def area(self): + return np.sum(self.image) * self._pixel_area + + @property + def bbox(self): + """ + Returns + ------- + A tuple of the bounding box's start coordinates for each dimension, + followed by the end coordinates for each dimension. + """ + return tuple( + [self.slice[i].start for i in range(self._ndim)] + + [self.slice[i].stop for i in range(self._ndim)] + ) + + @property + def area_bbox(self): + return self.image.size * self._pixel_area + + @property + def centroid(self): + return tuple(self.coords_scaled.mean(axis=0)) + + @property + @_cached + def area_convex(self): + return np.sum(self.image_convex) * self._pixel_area + + @property + @_cached + def image_convex(self): + from ..morphology.convex_hull import convex_hull_image + + return convex_hull_image(self.image) + + @property + def coords_scaled(self): + indices = np.argwhere(self.image) + object_offset = np.array([self.slice[i].start for i in range(self._ndim)]) + return (object_offset + indices) * self._spacing + self._offset + + @property + def coords(self): + indices = np.argwhere(self.image) + object_offset = np.array([self.slice[i].start for i in range(self._ndim)]) + return object_offset + indices + self._offset + + @property + @only2d + def eccentricity(self): + l1, l2 = self.inertia_tensor_eigvals + if l1 == 0: + return 0 + return sqrt(1 - l2 / l1) + + @property + def equivalent_diameter_area(self): + return (2 * self._ndim * self.area / PI) ** (1 / self._ndim) + + @property + def euler_number(self): + if self._ndim not in [2, 3]: + raise NotImplementedError( + 'Euler number is implemented for 2D and 3D images only' + ) + return euler_number(self.image, self._ndim) + + @property + def extent(self): + return self.area / self.area_bbox + + @property + def feret_diameter_max(self): + identity_convex_hull = np.pad( + self.image_convex, 2, mode='constant', constant_values=0 + ) + if self._ndim == 2: + coordinates = np.vstack( + find_contours(identity_convex_hull, 0.5, fully_connected='high') + ) + elif self._ndim == 3: + coordinates, _, _, _ = marching_cubes(identity_convex_hull, level=0.5) + distances = pdist(coordinates * self._spacing, 'sqeuclidean') + return sqrt(np.max(distances)) + + @property + def area_filled(self): + return np.sum(self.image_filled) * self._pixel_area + + @property + @_cached + def image_filled(self): + structure = np.ones((3,) * self._ndim) + return ndi.binary_fill_holes(self.image, structure) + + @property + @_cached + def image(self): + return self._label_image[self.slice] == self.label + + @property + @_cached + def inertia_tensor(self): + mu = self.moments_central + return _moments.inertia_tensor(self.image, mu, spacing=self._spacing) + + @property + @_cached + def inertia_tensor_eigvals(self): + return _moments.inertia_tensor_eigvals(self.image, T=self.inertia_tensor) + + @property + @_cached + def image_intensity(self): + if self._intensity_image is None: + raise AttributeError('No intensity image specified.') + image = ( + self.image + if not self._multichannel + else np.expand_dims(self.image, self._ndim) + ) + return self._intensity_image[self.slice] * image + + def _image_intensity_double(self): + return self.image_intensity.astype(np.float64, copy=False) + + @property + def centroid_local(self): + M = self.moments + M0 = M[(0,) * self._ndim] + + def _get_element(axis): + return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis) + + return np.asarray( + tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim)) + ) + + @property + def intensity_max(self): + vals = self.image_intensity[self.image] + return np.max(vals, axis=0).astype(np.float64, copy=False) + + @property + def intensity_mean(self): + return np.mean(self.image_intensity[self.image], axis=0) + + @property + def intensity_median(self): + return np.median(self.image_intensity[self.image], axis=0) + + @property + def intensity_min(self): + vals = self.image_intensity[self.image] + return np.min(vals, axis=0).astype(np.float64, copy=False) + + @property + def intensity_std(self): + vals = self.image_intensity[self.image] + return np.std(vals, axis=0) + + @property + def axis_major_length(self): + if self._ndim == 2: + l1 = self.inertia_tensor_eigvals[0] + return 4 * sqrt(l1) + elif self._ndim == 3: + # equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[0] + ev = self.inertia_tensor_eigvals + l2 = 10 * (ev[0] + ev[1] - ev[2]) + return sqrt(max(0, l2)) + else: + raise ValueError("axis_major_length only available in 2D and 3D") + + @property + def axis_minor_length(self): + if self._ndim == 2: + l2 = self.inertia_tensor_eigvals[-1] + return 4 * sqrt(l2) + elif self._ndim == 3: + # equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[-1] + ev = self.inertia_tensor_eigvals + l2 = 10 * (-ev[0] + ev[1] + ev[2]) + # numerical errors can lead to small negative values + return sqrt(max(0, l2)) + else: + raise ValueError("axis_minor_length only available in 2D and 3D") + + @property + @_cached + def moments(self): + M = _moments.moments(self.image.astype(np.uint8), 3, spacing=self._spacing) + return M + + @property + @_cached + def moments_central(self): + mu = _moments.moments_central( + self.image.astype(np.uint8), + self.centroid_local, + order=3, + spacing=self._spacing, + ) + return mu + + @property + @only2d + def moments_hu(self): + if any(s != 1.0 for s in self._spacing): + raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only') + return _moments.moments_hu(self.moments_normalized) + + @property + @_cached + def moments_normalized(self): + return _moments.moments_normalized( + self.moments_central, 3, spacing=self._spacing + ) + + @property + @only2d + def orientation(self): + a, b, b, c = self.inertia_tensor.flat + if a - c == 0: + if b < 0: + return PI / 4.0 + else: + return -PI / 4.0 + else: + return 0.5 * atan2(-2 * b, c - a) + + @property + @only2d + def perimeter(self): + if len(np.unique(self._spacing)) != 1: + raise NotImplementedError('`perimeter` supports isotropic spacings only') + return perimeter(self.image, 4) * self._spacing[0] + + @property + @only2d + def perimeter_crofton(self): + if len(np.unique(self._spacing)) != 1: + raise NotImplementedError('`perimeter` supports isotropic spacings only') + return perimeter_crofton(self.image, 4) * self._spacing[0] + + @property + def solidity(self): + return self.area / self.area_convex + + @property + def centroid_weighted(self): + ctr = self.centroid_weighted_local + return tuple( + idx + slc.start * spc + for idx, slc, spc in zip(ctr, self.slice, self._spacing) + ) + + @property + def centroid_weighted_local(self): + M = self.moments_weighted + M0 = M[(0,) * self._ndim] + + def _get_element(axis): + return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis) + + return np.asarray( + tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim)) + ) + + @property + @_cached + def moments_weighted(self): + image = self._image_intensity_double() + if self._multichannel: + moments = np.stack( + [ + _moments.moments(image[..., i], order=3, spacing=self._spacing) + for i in range(image.shape[-1]) + ], + axis=-1, + ) + else: + moments = _moments.moments(image, order=3, spacing=self._spacing) + return moments + + @property + @_cached + def moments_weighted_central(self): + ctr = self.centroid_weighted_local + image = self._image_intensity_double() + if self._multichannel: + moments_list = [ + _moments.moments_central( + image[..., i], center=ctr[..., i], order=3, spacing=self._spacing + ) + for i in range(image.shape[-1]) + ] + moments = np.stack(moments_list, axis=-1) + else: + moments = _moments.moments_central( + image, ctr, order=3, spacing=self._spacing + ) + return moments + + @property + @only2d + def moments_weighted_hu(self): + if not (np.array(self._spacing) == np.array([1, 1])).all(): + raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only') + nu = self.moments_weighted_normalized + if self._multichannel: + nchannels = self._intensity_image.shape[-1] + return np.stack( + [_moments.moments_hu(nu[..., i]) for i in range(nchannels)], + axis=-1, + ) + else: + return _moments.moments_hu(nu) + + @property + @_cached + def moments_weighted_normalized(self): + mu = self.moments_weighted_central + if self._multichannel: + nchannels = self._intensity_image.shape[-1] + return np.stack( + [ + _moments.moments_normalized( + mu[..., i], order=3, spacing=self._spacing + ) + for i in range(nchannels) + ], + axis=-1, + ) + else: + return _moments.moments_normalized(mu, order=3, spacing=self._spacing) + + def __iter__(self): + props = PROP_VALS + + if self._intensity_image is None: + unavailable_props = _require_intensity_image + props = props.difference(unavailable_props) + + return iter(sorted(props)) + + def __getitem__(self, key): + if key in PROPS: + warn( + f"`RegionProperties[{key!r}]` is deprecated starting in " + "version 0.26 and will be removed in version 2.0. Use " + f"`RegionProperties[{PROPS[key]!r}]` instead. ", + category=FutureWarning, + stacklevel=2, + ) + key = PROPS[key] + return getattr(self, key) + + def __eq__(self, other): + if not isinstance(other, RegionProperties): + return False + + for key in PROP_VALS: + try: + # so that NaNs are equal + np.testing.assert_equal( + getattr(self, key, None), getattr(other, key, None) + ) + except AssertionError: + return False + + return True + + def __repr__(self): + cls_name = type(self).__qualname__ + out = f"<{cls_name}: label={self.label!r}, bbox={self.bbox}>" + return out + + +# For compatibility with code written prior to 0.16 +_RegionProperties = RegionProperties + + +def _props_to_dict(regions, properties=('label', 'bbox'), separator='-'): + """Convert image region properties list into a column dictionary. + + Parameters + ---------- + regions : (K,) list + List of RegionProperties objects as returned by :func:`regionprops`. + properties : tuple or list of str, optional + Properties that will be included in the resulting dictionary + For a list of available properties, please see :func:`regionprops`. + Users should remember to add "label" to keep track of region + identities. + separator : str, optional + For non-scalar properties not listed in OBJECT_COLUMNS, each element + will appear in its own column, with the index of that element separated + from the property name by this separator. For example, the inertia + tensor of a 2D region will appear in four columns: + ``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``, + and ``inertia_tensor-1-1`` (where the separator is ``-``). + + Object columns are those that cannot be split in this way because the + number of columns would change depending on the object. For example, + ``image`` and ``coords``. + + Returns + ------- + out_dict : dict + Dictionary mapping property names to an array of values of that + property, one value per region. This dictionary can be used as input to + pandas ``DataFrame`` to map property names to columns in the frame and + regions to rows. + + Notes + ----- + Each column contains either a scalar property, an object property, or an + element in a multidimensional array. + + Properties with scalar values for each region, such as "eccentricity", will + appear as a float or int array with that property name as key. + + Multidimensional properties *of fixed size* for a given image dimension, + such as "centroid" (every centroid will have three elements in a 3D image, + no matter the region size), will be split into that many columns, with the + name {property_name}{separator}{element_num} (for 1D properties), + {property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D + properties), and so on. + + For multidimensional properties that don't have a fixed size, such as + "image" (the image of a region varies in size depending on the region + size), an object array will be used, with the corresponding property name + as the key. + + Examples + -------- + >>> from skimage import data, util, measure + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> proplist = regionprops(label_image, image) + >>> props = _props_to_dict(proplist, properties=['label', 'inertia_tensor', + ... 'inertia_tensor_eigvals']) + >>> props # doctest: +ELLIPSIS +SKIP + {'label': array([ 1, 2, ...]), ... + 'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ... + ..., + 'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])} + + The resulting dictionary can be directly passed to pandas, if installed, to + obtain a clean DataFrame: + + >>> import pandas as pd # doctest: +SKIP + >>> data = pd.DataFrame(props) # doctest: +SKIP + >>> data.head() # doctest: +SKIP + label inertia_tensor-0-0 ... inertia_tensor_eigvals-1 + 0 1 4012.909888 ... 267.065503 + 1 2 8.514739 ... 2.834806 + 2 3 0.666667 ... 0.000000 + 3 4 0.000000 ... 0.000000 + 4 5 0.222222 ... 0.111111 + + """ + + out = {} + n = len(regions) + for prop in properties: + r = regions[0] + # Copy the original property name so the output will have the + # user-provided property name in the case of deprecated names. + orig_prop = prop + # determine the current property name for any deprecated property. + prop = PROPS.get(prop, prop) + rp = getattr(r, prop) + if prop in COL_DTYPES: + dtype = COL_DTYPES[prop] + else: + func = r._extra_properties[prop] + dtype = _infer_regionprop_dtype( + func, + intensity=r._intensity_image is not None, + ndim=r.image.ndim, + ) + + # scalars and objects are dedicated one column per prop + # array properties are raveled into multiple columns + # for more info, refer to notes 1 + if np.isscalar(rp) or prop in OBJECT_COLUMNS or dtype is np.object_: + column_buffer = np.empty(n, dtype=dtype) + for i in range(n): + column_buffer[i] = regions[i][prop] + out[orig_prop] = np.copy(column_buffer) + else: + # precompute property column names and locations + modified_props = [] + locs = [] + for ind in np.ndindex(np.shape(rp)): + modified_props.append(separator.join(map(str, (orig_prop,) + ind))) + locs.append(ind if len(ind) > 1 else ind[0]) + + # fill temporary column data_array + n_columns = len(locs) + column_data = np.empty((n, n_columns), dtype=dtype) + for k in range(n): + # we coerce to a numpy array to ensure structures like + # tuple-of-arrays expand correctly into columns + rp = np.asarray(regions[k][prop]) + for i, loc in enumerate(locs): + column_data[k, i] = rp[loc] + + # add the columns to the output dictionary + for i, modified_prop in enumerate(modified_props): + out[modified_prop] = column_data[:, i] + return out + + +def regionprops_table( + label_image, + intensity_image=None, + properties=('label', 'bbox'), + *, + cache=True, + separator='-', + extra_properties=None, + spacing=None, +): + """Compute region properties and return them as a pandas-compatible table. + + The return value is a dictionary mapping property names to value arrays. + This dictionary can be used as input to ``pandas.DataFrame`` to result in + a "tidy" [1]_ table with one region per row and one property per column. + + Use this function typically when you want to do downstream data analysis, + or save region data to disk in a structured way. One downside of this + function is that it breaks multi-dimensional properties into independent + columns; for example, the region centroids of a 3D image end up in three + different columns, one per dimension. If you need to do complex + computations with the region properties, using + :func:`skimage.measure.regionprops` might be more fitting. + + .. versionadded:: 0.16 + + Parameters + ---------- + label_image : (M, N[, P]) ndarray + Label image. Labels with value 0 are ignored. + intensity_image : (M, N[, P][, C]) ndarray, optional + Intensity (input) image of same shape as label image, plus + optionally an extra dimension for multichannel data. The channel dimension, + if present, must be the last axis. Default is None. + + .. versionchanged:: 0.18.0 + The ability to provide an extra dimension for channels was added. + properties : tuple or list of str, optional + Properties that will be included in the resulting dictionary + For a list of available properties, please see :func:`regionprops`. + Users should remember to add "label" to keep track of region + identities. + cache : bool, optional + Determine whether to cache calculated properties. The computation is + much faster for cached properties, whereas the memory consumption + increases. + separator : str, optional + For non-scalar properties not listed in OBJECT_COLUMNS, each element + will appear in its own column, with the index of that element separated + from the property name by this separator. For example, the inertia + tensor of a 2D region will appear in four columns: + ``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``, + and ``inertia_tensor-1-1`` (where the separator is ``-``). + + Object columns are those that cannot be split in this way because the + number of columns would change depending on the object. For example, + ``image`` and ``coords``. + extra_properties : iterable of callables + Add extra property computation functions that are not included with + skimage. The name of the property is derived from the function name, + the dtype is inferred by calling the function on a small sample. + If the name of an extra property clashes with the name of an existing + property the extra property will not be visible and a UserWarning is + issued. A property computation function must take a region mask as its + first argument. If the property requires an intensity image, it must + accept the intensity image as the second argument. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + + Returns + ------- + out_dict : dict + Dictionary mapping property names to an array of values of that + property, one value per region. This dictionary can be used as input to + pandas ``DataFrame`` to map property names to columns in the frame and + regions to rows. If the image has no regions, + the arrays will have length 0, but the correct type. + + Notes + ----- + Each column contains either a scalar property, an object property, or an + element in a multidimensional array. + + Properties with scalar values for each region, such as "eccentricity", will + appear as a float or int array with that property name as key. + + Multidimensional properties *of fixed size* for a given image dimension, + such as "centroid" (every centroid will have three elements in a 3D image, + no matter the region size), will be split into that many columns, with the + name {property_name}{separator}{element_num} (for 1D properties), + {property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D + properties), and so on. + + For multidimensional properties that don't have a fixed size, such as + "image" (the image of a region varies in size depending on the region + size), an object array will be used, with the corresponding property name + as the key. + + References + ---------- + .. [1] Wickham, H (2014) "Tidy Data" Journal of Statistical Software, + 59(10), 1–23. https://doi.org/10.18637/jss.v059.i10 + https://vita.had.co.nz/papers/tidy-data.pdf + + Examples + -------- + >>> from skimage import data, util, measure + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> props = measure.regionprops_table(label_image, image, + ... properties=['label', 'inertia_tensor', + ... 'inertia_tensor_eigvals']) + >>> props # doctest: +ELLIPSIS +SKIP + {'label': array([ 1, 2, ...]), ... + 'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ... + ..., + 'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])} + + The resulting dictionary can be directly passed to pandas, if installed, to + obtain a clean DataFrame: + + >>> import pandas as pd # doctest: +SKIP + >>> data = pd.DataFrame(props) # doctest: +SKIP + >>> data.head() # doctest: +SKIP + label inertia_tensor-0-0 ... inertia_tensor_eigvals-1 + 0 1 4012.909888 ... 267.065503 + 1 2 8.514739 ... 2.834806 + 2 3 0.666667 ... 0.000000 + 3 4 0.000000 ... 0.000000 + 4 5 0.222222 ... 0.111111 + + [5 rows x 7 columns] + + If we want to measure a feature that does not come as a built-in + property, we can define custom functions and pass them as + ``extra_properties``. For example, we can create a custom function + that measures the intensity quartiles in a region: + + >>> from skimage import data, util, measure + >>> import numpy as np + >>> def quartiles(regionmask, intensity): + ... return np.percentile(intensity[regionmask], q=(25, 50, 75)) + >>> + >>> image = data.coins() + >>> label_image = measure.label(image > 110, connectivity=image.ndim) + >>> props = measure.regionprops_table(label_image, intensity_image=image, + ... properties=('label',), + ... extra_properties=(quartiles,)) + >>> import pandas as pd # doctest: +SKIP + >>> pd.DataFrame(props).head() # doctest: +SKIP + label quartiles-0 quartiles-1 quartiles-2 + 0 1 117.00 123.0 130.0 + 1 2 111.25 112.0 114.0 + 2 3 111.00 111.0 111.0 + 3 4 111.00 111.5 112.5 + 4 5 112.50 113.0 114.0 + + """ + regions = regionprops( + label_image, + intensity_image=intensity_image, + cache=cache, + extra_properties=extra_properties, + spacing=spacing, + ) + if extra_properties is not None: + properties = list(properties) + [prop.__name__ for prop in extra_properties] + if len(regions) == 0: + ndim = label_image.ndim + label_image = np.zeros((3,) * ndim, dtype=int) + label_image[(1,) * ndim] = 1 + if intensity_image is not None: + intensity_image = np.zeros( + label_image.shape + intensity_image.shape[ndim:], + dtype=intensity_image.dtype, + ) + regions = regionprops( + label_image, + intensity_image=intensity_image, + cache=cache, + extra_properties=extra_properties, + spacing=spacing, + ) + + out_d = _props_to_dict(regions, properties=properties, separator=separator) + return {k: v[:0] for k, v in out_d.items()} + + return _props_to_dict(regions, properties=properties, separator=separator) + + +def regionprops( + label_image, + intensity_image=None, + cache=True, + *, + extra_properties=None, + spacing=None, + offset=None, +): + r"""Measure properties of labeled image regions. + + Region properties are evaluated on demand and come in diverse types. If + you want to do tabular data analysis of specific properties, consider + using :func:`skimage.measure.regionprops_table` instead. + + Parameters + ---------- + label_image : (M, N[, P]) ndarray + Label image. Labels with value 0 are ignored. + + .. versionchanged:: 0.14.1 + Previously, ``label_image`` was processed by ``numpy.squeeze`` and + so any number of singleton dimensions was allowed. This resulted in + inconsistent handling of images with singleton dimensions. To + recover the old behaviour, use + ``regionprops(np.squeeze(label_image), ...)``. + intensity_image : (M, N[, P][, C]) ndarray, optional + Intensity (input) image of same shape as label image, plus + optionally an extra dimension for multichannel data. Currently, + this extra channel dimension, if present, must be the last axis. + Default is None. + + .. versionchanged:: 0.18.0 + The ability to provide an extra dimension for channels was added. + cache : bool, optional + Determine whether to cache calculated properties. The computation is + much faster for cached properties, whereas the memory consumption + increases. + extra_properties : iterable of callables + Add extra property computation functions that are not included with + skimage. The name of the property is derived from the function name + and its dtype is inferred by calling the function on a small sample. + If the name of an extra property clashes with the name of an existing + property, the extra property will not be visible and a UserWarning will be + issued. A property computation function must take `label_image` as its + first argument. If the property requires an intensity image, it must + accept `intensity_image` as the second argument. + spacing : tuple of float, shape (ndim,) + The pixel spacing along each axis of the image. + offset : array-like of int, shape `(label_image.ndim,)`, optional + Coordinates of the origin ("top-left" corner) of the label image. + Normally this is ([0, ]0, 0), but it might be different if one wants + to obtain regionprops of subvolumes within a larger volume. + + Returns + ------- + properties : list of RegionProperties + Each item of the list corresponds to one labeled image region, + and can be accessed using the attributes listed below. + + Notes + ----- + The following properties can be accessed as attributes or keys: + + **area** : float + Area of the region, i.e., number of pixels of the region scaled by + pixel area (as determined by `spacing`). + **area_bbox** : float + Area of the bounding box, i.e., number of pixels of the region's + bounding box scaled by pixel area (as determined by `spacing`). + **area_convex** : float + Area of the convex hull image, which is the smallest convex + polygon that encloses the region. + **area_filled** : float + Area of the region with all the holes filled in. + **axis_major_length** : float + The length of the major axis of the ellipse that has the same + normalized second central moments as the region. + **axis_minor_length** : float + The length of the minor axis of the ellipse that has the same + normalized second central moments as the region. + **bbox** : tuple + Bounding box ``(min_row, min_col, max_row, max_col)``. + Pixels belonging to the bounding box are in the half-open interval + ``[min_row; max_row)`` and ``[min_col; max_col)``. + **centroid** : array + Centroid coordinate tuple ``(row, col)``. + **centroid_local** : array + Centroid coordinate tuple ``(row, col)``, relative to region bounding + box. + **centroid_weighted** : array + Centroid coordinate tuple ``(row, col)`` weighted with intensity + image. + **centroid_weighted_local** : array + Centroid coordinate tuple ``(row, col)``, relative to region bounding + box, weighted with intensity image. + **coords_scaled** : (K, 2) ndarray + Coordinate list ``(row, col)`` of the region scaled by `spacing`. + **coords** : (K, 2) ndarray + Coordinate list ``(row, col)`` of the region. + **eccentricity** : float + Eccentricity of the ellipse that has the same second moments as the + region. The eccentricity is the ratio of the focal distance + (distance between focal points) over the major axis length. + The value is in the interval [0, 1). + When it is 0, the ellipse becomes a circle. + **equivalent_diameter_area** : float + The diameter of a circle with the same area as the region. + **euler_number** : int + Euler characteristic of the set of non-zero pixels. + Computed as number of connected components subtracted by number of + holes (input.ndim connectivity). In 3D, number of connected + components plus number of holes subtracted by number of tunnels. + **extent** : float + Ratio of pixels in the region to pixels in the total bounding box. + Computed as ``area / (rows * cols)``. + **feret_diameter_max** : float + Maximum Feret's diameter computed as the longest distance between + points around a region's convex hull contour as determined by + ``find_contours`` [5]_. + **image** : (H, J) ndarray + Binary region image sliced by the bounding box. + **image_convex** : (H, J) ndarray + Binary convex hull image sliced by bounding box. + **image_filled** : (H, J) ndarray + Binary region image with filled holes sliced by bounding box. + **image_intensity** : (H, J) ndarray + Intensity image sliced by bounding box. + **inertia_tensor** : ndarray + Inertia tensor of the region for the rotation around its mass. + **inertia_tensor_eigvals** : tuple + The eigenvalues of the inertia tensor in decreasing order. + **intensity_max** : float + Value of greatest intensity in the region. + **intensity_mean** : float + Average of intensity values in the region. + **intensity_median** : float + Value of median intensity in the region. + **intensity_min** : float + Value of lowest intensity in the region. + **intensity_std** : float + Standard deviation of intensity values in the region. + **label** : int + The region's label in the input label image. + **moments** : (3, 3) ndarray + Spatial moments up to 3rd order:: + + m_ij = sum{ array(row, col) * row^i * col^j } + + where the sum is over the ``row, col`` coordinates of the region. + **moments_central** : (3, 3) ndarray + Central moments (translation invariant) up to 3rd order:: + + mu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } + + where the sum is over the ``row, col`` coordinates of the region, + and ``row_c`` and ``col_c`` are the coordinates of the region's centroid. + **moments_hu** : tuple + Hu moments (translation, scale and rotation invariant). + **moments_normalized** : (3, 3) ndarray + Normalized moments (translation and scale invariant) up to 3rd order:: + + nu_ij = mu_ij / m_00^[(i+j)/2 + 1] + + where ``m_00`` is the zeroth spatial moment. + **moments_weighted** : (3, 3) array + Spatial moments of intensity image up to 3rd order:: + + wm_ij = sum{ array(row, col) * row^i * col^j } + + where the sum is over the ``row, col`` coordinates of the region. + **moments_weighted_central** : (3, 3) ndarray + Central moments (translation invariant) of intensity image up to + 3rd order:: + + wmu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } + + where the sum is over the ``row, col`` coordinates of the region, + and ``row_c`` and ``col_c`` are the coordinates of the region's weighted + centroid. + **moments_weighted_hu** : tuple + Hu moments (translation, scale and rotation invariant) of intensity + image. + **moments_weighted_normalized** : (3, 3) ndarray + Normalized moments (translation and scale invariant) of intensity + image up to 3rd order:: + + wnu_ij = wmu_ij / wm_00^[(i+j)/2 + 1] + + where ``wm_00`` is the zero-th spatial moment (intensity-weighted area). + **num_pixels** : int + Number of foreground pixels. + **orientation** : float + Angle between the 0th axis (rows) and the major + axis of the ellipse that has the same second moments as the region, + ranging from :math:`-\pi/2` to :math:`\pi/2` counter-clockwise. + **perimeter** : float + Perimeter of the region which approximates the contour as a line + through the centers of border pixels using a 4-connectivity. + **perimeter_crofton** : float + Perimeter of the region approximated by the Crofton formula in 4 + directions. + **slice** : tuple of slices + A slice to extract the region from the input image. + **solidity** : float + Ratio of pixels in the region to pixels of the convex hull image. + + `properties` also supports iteration, so that you can do:: + + for region in properties: + print(region, properties[region]) + + See Also + -------- + label + + References + ---------- + .. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: + Core Algorithms. Springer-Verlag, London, 2009. + .. [2] B. Jähne. Digital Image Processing. Springer-Verlag, + Berlin-Heidelberg, 6. edition, 2005. + .. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image + Features, from Lecture notes in computer science, p. 676. Springer, + Berlin, 1993. + .. [4] https://en.wikipedia.org/wiki/Image_moment + .. [5] W. Pabst, E. Gregorová. Characterization of particles and particle + systems, pp. 27-28. ICT Prague, 2007. + https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf + + Examples + -------- + >>> import skimage as ski + >>> img = ski.util.img_as_ubyte(ski.data.coins()) > 110 + >>> label_img = ski.measure.label(img, connectivity=img.ndim) + >>> props = ski.measure.regionprops(label_img) + >>> # centroid of first labeled region + >>> props[0].centroid + (22.72987986048314, 81.91228523446583) + >>> # centroid of first labeled region + >>> props[0]['centroid'] + (22.72987986048314, 81.91228523446583) + + Add custom measurements by passing functions as ``extra_properties``: + + >>> import numpy as np + >>> import skimage as ski + >>> img = ski.util.img_as_ubyte(ski.data.coins()) > 110 + >>> label_img = ski.measure.label(img, connectivity=img.ndim) + >>> def pixelcount(regionmask): + ... return np.sum(regionmask) + >>> props = ski.measure.regionprops(label_img, extra_properties=(pixelcount,)) + >>> # pixelcount of first labeled region + >>> props[0].pixelcount + 7741 + >>> # pixelcount of first labeled region + >>> props[1]['pixelcount'] + 42 + + """ + + if label_image.ndim not in (2, 3): + raise TypeError('Only 2-D and 3-D images supported.') + + if not np.issubdtype(label_image.dtype, np.integer): + if np.issubdtype(label_image.dtype, bool): + raise TypeError( + 'Non-integer image types are ambiguous: ' + 'use skimage.measure.label to label the connected ' + 'components of label_image, ' + 'or label_image.astype(np.uint8) to interpret ' + 'the True values as a single label.' + ) + else: + raise TypeError('Non-integer label_image types are ambiguous') + + if offset is None: + offset_arr = np.zeros((label_image.ndim,), dtype=int) + else: + offset_arr = np.asarray(offset) + if offset_arr.ndim != 1 or offset_arr.size != label_image.ndim: + raise ValueError( + 'Offset should be an array-like of integers ' + 'of shape (label_image.ndim,); ' + f'{offset} was provided.' + ) + + regions = [] + + objects = ndi.find_objects(label_image) + for i, sl in enumerate(objects): + if sl is None: + continue + + label = i + 1 + + props = RegionProperties( + sl, + label, + label_image, + intensity_image, + cache, + spacing=spacing, + extra_properties=extra_properties, + offset=offset_arr, + ) + regions.append(props) + + return regions + + +def _parse_docs(): + import re + import textwrap + + doc = regionprops.__doc__ or '' + arg_regex = r'\*\*(\w+)\*\* \:.*?\n(.*?)(?=\n [\*\S]+)' + if sys.version_info >= (3, 13): + arg_regex = r'\*\*(\w+)\*\* \:.*?\n(.*?)(?=\n[\*\S]+)' + + matches = re.finditer(arg_regex, doc, flags=re.DOTALL) + prop_doc = {m.group(1): textwrap.dedent(m.group(2)) for m in matches} + + return prop_doc + + +def _install_properties_docs(): + prop_doc = _parse_docs() + + for p in [member for member in dir(RegionProperties) if not member.startswith('_')]: + getattr(RegionProperties, p).__doc__ = prop_doc[p] + + +if __debug__: + # don't install docstrings when in optimized/non-debug mode + _install_properties_docs() diff --git a/envs/kitoverlay/skimage/measure/_regionprops_utils.py b/envs/kitoverlay/skimage/measure/_regionprops_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e788e31c634e7447083ac75120f0eb9325cf53 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/_regionprops_utils.py @@ -0,0 +1,629 @@ +from math import sqrt +from numbers import Real +import numpy as np +from scipy import ndimage as ndi + + +STREL_4 = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8) +STREL_8 = np.ones((3, 3), dtype=np.uint8) + + +# Coefficients from +# Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of Discretized Sets +# - On the Choice of Adjacency in Homogeneous Lattices. +# In: Mecke K., Stoyan D. (eds) Morphology of Condensed Matter. Lecture Notes +# in Physics, vol 600. Springer, Berlin, Heidelberg. +# The value of coefficients correspond to the contributions to the Euler number +# of specific voxel configurations, which are themselves encoded thanks to a +# LUT. Computing the Euler number from the addition of the contributions of +# local configurations is possible thanks to an integral geometry formula +# (see the paper by Ohser et al. for more details). +EULER_COEFS2D_4 = [0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0] +EULER_COEFS2D_8 = [0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0] +EULER_COEFS3D_26 = np.array( + [ + 0, + 1, + 1, + 0, + 1, + 0, + -2, + -1, + 1, + -2, + 0, + -1, + 0, + -1, + -1, + 0, + 1, + 0, + -2, + -1, + -2, + -1, + -1, + -2, + -6, + -3, + -3, + -2, + -3, + -2, + 0, + -1, + 1, + -2, + 0, + -1, + -6, + -3, + -3, + -2, + -2, + -1, + -1, + -2, + -3, + 0, + -2, + -1, + 0, + -1, + -1, + 0, + -3, + -2, + 0, + -1, + -3, + 0, + -2, + -1, + 0, + 1, + 1, + 0, + 1, + -2, + -6, + -3, + 0, + -1, + -3, + -2, + -2, + -1, + -3, + 0, + -1, + -2, + -2, + -1, + 0, + -1, + -3, + -2, + -1, + 0, + 0, + -1, + -3, + 0, + 0, + 1, + -2, + -1, + 1, + 0, + -2, + -1, + -3, + 0, + -3, + 0, + 0, + 1, + -1, + 4, + 0, + 3, + 0, + 3, + 1, + 2, + -1, + -2, + -2, + -1, + -2, + -1, + 1, + 0, + 0, + 3, + 1, + 2, + 1, + 2, + 2, + 1, + 1, + -6, + -2, + -3, + -2, + -3, + -1, + 0, + 0, + -3, + -1, + -2, + -1, + -2, + -2, + -1, + -2, + -3, + -1, + 0, + -1, + 0, + 4, + 3, + -3, + 0, + 0, + 1, + 0, + 1, + 3, + 2, + 0, + -3, + -1, + -2, + -3, + 0, + 0, + 1, + -1, + 0, + 0, + -1, + -2, + 1, + -1, + 0, + -1, + -2, + -2, + -1, + 0, + 1, + 3, + 2, + -2, + 1, + -1, + 0, + 1, + 2, + 2, + 1, + 0, + -3, + -3, + 0, + -1, + -2, + 0, + 1, + -1, + 0, + -2, + 1, + 0, + -1, + -1, + 0, + -1, + -2, + 0, + 1, + -2, + -1, + 3, + 2, + -2, + 1, + 1, + 2, + -1, + 0, + 2, + 1, + -1, + 0, + -2, + 1, + -2, + 1, + 1, + 2, + -2, + 3, + -1, + 2, + -1, + 2, + 0, + 1, + 0, + -1, + -1, + 0, + -1, + 0, + 2, + 1, + -1, + 2, + 0, + 1, + 0, + 1, + 1, + 0, + ] +) + + +def euler_number(image, connectivity=None): + """Calculate the Euler characteristic in binary image. + + For 2D objects, the Euler number is the number of objects minus the number + of holes. For 3D objects, the Euler number is obtained as the number of + objects plus the number of holes, minus the number of tunnels, or loops. + + Parameters + ---------- + image : (M, N[, P]) ndarray + Input image. If image is not binary, all values greater than zero + are considered as the object. + connectivity : int, optional + Maximum number of orthogonal hops to consider a pixel/voxel + as a neighbor. + Accepted values are ranging from 1 to input.ndim. If ``None``, a full + connectivity of ``input.ndim`` is used. + 4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2, + respectively). + 6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3, + respectively). Connectivity 2 is not defined. + + Returns + ------- + euler_number : int + Euler characteristic of the set of all objects in the image. + + Notes + ----- + The Euler characteristic is an integer number that describes the + topology of the set of all objects in the input image. If object is + 4-connected, then background is 8-connected, and conversely. + + The computation of the Euler characteristic is based on an integral + geometry formula in discretized space. In practice, a neighborhood + configuration is constructed, and a LUT is applied for each + configuration. The coefficients used are the ones of Ohser et al. + + It can be useful to compute the Euler characteristic for several + connectivities. A large relative difference between results + for different connectivities suggests that the image resolution + (with respect to the size of objects and holes) is too low. + + References + ---------- + .. [1] S. Rivollier. Analyse d’image geometrique et morphometrique par + diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, + 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. + https://tel.archives-ouvertes.fr/tel-00560838 + .. [2] Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of + Discretized Sets - On the Choice of Adjacency in Homogeneous + Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed + Matter. Lecture Notes in Physics, vol 600. Springer, Berlin, + Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + >>> SAMPLE = np.zeros((100,100,100)); + >>> SAMPLE[40:60, 40:60, 40:60]=1 + >>> ski.measure.euler_number(SAMPLE) # doctest: +ELLIPSIS + 1... + >>> SAMPLE[45:55,45:55,45:55] = 0; + >>> ski.measure.euler_number(SAMPLE) # doctest: +ELLIPSIS + 2... + >>> SAMPLE = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], + ... [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0], + ... [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], + ... [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]) + >>> ski.measure.euler_number(SAMPLE) + 0 + >>> ski.measure.euler_number(SAMPLE, connectivity=1) + 2 + """ + + # as image can be a label image, transform it to binary + image = (image > 0).astype(int) + image = np.pad(image, pad_width=1, mode='constant') + + # check connectivity + if connectivity is None: + connectivity = image.ndim + + # config variable is an adjacency configuration. A coefficient given by + # variable coefs is attributed to each configuration in order to get + # the Euler characteristic. + if image.ndim == 2: + config = np.array([[0, 0, 0], [0, 1, 4], [0, 2, 8]]) + if connectivity == 1: + coefs = EULER_COEFS2D_4 + else: + coefs = EULER_COEFS2D_8 + bins = 16 + else: # 3D images + if connectivity == 2: + raise NotImplementedError( + 'For 3D images, Euler number is implemented ' + 'for connectivities 1 and 3 only' + ) + + config = np.array( + [ + [[0, 0, 0], [0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 1, 4], [0, 2, 8]], + [[0, 0, 0], [0, 16, 64], [0, 32, 128]], + ] + ) + if connectivity == 1: + coefs = EULER_COEFS3D_26[::-1] + else: + coefs = EULER_COEFS3D_26 + bins = 256 + + # XF has values in the 0-255 range in 3D, and in the 0-15 range in 2D, + # with one unique value for each binary configuration of the + # 27-voxel cube in 3D / 8-pixel square in 2D, up to symmetries + XF = ndi.convolve(image, config, mode='constant', cval=0) + h = np.bincount(XF.ravel(), minlength=bins) + + if image.ndim == 2: + return coefs @ h + else: + return int(0.125 * coefs @ h) + + +def perimeter(image, neighborhood=4): + """Calculate total perimeter of all objects in binary image. + + Parameters + ---------- + image : (M, N) ndarray + Binary input image. + neighborhood : 4 or 8, optional + Neighborhood connectivity for border pixel determination. It is used to + compute the contour. A higher neighborhood widens the border on which + the perimeter is computed. + + Returns + ------- + perimeter : float + Total perimeter of all objects in binary image. + + References + ---------- + .. [1] K. Benkrid, D. Crookes. Design and FPGA Implementation of + a Perimeter Estimator. The Queen's University of Belfast. + http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc + + Examples + -------- + >>> import skimage as ski + >>> # coins image (binary) + >>> img_coins = ski.data.coins() > 110 + >>> # total perimeter of all objects in the image + >>> ski.measure.perimeter(img_coins, neighborhood=4) # doctest: +ELLIPSIS + 7796.867... + >>> ski.measure.perimeter(img_coins, neighborhood=8) # doctest: +ELLIPSIS + 8806.268... + + """ + if image.ndim != 2: + raise NotImplementedError('`perimeter` supports 2D images only') + + if neighborhood == 4: + strel = STREL_4 + else: + strel = STREL_8 + image = image.astype(np.uint8) + eroded_image = ndi.binary_erosion(image, strel, border_value=0) + border_image = image - eroded_image + + perimeter_weights = np.zeros(50, dtype=np.float64) + perimeter_weights[[5, 7, 15, 17, 25, 27]] = 1 + perimeter_weights[[21, 33]] = sqrt(2) + perimeter_weights[[13, 23]] = (1 + sqrt(2)) / 2 + + perimeter_image = ndi.convolve( + border_image, + np.array([[10, 2, 10], [2, 1, 2], [10, 2, 10]]), + mode='constant', + cval=0, + ) + + # You can also write + # return perimeter_weights[perimeter_image].sum() + # but that was measured as taking much longer than bincount + np.dot (5x + # as much time) + perimeter_histogram = np.bincount(perimeter_image.ravel(), minlength=50) + total_perimeter = perimeter_histogram @ perimeter_weights + return total_perimeter + + +def perimeter_crofton(image, directions=4): + """Calculate total Crofton perimeter of all objects in binary image. + + Parameters + ---------- + image : (M, N) ndarray + Input image. If image is not binary, all values greater than zero + are considered as the object. + directions : 2 or 4, optional + Number of directions used to approximate the Crofton perimeter. By + default, 4 is used: it should be more accurate than 2. + Computation time is the same in both cases. + + Returns + ------- + perimeter : float + Total perimeter of all objects in binary image. + + Notes + ----- + This measure is based on Crofton formula [1], which is a measure from + integral geometry. It is defined for general curve length evaluation via + a double integral along all directions. In a discrete + space, 2 or 4 directions give a quite good approximation, 4 being more + accurate than 2 for more complex shapes. + + Similar to :func:`~.measure.perimeter`, this function returns an + approximation of the perimeter in continuous space. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Crofton_formula + .. [2] S. Rivollier. Analyse d’image geometrique et morphometrique par + diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, + 2010. + Ecole Nationale Superieure des Mines de Saint-Etienne. + https://tel.archives-ouvertes.fr/tel-00560838 + + Examples + -------- + >>> import skimage as ski + >>> # coins image (binary) + >>> img_coins = ski.data.coins() > 110 + >>> # total perimeter of all objects in the image + >>> ski.measure.perimeter_crofton(img_coins, directions=2) # doctest: +ELLIPSIS + 8144.578... + >>> ski.measure.perimeter_crofton(img_coins, directions=4) # doctest: +ELLIPSIS + 7837.077... + """ + if image.ndim != 2: + raise NotImplementedError('`perimeter_crofton` supports 2D images only') + + # as image could be a label image, transform it to binary image + image = (image > 0).astype(np.uint8) + image = np.pad(image, pad_width=1, mode='constant') + XF = ndi.convolve( + image, np.array([[0, 0, 0], [0, 1, 4], [0, 2, 8]]), mode='constant', cval=0 + ) + + h = np.bincount(XF.ravel(), minlength=16) + + # definition of the LUT + if directions == 2: + coefs = [ + 0, + np.pi / 2, + 0, + 0, + 0, + np.pi / 2, + 0, + 0, + np.pi / 2, + np.pi, + 0, + 0, + np.pi / 2, + np.pi, + 0, + 0, + ] + else: + coefs = [ + 0, + np.pi / 4 * (1 + 1 / (np.sqrt(2))), + np.pi / (4 * np.sqrt(2)), + np.pi / (2 * np.sqrt(2)), + 0, + np.pi / 4 * (1 + 1 / (np.sqrt(2))), + 0, + np.pi / (4 * np.sqrt(2)), + np.pi / 4, + np.pi / 2, + np.pi / (4 * np.sqrt(2)), + np.pi / (4 * np.sqrt(2)), + np.pi / 4, + np.pi / 2, + 0, + 0, + ] + + total_perimeter = coefs @ h + return total_perimeter + + +def _normalize_spacing(spacing, ndims): + """Normalize spacing parameter. + + The `spacing` parameter should be a sequence of numbers matching + the image dimensions. If `spacing` is a scalar, assume equal + spacing along all dimensions. + + Parameters + ---------- + spacing : Any + User-provided `spacing` keyword. + ndims : int + Number of image dimensions. + + Returns + ------- + spacing : array + Corrected spacing. + + Raises + ------ + ValueError + If `spacing` is invalid. + + """ + spacing = np.array(spacing) + if spacing.shape == (): + spacing = np.broadcast_to(spacing, shape=(ndims,)) + elif spacing.shape != (ndims,): + raise ValueError( + f"spacing isn't a scalar nor a sequence of shape {(ndims,)}, got {spacing}." + ) + if not all(isinstance(s, Real) for s in spacing): + raise TypeError( + f"Element of spacing isn't float or integer type, got {spacing}." + ) + if not all(np.isfinite(spacing)): + raise ValueError( + f"Invalid spacing parameter. All elements must be finite, got {spacing}." + ) + return spacing diff --git a/envs/kitoverlay/skimage/measure/block.py b/envs/kitoverlay/skimage/measure/block.py new file mode 100644 index 0000000000000000000000000000000000000000..a256c077b26518609b2652ff0ff973515a191331 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/block.py @@ -0,0 +1,94 @@ +import numpy as np +from ..util import view_as_blocks + + +def block_reduce(image, block_size=2, func=np.sum, cval=0, func_kwargs=None): + """Downsample image by applying function `func` to local blocks. + + This function is useful for max and mean pooling, for example. + + Parameters + ---------- + image : (M[, ...]) ndarray + N-dimensional input image. + block_size : array_like or int + Array containing down-sampling integer factor along each axis. + Default block_size is 2. + func : callable + Function object which is used to calculate the return value for each + local block. This function must implement an ``axis`` parameter. + Primary functions are ``numpy.sum``, ``numpy.min``, ``numpy.max``, + ``numpy.mean`` and ``numpy.median``. See also `func_kwargs`. + cval : float + Constant padding value if image is not perfectly divisible by the + block size. + func_kwargs : dict + Keyword arguments passed to `func`. Notably useful for passing dtype + argument to ``np.mean``. Takes dictionary of inputs, e.g.: + ``func_kwargs={'dtype': np.float16})``. + + Returns + ------- + image : ndarray + Down-sampled image with same number of dimensions as input image. + + Examples + -------- + >>> from skimage.measure import block_reduce + >>> image = np.arange(3*3*4).reshape(3, 3, 4) + >>> image # doctest: +NORMALIZE_WHITESPACE + 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]]]) + >>> block_reduce(image, block_size=(3, 3, 1), func=np.mean) + array([[[16., 17., 18., 19.]]]) + >>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=np.max) + >>> image_max1 # doctest: +NORMALIZE_WHITESPACE + array([[[11]], + [[23]], + [[35]]]) + >>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max) + >>> image_max2 # doctest: +NORMALIZE_WHITESPACE + array([[[27], + [31], + [35]]]) + """ + + if np.isscalar(block_size): + block_size = (block_size,) * image.ndim + elif len(block_size) != image.ndim: + raise ValueError( + "`block_size` must be a scalar or have " "the same length as `image.shape`" + ) + + if func_kwargs is None: + func_kwargs = {} + + pad_width = [] + for i in range(len(block_size)): + if block_size[i] < 1: + raise ValueError( + "Down-sampling factors must be >= 1. Use " + "`skimage.transform.resize` to up-sample an " + "image." + ) + if image.shape[i] % block_size[i] != 0: + after_width = block_size[i] - (image.shape[i] % block_size[i]) + else: + after_width = 0 + pad_width.append((0, after_width)) + + if np.any(np.asarray(pad_width)): + image = np.pad( + image, pad_width=pad_width, mode='constant', constant_values=cval + ) + + blocked = view_as_blocks(image, block_size) + + return func(blocked, axis=tuple(range(image.ndim, blocked.ndim)), **func_kwargs) diff --git a/envs/kitoverlay/skimage/measure/entropy.py b/envs/kitoverlay/skimage/measure/entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..51c6bcc0706e25b710cdb15e4027a4061f1700d3 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/entropy.py @@ -0,0 +1,41 @@ +from numpy import unique +from scipy.stats import entropy as scipy_entropy + + +def shannon_entropy(image, base=2): + """Calculate the Shannon entropy of an image. + + The Shannon entropy is defined as S = -sum(pk * log(pk)), + where pk are frequency/probability of pixels of value k. + + Parameters + ---------- + image : (M, N) ndarray + Grayscale input image. + base : float, optional + The logarithmic base to use. + + Returns + ------- + entropy : float + + Notes + ----- + The returned value is measured in bits or shannon (Sh) for base=2, natural + unit (nat) for base=np.e and hartley (Hart) for base=10. + + References + ---------- + .. [1] `https://en.wikipedia.org/wiki/Entropy_(information_theory) `_ + .. [2] https://en.wiktionary.org/wiki/Shannon_entropy + + Examples + -------- + >>> from skimage import data + >>> from skimage.measure import shannon_entropy + >>> shannon_entropy(data.camera()) + 7.231695011055706 + """ + + _, counts = unique(image, return_counts=True) + return scipy_entropy(counts, base=base) diff --git a/envs/kitoverlay/skimage/measure/fit.py b/envs/kitoverlay/skimage/measure/fit.py new file mode 100644 index 0000000000000000000000000000000000000000..61a069ff7b17aa7b62b0ea6dd5df99b31cf8d0bd --- /dev/null +++ b/envs/kitoverlay/skimage/measure/fit.py @@ -0,0 +1,1493 @@ +import inspect +import math +from typing import Protocol, runtime_checkable, Self +from warnings import warn, catch_warnings + +import numpy as np +from numpy.linalg import inv +from scipy import optimize, spatial + +from .._shared.utils import ( + _deprecate_estimate, + FailedEstimation, + deprecate_parameter, + deprecate_func, + DEPRECATED, +) + +_EPSILON = np.spacing(1) + + +def _check_data_dim(data, dim): + if data.ndim != 2 or data.shape[1] != dim: + raise ValueError(f"Input data must have shape (N, {dim}).") + + +def _check_data_atleast_2D(data): + if data.ndim < 2 or data.shape[1] < 2: + raise ValueError('Input data must be at least 2D.') + + +@runtime_checkable +class RansacModelProtocol(Protocol): + """Protocol for `ransac` model class.""" + + @classmethod + def from_estimate(cls, *data): ... + + def residuals(self, *data): ... + + +_PARAMS_DEP_START = '0.26' +_PARAMS_DEP_STOP = '2.2' + + +class BaseModel: + def __init_subclass__(self): + warn( + f'`BaseModel` deprecated since version {_PARAMS_DEP_START} and ' + f'will be removed in version {_PARAMS_DEP_STOP}', + category=FutureWarning, + stacklevel=2, + ) + + +class _BaseModel: + """Implement common methods for model classes. + + This class can be removed when we expire deprecations of ``estimate`` + method, and `params` arguments to ``predict*`` methods. + + Note that each inheriting class will need to implement + ``_params2init_values``, that breaks up the ``params`` vector into separate + components comprising the arguments to the function ``__init__``, and + checks the resulting input arguments for validity. + """ + + @classmethod + def from_estimate(cls, data) -> Self | FailedEstimation: + # In order to defer to the ``_estimate`` method, we first need to + # create an empty not-initialized instance, that we can override by + # executing the ``_estimate`` method. This relies on the assumption + # that `_estimate` can work with an uninitialized instance. This + # assumption only need hold until we can expire the deprecation of the + # `estimate` method, at which point we can move the estimation logic + # from the ``_estimate`` methods, to the respective ``from_estimate`` + # class methods. + with catch_warnings(action='ignore'): + tf = cls() + msg = tf._estimate(data, warn_only=False) + return tf if msg is None else FailedEstimation(f'{cls.__name__}: {msg}') + + def _get_init_values(self, params): + if params is None or params is DEPRECATED: + if getattr(self, self._init_args[0]) is None: + # Until the deprecation of no-argument initialization expires, + # it is easy to create a not-initialized model, evidenced by + # None values of the init attributes. + cls_name = type(self).__name__ + raise ValueError( + '`params` argument must be specified when ' + 'applied to model initialized with ' + f'``{cls_name}()``; Consider creating new ' + f'{cls_name} with suitable input arguments, ' + f'or by using ``{cls_name}.from_estimate``.' + ) + return [getattr(self, a) for a in self._init_args] + return self._params2init_values(params) + + +def _warn_or_msg(msg, warn_only=True): + """If `warn_only`, warn with `msg`, return ``None``, else return `msg` + + For `from_estimate` API, we want to return a ``FailedEstimation`` for these + estimation failures, which we do by setting ``warn_only=False``, and + passing back the `msg` from the ``_estimation`` method via this function. + For the deprecated ``estimate`` API, we want to warn (``warn_only=True``), + and return an incomplete transform. The ``None`` return value indicates + the estimation has kind-of succeeded, for back compatibility. + """ + if not warn_only: + return msg + warn(msg, category=RuntimeWarning, stacklevel=5) + return None + + +def _deprecate_no_args(cls): + """Class decorator to allow, deprecate no input arguments to ``__init__``. + + Makes a new ``__init__`` method, that a) will allow option of passing no + arguments, and b) when used thus, raises a deprecation warning. Otherwise + defers to an assumed-existing ``_args_init`` instance method to deal with + input arguments. If there are no parameters, set desired parameters to + None, to signal uninitialized object. + + At the end of deprecation we can drop this decorator, and rename + ``_args_init`` to ``__init__``. + """ + + args_init_sig = inspect.signature(cls._args_init) + cls._init_args = [k for k in args_init_sig.parameters if k != 'self'] + + def init(self, *args, **kwargs): + if len(args) or len(kwargs): + self._args_init(*args, **kwargs) + return + warn( + f'Calling ``{cls.__name__}()`` (without arguments) has been ' + f'deprecated since version {_PARAMS_DEP_START} and will be ' + f'removed in version {_PARAMS_DEP_STOP}; see help for ' + f'``{cls.__name__}``.', + category=FutureWarning, + stacklevel=2, + ) + # Blank initialization. + for k in cls._init_args: + setattr(self, k, None) + + init.__signature__ = args_init_sig + cls.__init__ = init + return cls + + +def _deprecate_model_params(func): + """Deprecate `params` argument of various model methods.""" + func = deprecate_parameter( + 'params', + start_version=_PARAMS_DEP_START, + stop_version=_PARAMS_DEP_STOP, + modify_docstring=False, + )(func) + func.__doc__ = func.__doc__.replace('{{ start_version }}', _PARAMS_DEP_START) + return func + + +@_deprecate_no_args +class LineModelND(_BaseModel): + """Total least squares estimator for N-dimensional lines. + + In contrast to ordinary least squares line estimation, this estimator + minimizes the orthogonal distances of points to the estimated line. + + Lines are defined by a point (origin) and a unit vector (direction) + according to the following vector equation:: + + X = origin + lambda * direction + + Parameters + ---------- + origin : array-like, shape (N,) + Coordinates of line origin in N dimensions. + direction : array-like, shape (N,) + Vector giving line direction. + + Raises + ------ + ValueError + If length of `origin` and `direction` differ. + + Examples + -------- + >>> x = np.linspace(1, 2, 25) + >>> y = 1.5 * x + 3 + >>> lm = LineModelND.from_estimate(np.stack([x, y], axis=-1)) + >>> lm.origin + array([1.5 , 5.25]) + >>> lm.direction # doctest: +FLOAT_CMP + array([0.5547 , 0.83205]) + >>> res = lm.residuals(np.stack([x, y], axis=-1)) + >>> np.abs(np.round(res, 9)) + array([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.]) + >>> np.round(lm.predict_y(x[:5]), 3) + array([4.5 , 4.562, 4.625, 4.688, 4.75 ]) + >>> np.round(lm.predict_x(y[:5]), 3) + array([1. , 1.042, 1.083, 1.125, 1.167]) + + """ + + def _args_init(self, origin, direction): + """Initialize ``LineModelND`` instance. + + Parameters + ---------- + origin : array-like, shape (N,) + Coordinates of line origin in N dimensions. + direction : array-like, shape (N,) + Vector giving line direction. + """ + self.origin, self.direction = self._check_init_values(origin, direction) + + def _check_init_values(self, origin, direction): + origin, direction = (np.array(v) for v in (origin, direction)) + if len(origin) != len(direction): + raise ValueError('Direction vector should be same length as origin point.') + return origin, direction + + def _params2init_values(self, params): + if len(params) != 2: + raise ValueError('Input `params` should be length 2') + return self._check_init_values(*params) + + @property + @deprecate_func( + deprecated_version=_PARAMS_DEP_START, + removed_version=_PARAMS_DEP_STOP, + hint='`params` attribute deprecated; use ``origin, direction`` attributes instead', + ) + def params(self): + """Return model attributes as ``origin, direction`` tuple.""" + return self.origin, self.direction + + @classmethod + def from_estimate(cls, data): + """Estimate line model from data. + + This minimizes the sum of shortest (orthogonal) distances + from the given data points to the estimated line. + + Parameters + ---------- + data : (N, dim) array + N points in a space of dimensionality dim >= 2. + + Returns + ------- + model : Self or `~.FailedEstimation` + An instance of the line model 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 + + model = LineModelND.from_estimate(...) + if not model: + raise RuntimeError(f"Failed estimation: {model}") + """ + return super().from_estimate(data) + + def _estimate(self, data, warn_only=True): + _check_data_atleast_2D(data) + + origin = data.mean(axis=0) + data = data - origin + + if data.shape[0] == 2: # well determined + direction = data[1] - data[0] + norm = np.linalg.norm(direction) + if norm != 0: # this should not happen to be norm 0 + direction /= norm + elif data.shape[0] > 2: # over-determined + # Note: with full_matrices=1 Python dies with joblib parallel_for. + _, _, v = np.linalg.svd(data, full_matrices=False) + direction = v[0] + else: # under-determined + return 'estimate under-determined' + + self.origin = origin + self.direction = direction + return None + + @_deprecate_model_params + def residuals(self, data, params=DEPRECATED): + """Determine residuals of data to model. + + For each point, the shortest (orthogonal) distance to the line is + returned. It is obtained by projecting the data onto the line. + + Parameters + ---------- + data : (N, dim) array + N points in a space of dimension dim. + + Returns + ------- + residuals : (N,) array + Residual for each data point. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional custom parameter set in the form (`origin`, `direction`). + + .. deprecated:: {{ start_version }} + """ + _check_data_atleast_2D(data) + origin, direction = self._get_init_values(params) + if len(origin) != data.shape[1]: + raise ValueError( + f'`origin` is {len(origin)}D, but `data` is {data.shape[1]}D' + ) + res = (data - origin) - ((data - origin) @ direction)[ + ..., np.newaxis + ] * direction + return np.linalg.norm(res, axis=1) + + @_deprecate_model_params + def predict(self, x, axis=0, params=DEPRECATED): + """Predict intersection of line model with orthogonal hyperplane. + + Parameters + ---------- + x : (n, 1) array + Coordinates along an axis. + axis : int + Axis orthogonal to the hyperplane intersecting the line. + + Returns + ------- + data : (n, m) array + Predicted coordinates. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional custom parameter set in the form (`origin`, `direction`). + + .. deprecated:: {{ start_version }} + + Raises + ------ + ValueError + If the line is parallel to the given axis. + """ + origin, direction = self._get_init_values(params) + if direction[axis] == 0: + # line parallel to axis + raise ValueError(f'Line parallel to axis {axis}') + + l = (x - origin[axis]) / direction[axis] + data = origin + l[..., np.newaxis] * direction + return data + + @_deprecate_model_params + def predict_x(self, y, params=DEPRECATED): + """Predict x-coordinates for 2D lines using the estimated model. + + Alias for:: + + predict(y, axis=1)[:, 0] + + Parameters + ---------- + y : array + y-coordinates. + + Returns + ------- + x : array + Predicted x-coordinates. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional custom parameter set in the form (`origin`, `direction`). + + .. deprecated:: {{ start_version }} + + """ + # Avoid triggering deprecationwarning in predict. + tf = ( + self + if (params is None or params is DEPRECATED) + else type(self)(*self._params2init_values(params)) + ) + x = tf.predict(y, axis=1)[:, 0] + return x + + @_deprecate_model_params + def predict_y(self, x, params=DEPRECATED): + """Predict y-coordinates for 2D lines using the estimated model. + + Alias for:: + + predict(x, axis=0)[:, 1] + + Parameters + ---------- + x : array + x-coordinates. + + Returns + ------- + y : array + Predicted y-coordinates. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional custom parameter set in the form (`origin`, `direction`). + + .. deprecated:: {{ start_version }} + + """ + # Avoid triggering deprecationwarning in predict. + tf = ( + self + if (params is None or params is DEPRECATED) + else type(self)(*self._params2init_values(params)) + ) + y = tf.predict(x, axis=0)[:, 1] + return y + + @_deprecate_estimate + def estimate(self, data): + """Estimate line model from data. + + This minimizes the sum of shortest (orthogonal) distances + from the given data points to the estimated line. + + Parameters + ---------- + data : (N, dim) array + N points in a space of dimensionality ``dim >= 2``. + + Returns + ------- + success : bool + True, if model estimation succeeds. + """ + return self._estimate(data) is None + + +@_deprecate_no_args +class CircleModel(_BaseModel): + """Total least squares estimator for 2D circles. + + The functional model of the circle is:: + + r**2 = (x - xc)**2 + (y - yc)**2 + + This estimator minimizes the squared distances from all points to the + circle:: + + min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } + + A minimum number of 3 points is required to solve for the parameters. + + Parameters + ---------- + center : array-like, shape (2,) + Coordinates of circle center. + radius : float + Circle radius. + + Notes + ----- + The estimation is carried out using a 2D version of the spherical + estimation given in [1]_. + + References + ---------- + .. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models + for pvc-coated polyester via inverse bubble inflation. + Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87. + https://hdl.handle.net/10019.1/98627 + + Raises + ------ + ValueError + If `center` does not have length 2. + + Examples + -------- + >>> t = np.linspace(0, 2 * np.pi, 25) + >>> xy = CircleModel((2, 3), 4).predict_xy(t) + >>> model = CircleModel.from_estimate(xy) + >>> model.center + array([2., 3.]) + >>> model.radius + 4.0 + >>> res = model.residuals(xy) + >>> np.abs(np.round(res, 9)) + array([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.]) + + The estimation can fail when — for example — 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: + >>> if model: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate model with identical points. + >>> bad_data = np.ones((4, 2)) + >>> bad_model = CircleModel.from_estimate(bad_data) + >>> if not bad_model: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_model.residuals(xy) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "residuals" for failed estimation ... + """ + + def _args_init(self, center, radius): + """Initialize CircleModel instance. + + Parameters + ---------- + center : array-like, shape (2,) + Coordinates of circle center. + radius : float + Circle radius. + """ + self.center, self.radius = self._check_init_values(center, radius) + + def _check_init_values(self, center, radius): + center = np.array(center) + if not len(center) == 2: + raise ValueError('Center coordinates should be length 2') + return center, radius + + def _params2init_values(self, params): + params = np.array(params) + if len(params) != 3: + raise ValueError('Input `params` should be length 3') + return self._check_init_values(params[:2], params[2]) + + @property + @deprecate_func( + deprecated_version=_PARAMS_DEP_START, + removed_version=_PARAMS_DEP_STOP, + hint='`params` attribute deprecated; use `center, radius` attributes instead', + ) + def params(self): + """Return model attributes ``center, radius`` as 1D array.""" + return np.r_[self.center, self.radius] + + @classmethod + def from_estimate(cls, data): + """Estimate circle model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + model : Self or `~.FailedEstimation` + An instance of the circle model 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 + + model = CircleModel.from_estimate(...) + if not model: + raise RuntimeError(f"Failed estimation: {model}") + """ + return super().from_estimate(data) + + def _estimate(self, data, warn_only=True): + _check_data_dim(data, dim=2) + + # to prevent integer overflow, cast data to float, if it isn't already + float_type = np.promote_types(data.dtype, np.float32) + data = data.astype(float_type, copy=False) + # normalize value range to avoid misfitting due to numeric errors if + # the relative distanceses are small compared to absolute distances + origin = data.mean(axis=0) + data = data - origin + scale = data.std() + if scale < np.finfo(float_type).tiny: + return _warn_or_msg( + "Standard deviation of data is too small to estimate " + "circle with meaningful precision.", + warn_only=warn_only, + ) + + data /= scale + + # Adapted from a spherical estimator covered in a blog post by Charles + # Jeckel (see also reference 1 above): + # https://jekel.me/2015/Least-Squares-Sphere-Fit/ + A = np.append(data * 2, np.ones((data.shape[0], 1), dtype=float_type), axis=1) + f = np.sum(data**2, axis=1) + C, _, rank, _ = np.linalg.lstsq(A, f, rcond=None) + + if rank != 3: + return _warn_or_msg( + "Input does not contain enough significant data points.", + warn_only=warn_only, + ) + + center = C[0:2] + distances = spatial.minkowski_distance(center, data) + r = np.sqrt(np.mean(distances**2)) + + # Revert normalization and set init params. + self.center = center * scale + origin + self.radius = r * scale + return None + + def residuals(self, data): + """Determine residuals of data to model. + + For each point the shortest distance to the circle is returned. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + residuals : (N,) array + Residual for each data point. + + """ + + _check_data_dim(data, dim=2) + + xc, yc = self.center + r = self.radius + + x = data[:, 0] + y = data[:, 1] + + return r - np.sqrt((x - xc) ** 2 + (y - yc) ** 2) + + @_deprecate_model_params + def predict_xy(self, t, params=DEPRECATED): + """Predict x- and y-coordinates using the estimated model. + + Parameters + ---------- + t : array-like + Angles in circle in radians. Angles start to count from positive + x-axis to positive y-axis in a right-handed system. + + Returns + ------- + xy : (..., 2) array + Predicted x- and y-coordinates. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional parameters ``xc``, ``yc``, `radius`. + + .. deprecated:: {{ start_version }} + """ + t = np.asanyarray(t) + (xc, yc), r = self._get_init_values(params) + + x = xc + r * np.cos(t) + y = yc + r * np.sin(t) + + return np.concatenate((x[..., None], y[..., None]), axis=t.ndim) + + @_deprecate_estimate + def estimate(self, data): + """Estimate circle model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + """ + return self._estimate(data) is None + + +@_deprecate_no_args +class EllipseModel(_BaseModel): + """Total least squares estimator for 2D ellipses. + + The functional model of the ellipse is:: + + xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t) + yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t) + d = sqrt((x - xt)**2 + (y - yt)**2) + + where ``(xt, yt)`` is the closest point on the ellipse to ``(x, y)``. Thus + d is the shortest distance from the point to the ellipse. + + The estimator is based on a least squares minimization. The optimal + solution is computed directly, no iterations are required. This leads + to a simple, stable and robust fitting method. + + Parameters + ---------- + center : array-like, shape (2,) + Coordinates of ellipse center. + axis_lengths : array-like, shape (2,) + Length of first axis and length of second axis. Call these ``a`` and + ``b``. + theta : float + Angle of first axis. + + Raises + ------ + ValueError + If `center` does not have length 2. + + Examples + -------- + + >>> em = EllipseModel((10, 15), (8, 4), np.deg2rad(30)) + >>> xy = em.predict_xy(np.linspace(0, 2 * np.pi, 25)) + >>> ellipse = EllipseModel.from_estimate(xy) + >>> ellipse.center + array([10., 15.]) + >>> ellipse.axis_lengths + array([8., 4.]) + >>> round(ellipse.theta, 2) + 0.52 + >>> np.round(abs(ellipse.residuals(xy)), 5) + array([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.]) + + The estimation can fail when — for example — all the input or output + points are the same. If this happens, you will get an ellipse model for + which ``bool(model)`` is ``False``: + + >>> # A successfully estimated model is truthy: + >>> if ellipse: + ... print("Estimation succeeded.") + Estimation succeeded. + >>> # Not so for a degenerate model with identical points. + >>> bad_data = np.ones((4, 2)) + >>> bad_ellipse = EllipseModel.from_estimate(bad_data) + >>> if not bad_ellipse: + ... print("Estimation failed.") + Estimation failed. + + Trying to use this failed estimation transform result will give a suitable + error: + + >>> bad_ellipse.residuals(xy) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + FailedEstimationAccessError: No attribute "residuals" for failed estimation ... + """ + + def _args_init(self, center, axis_lengths, theta): + """Initialize ``EllipseModel`` instance. + + Parameters + ---------- + center : array-like, shape (2,) + Coordinates of ellipse center. + axis_lengths : array-like, shape (2,) + Length of first axis and length of second axis. Call these ``a`` + and ``b``. + theta : float + Angle of first axis. + """ + self.center, self.axis_lengths, self.theta = self._check_init_values( + center, axis_lengths, theta + ) + + def _check_init_values(self, center, axis_lengths, theta): + center, axis_lengths = [np.array(v) for v in (center, axis_lengths)] + if not len(center) == 2: + raise ValueError('Center coordinates should be length 2') + if not len(axis_lengths) == 2: + raise ValueError('Axis lengths should be length 2') + return center, axis_lengths, theta + + def _params2init_values(self, params): + params = np.array(params) + if len(params) != 5: + raise ValueError('Input `params` should be length 5') + return self._check_init_values(params[:2], params[2:4], params[4]) + + @property + @deprecate_func( + deprecated_version=_PARAMS_DEP_START, + removed_version=_PARAMS_DEP_STOP, + hint='`params` attribute deprecated; use `center, axis_lengths, theta` attributes instead', + ) + def params(self): + """Return model attributes ``center, axis_lengths, theta`` as 1D array.""" + return np.r_[self.center, self.axis_lengths, self.theta] + + @classmethod + def from_estimate(cls, data): + """Estimate ellipse model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + model : Self or `~.FailedEstimation` + An instance of the ellipse model 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 + + model = EllipseModel.from_estimate(...) + if not model: + raise RuntimeError(f"Failed estimation: {model}") + + References + ---------- + .. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares + fitting of ellipses". In Proc. 6th International Conference in + Central Europe on Computer Graphics and Visualization. + WSCG (Vol. 98, pp. 125-132). + + """ + return super().from_estimate(data) + + def _estimate(self, data, warn_only=True): + # Original Implementation: Ben Hammel, Nick Sullivan-Molina + # another REFERENCE: [2] http://mathworld.wolfram.com/Ellipse.html + _check_data_dim(data, dim=2) + + if len(data) < 5: + return _warn_or_msg( + "Need at least 5 data points to estimate an ellipse.", + warn_only=warn_only, + ) + + # to prevent integer overflow, cast data to float, if it isn't already + float_type = np.promote_types(data.dtype, np.float32) + data = data.astype(float_type, copy=False) + + # normalize value range to avoid misfitting due to numeric errors if + # the relative distances are small compared to absolute distances + origin = data.mean(axis=0) + data = data - origin + scale = data.std() + if scale < np.finfo(float_type).tiny: + return _warn_or_msg( + "Standard deviation of data is too small to estimate " + "ellipse with meaningful precision.", + warn_only=warn_only, + ) + data /= scale + + x = data[:, 0] + y = data[:, 1] + + # Quadratic part of design matrix [eqn. 15] from [1] + D1 = np.vstack([x**2, x * y, y**2]).T + # Linear part of design matrix [eqn. 16] from [1] + D2 = np.vstack([x, y, np.ones_like(x)]).T + + # forming scatter matrix [eqn. 17] from [1] + S1 = D1.T @ D1 + S2 = D1.T @ D2 + S3 = D2.T @ D2 + + # Constraint matrix [eqn. 18] + C1 = np.array([[0.0, 0.0, 2.0], [0.0, -1.0, 0.0], [2.0, 0.0, 0.0]]) + + try: + # Reduced scatter matrix [eqn. 29] + M = inv(C1) @ (S1 - S2 @ inv(S3) @ S2.T) + except np.linalg.LinAlgError: # LinAlgError: Singular matrix + return 'Singular matrix from estimation' + + # M*|a b c >=l|a b c >. Find eigenvalues and eigenvectors + # from this equation [eqn. 28] + eig_vals, eig_vecs = np.linalg.eig(M) + + # eigenvector must meet constraint 4ac - b^2 to be valid. + cond = 4 * np.multiply(eig_vecs[0, :], eig_vecs[2, :]) - np.power( + eig_vecs[1, :], 2 + ) + a1 = eig_vecs[:, (cond > 0)] + # seeks for empty matrix + if 0 in a1.shape or len(a1.ravel()) != 3: + return 'Eigenvector constraints not met' + a, b, c = a1.ravel() + + # |d f g> = -S3^(-1)*S2^(T)*|a b c> [eqn. 24] + a2 = -inv(S3) @ S2.T @ a1 + d, f, g = a2.ravel() + + # eigenvectors are the coefficients of an ellipse in general form + # a*x^2 + 2*b*x*y + c*y^2 + 2*d*x + 2*f*y + g = 0 (eqn. 15) from [2] + b /= 2.0 + d /= 2.0 + f /= 2.0 + + # finding center of ellipse [eqn.19 and 20] from [2] + x0 = (c * d - b * f) / (b**2.0 - a * c) + y0 = (a * f - b * d) / (b**2.0 - a * c) + + # Find the semi-axes lengths [eqn. 21 and 22] from [2] + numerator = a * f**2 + c * d**2 + g * b**2 - 2 * b * d * f - a * c * g + term = np.sqrt((a - c) ** 2 + 4 * b**2) + denominator1 = (b**2 - a * c) * (term - (a + c)) + denominator2 = (b**2 - a * c) * (-term - (a + c)) + width = np.sqrt(2 * numerator / denominator1) + height = np.sqrt(2 * numerator / denominator2) + + # angle of counterclockwise rotation of major-axis of ellipse + # to x-axis [eqn. 23] from [2]. + phi = 0.5 * np.arctan((2.0 * b) / (a - c)) + if a > c: + phi += 0.5 * np.pi + + # stabilize parameters: + # sometimes small fluctuations in data can cause + # height and width to swap + if width < height: + width, height = height, width + phi += np.pi / 2 + + phi %= np.pi + + # Revert normalization and set parameters. + params = np.nan_to_num([x0, y0, width, height, phi]).real + params[:4] *= scale + params[:2] += origin + + self.center, self.axis_lengths, self.theta = ( + params[:2], + params[2:4], + params[-1], + ) + return None + + def residuals(self, data): + """Determine residuals of data to model. + + For each point the shortest distance to the ellipse is returned. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + residuals : (N,) array + Residual for each data point. + + """ + + _check_data_dim(data, dim=2) + + xc, yc = self.center + a, b = self.axis_lengths + theta = self.theta + + ctheta = math.cos(theta) + stheta = math.sin(theta) + + x = data[:, 0] + y = data[:, 1] + + N = data.shape[0] + + def fun(t, xi, yi): + ct = math.cos(np.squeeze(t)) + st = math.sin(np.squeeze(t)) + xt = xc + a * ctheta * ct - b * stheta * st + yt = yc + a * stheta * ct + b * ctheta * st + return (xi - xt) ** 2 + (yi - yt) ** 2 + + # def Dfun(t, xi, yi): + # ct = math.cos(t) + # st = math.sin(t) + # xt = xc + a * ctheta * ct - b * stheta * st + # yt = yc + a * stheta * ct + b * ctheta * st + # dfx_t = - 2 * (xi - xt) * (- a * ctheta * st + # - b * stheta * ct) + # dfy_t = - 2 * (yi - yt) * (- a * stheta * st + # + b * ctheta * ct) + # return [dfx_t + dfy_t] + + residuals = np.empty((N,), dtype=np.float64) + + # initial guess for parameter t of closest point on ellipse + t0 = np.arctan2(y - yc, x - xc) - theta + + # determine shortest distance to ellipse for each point + for i in range(N): + xi = x[i] + yi = y[i] + # faster without Dfun, because of the python overhead + t, _ = optimize.leastsq(fun, t0[i], args=(xi, yi)) + residuals[i] = np.sqrt(fun(t, xi, yi)) + + return residuals + + @_deprecate_model_params + def predict_xy(self, t, params=DEPRECATED): + """Predict x- and y-coordinates using the estimated model. + + Parameters + ---------- + t : array + Angles in circle in radians. Angles start to count from positive + x-axis to positive y-axis in a right-handed system. + + Returns + ------- + xy : (..., 2) array + Predicted x- and y-coordinates. + + Other parameters + ---------------- + params : `~.DEPRECATED`, optional + Optional ellipse model parameters in the following order ``xc``, + ``yc``, `a`, `b`, `theta`. + + .. deprecated:: {{ start_version }} + """ + t = np.asanyarray(t) + (xc, yc), (a, b), theta = self._get_init_values(params) + + ct = np.cos(t) + st = np.sin(t) + ctheta = math.cos(theta) + stheta = math.sin(theta) + + x = xc + a * ctheta * ct - b * stheta * st + y = yc + a * stheta * ct + b * ctheta * st + + return np.concatenate((x[..., None], y[..., None]), axis=t.ndim) + + @_deprecate_estimate + def estimate(self, data): + """Estimate ellipse model from data using total least squares. + + Parameters + ---------- + data : (N, 2) array + N points with ``(x, y)`` coordinates, respectively. + + Returns + ------- + success : bool + True, if model estimation succeeds. + + + References + ---------- + .. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares + fitting of ellipses". In Proc. 6th International Conference in + Central Europe on Computer Graphics and Visualization. + WSCG (Vol. 98, pp. 125-132). + + """ + return self._estimate(data) is None + + +def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability): + """Determine number trials such that at least one outlier-free subset is + sampled for the given inlier/outlier ratio. + + Parameters + ---------- + n_inliers : int + Number of inliers in the data. + n_samples : int + Total number of samples in the data. + min_samples : int + Minimum number of samples chosen randomly from original data. + probability : float + Probability (confidence) that one outlier-free sample is generated. + + Returns + ------- + trials : int + Number of trials. + """ + if probability == 0: + return 0 + if n_inliers == 0: + return np.inf + inlier_ratio = n_inliers / n_samples + nom = 1 - probability + denom = 1 - inlier_ratio**min_samples + # Keep (de-)nominator in the range of [_EPSILON, 1 - _EPSILON] so that + # it is always guaranteed that the logarithm is negative and we return + # a positive number of trials. + nom = np.clip(nom, a_min=_EPSILON, a_max=1 - _EPSILON) + denom = np.clip(denom, a_min=_EPSILON, a_max=1 - _EPSILON) + return np.ceil(np.log(nom) / np.log(denom)) + + +def add_from_estimate(cls): + """Add ``from_estimate`` method class using ``estimate`` method""" + + if hasattr(cls, 'from_estimate'): + if not inspect.ismethod(cls.from_estimate): + raise TypeError(f'Class {cls} `from_estimate` must be a ' 'class method.') + return cls + + if not hasattr(cls, 'estimate'): + raise TypeError( + f'Class {cls} must have `from_estimate` class method ' + 'or `estimate` method.' + ) + + warn( + "Passing custom classes without `from_estimate` has been deprecated " + "since version 0.26 and will be removed in version 2.2. " + "Add `from_estimate` class method to custom class to avoid this " + "warning.", + category=FutureWarning, + stacklevel=3, + ) + + class FromEstimated(cls): + @classmethod + def from_estimate(klass, *args, **kwargs): + # Assume we can make default instance without input arguments. + instance = klass() + success = instance.estimate(*args, **kwargs) + return ( + instance + if success + else FailedEstimation(f'`{cls.__name__}` estimation failed') + ) + + return FromEstimated + + +def ransac( + data, + model_class, + min_samples, + residual_threshold, + is_data_valid=None, + is_model_valid=None, + max_trials=100, + stop_sample_num=np.inf, + stop_residuals_sum=0, + stop_probability=1, + rng=None, + initial_inliers=None, +): + """Fit a model to data with the RANSAC (random sample consensus) algorithm. + + RANSAC is an iterative algorithm for the robust estimation of parameters + from a subset of inliers from the complete data set. Each iteration + performs the following tasks: + + 1. Select `min_samples` random samples from the original data and check + whether the set of data is valid (see `is_data_valid`). + 2. Estimate a model to the random subset + (`model_cls.from_estimate(*data[random_subset]`) and check whether the + estimated model is valid (see `is_model_valid`). + 3. Classify all data as inliers or outliers by calculating the residuals + to the estimated model (`model_cls.residuals(*data)`) - all data samples + with residuals smaller than the `residual_threshold` are considered as + inliers. + 4. Save estimated model as best model if number of inlier samples is + maximal. In case the current estimated model has the same number of + inliers, it is only considered as the best model if it has less sum of + residuals. + + These steps are performed either a maximum number of times or until one of + the special stop criteria are met. The final model is estimated using all + inlier samples of the previously determined best model. + + Parameters + ---------- + data : list or tuple or array of shape (N,) + Data set to which the model is fitted, where N is the number of data + points and the remaining dimension are depending on model requirements. + If the model class requires multiple input data arrays (e.g. source and + destination coordinates of ``skimage.transform.AffineTransform``), + they can be optionally passed as tuple or list. Note, that in this case + the functions ``estimate(*data)``, ``residuals(*data)``, + ``is_model_valid(model, *random_data)`` and + ``is_data_valid(*random_data)`` must all take each data array as + separate arguments. + model_class : type + Class with the following methods: + + * Either: + + * ``from_estimate`` class method returning transform instance, as in + ``tform = model_class.from_estimate(*data)``; the resulting + ``tform`` should be truthy (``bool(tform) == True``) where + estimation succeeded, or falsey (``bool(tform) == False``) where it + failed; OR + * (deprecated) ``estimate`` instance method, returning flag to + indicate successful estimation, as in ``tform = model_class(); + success = tform.estimate(*data)``. ``success == True`` when + estimation succeeded, ``success == False`` when it failed. + + * ``residuals(*data)`` + + Your model should conform to the ``RansacModelProtocol`` — meaning + implement all of the methods / attributes specified by the + :class:``RansacModelProctocol``. An easy check to see whether that is + the case is to use ``isinstance(MyModel, RansacModelProtocol)``. See + https://docs.python.org/3/library/typing.html#typing.Protocol for more + details. + + min_samples : int, in range (0, N) + The minimum number of data points to fit a model to. + residual_threshold : float, >0 + Maximum distance for a data point to be classified as an inlier. + is_data_valid : Callable, optional + This function is called with the randomly selected data before the + model is fitted to it: `is_data_valid(*random_data)`. + is_model_valid : Callable, optional + This function is called with the estimated model and the randomly + selected data: `is_model_valid(model, *random_data)`, . + max_trials : int, optional + Maximum number of iterations for random sample selection. + stop_sample_num : int, optional + Stop iteration if at least this number of inliers are found. + stop_residuals_sum : float, optional + Stop iteration if sum of residuals is less than or equal to this + threshold. + stop_probability : float, optional, in range [0, 1] + RANSAC iteration stops if at least one outlier-free set of the + training data is sampled with ``probability >= stop_probability``, + depending on the current best model's inlier ratio and the number + of trials. This requires to generate at least N samples (trials): + + N >= log(1 - probability) / log(1 - e**m) + + where the probability (confidence) is typically set to a high value + such as 0.99, e is the current fraction of inliers w.r.t. the + total number of samples, and m is the min_samples value. + 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. + initial_inliers : array-like of bool, shape (N,), optional + Initial samples selection for model estimation + + + Returns + ------- + model : object + Best model with largest consensus set. + inliers : (N,) array + Boolean mask of inliers classified as ``True``. + + References + ---------- + .. [1] "RANSAC", Wikipedia, https://en.wikipedia.org/wiki/RANSAC + + Examples + -------- + + Generate ellipse data without tilt and add noise: + + >>> t = np.linspace(0, 2 * np.pi, 50) + >>> xc, yc = 20, 30 + >>> a, b = 5, 10 + >>> x = xc + a * np.cos(t) + >>> y = yc + b * np.sin(t) + >>> data = np.column_stack([x, y]) + >>> rng = np.random.default_rng(203560) # do not copy this value + >>> data += rng.normal(size=data.shape) + + Add some faulty data: + + >>> data[0] = (100, 100) + >>> data[1] = (110, 120) + >>> data[2] = (120, 130) + >>> data[3] = (140, 130) + + Estimate ellipse model using all available data: + + >>> model = EllipseModel.from_estimate(data) + >>> np.round(model.center) + array([71., 75.]) + >>> np.round(model.axis_lengths) + array([77., 13.]) + >>> np.round(model.theta) + 1.0 + + Next we estimate an ellipse model using RANSAC. + + Note that the results are not deterministic, because the RANSAC algorithm + uses some randomness. If you need the results to be deterministic, pass a + seeded number generator with the ``rng`` argument to ``ransac``. + + >>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50) + >>> np.abs(np.round(ransac_model.center)) # doctest: +SKIP + array([20., 30.]) + >>> np.abs(np.round(ransac_model.axis_lengths)) # doctest: +SKIP + array([10., 6.]) + >>> np.abs(np.round(ransac_model.theta)) # doctest: +SKIP + 2.0 + >>> inliers # doctest: +SKIP + array([False, False, False, False, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True], dtype=bool) + >>> sum(inliers) > 40 + True + + RANSAC can be used to robustly estimate a geometric + transformation. In this section, we also show how to use a + proportion of the total samples, rather than an absolute number. + + >>> from skimage.transform import SimilarityTransform + >>> rng = np.random.default_rng() + >>> src = 100 * rng.random((50, 2)) + >>> model0 = SimilarityTransform(scale=0.5, rotation=1, + ... translation=(10, 20)) + >>> dst = model0(src) + >>> dst[0] = (10000, 10000) + >>> dst[1] = (-100, 100) + >>> dst[2] = (50, 50) + >>> ratio = 0.5 # use half of the samples + >>> min_samples = int(ratio * len(src)) + >>> model, inliers = ransac( + ... (src, dst), + ... SimilarityTransform, + ... min_samples, + ... 10, + ... initial_inliers=np.ones(len(src), dtype=bool), + ... ) # doctest: +SKIP + >>> inliers # doctest: +SKIP + array([False, False, False, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True, True, True, True, True, + True, True, True, True, True]) + + """ + + best_inlier_num = 0 + best_inlier_residuals_sum = np.inf + best_inliers = [] + validate_model = is_model_valid is not None + validate_data = is_data_valid is not None + + rng = np.random.default_rng(rng) + + # in case data is not pair of input and output, male it like it + if not isinstance(data, (tuple, list)): + data = (data,) + num_samples = len(data[0]) + + if not (0 < min_samples <= num_samples): + raise ValueError(f"`min_samples` must be in range (0, {num_samples}]") + + if residual_threshold < 0: + raise ValueError("`residual_threshold` must be greater than zero") + + if max_trials < 0: + raise ValueError("`max_trials` must be greater than zero") + + if not (0 <= stop_probability <= 1): + raise ValueError("`stop_probability` must be in range [0, 1]") + + if initial_inliers is not None and len(initial_inliers) != num_samples: + raise ValueError( + f"RANSAC received a vector of initial inliers (length " + f"{len(initial_inliers)}) that didn't match the number of " + f"samples ({num_samples}). The vector of initial inliers should " + f"have the same length as the number of samples and contain only " + f"True (this sample is an initial inlier) and False (this one " + f"isn't) values." + ) + + # for the first run use initial guess of inliers + spl_idxs = ( + initial_inliers + if initial_inliers is not None + else rng.choice(num_samples, min_samples, replace=False) + ) + + # Ensure model_class has from_estimate class method. + model_class = add_from_estimate(model_class) + + # Check protocol. + if not isinstance(model_class, RansacModelProtocol): + raise TypeError( + f"`model_class` {model_class} should be of (protocol) type " + "RansacModelProtocol" + ) + + num_trials = 0 + # max_trials can be updated inside the loop, so this cannot be a for-loop + while num_trials < max_trials: + num_trials += 1 + + # do sample selection according data pairs + samples = [d[spl_idxs] for d in data] + + # for next iteration choose random sample set and be sure that + # no samples repeat + spl_idxs = rng.choice(num_samples, min_samples, replace=False) + + # optional check if random sample set is valid + if validate_data and not is_data_valid(*samples): + continue + + model = model_class.from_estimate(*samples) + # backwards compatibility + if not model: + continue + + # optional check if estimated model is valid + if validate_model and not is_model_valid(model, *samples): + continue + + residuals = np.abs(model.residuals(*data)) + # consensus set / inliers + inliers = residuals < residual_threshold + residuals_sum = residuals.dot(residuals) + + # choose as new best model if number of inliers is maximal + inliers_count = np.count_nonzero(inliers) + if ( + # more inliers + inliers_count > best_inlier_num + # same number of inliers but less "error" in terms of residuals + or ( + inliers_count == best_inlier_num + and residuals_sum < best_inlier_residuals_sum + ) + ): + best_inlier_num = inliers_count + best_inlier_residuals_sum = residuals_sum + best_inliers = inliers + max_trials = min( + max_trials, + _dynamic_max_trials( + best_inlier_num, num_samples, min_samples, stop_probability + ), + ) + if ( + best_inlier_num >= stop_sample_num + or best_inlier_residuals_sum <= stop_residuals_sum + ): + break + + # estimate final model using all inliers + if any(best_inliers): + # select inliers for each data array + data_inliers = [d[best_inliers] for d in data] + model = model_class.from_estimate(*data_inliers) + if validate_model and not is_model_valid(model, *data_inliers): + warn("Estimated model is not valid. Try increasing max_trials.") + else: + model = None + best_inliers = None + warn("No inliers found. Model not fitted") + + # Return model from wrapper, otherwise model itself. + return getattr(model, 'model', model), best_inliers diff --git a/envs/kitoverlay/skimage/measure/pnpoly.py b/envs/kitoverlay/skimage/measure/pnpoly.py new file mode 100644 index 0000000000000000000000000000000000000000..31272aed8d51290ac9b5b129a78b691b7c1c5aa4 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/pnpoly.py @@ -0,0 +1,67 @@ +from ._pnpoly import _grid_points_in_poly, _points_in_poly + + +def grid_points_in_poly(shape, verts, binarize=True): + """Test whether points on a specified grid are inside a polygon. + + For each ``(r, c)`` coordinate on a grid, i.e. ``(0, 0)``, ``(0, 1)`` etc., + test whether that point lies inside a polygon. + + You can control the output type with the `binarize` flag. Please refer to its + documentation for further details. + + Parameters + ---------- + shape : tuple (M, N) + Shape of the grid. + verts : (V, 2) array + Specify the V vertices of the polygon, sorted either clockwise + or anti-clockwise. The first point may (but does not need to be) + duplicated. + binarize : bool + If `True`, the output of the function is a boolean mask. + Otherwise, it is a labeled array. The labels are: + O - outside, 1 - inside, 2 - vertex, 3 - edge. + + See Also + -------- + points_in_poly + + Returns + ------- + mask : (M, N) ndarray + If `binarize` is True, the output is a boolean mask. True means the + corresponding pixel falls inside the polygon. + If `binarize` is False, the output is a labeled array, with pixels + having a label between 0 and 3. The meaning of the values is: + O - outside, 1 - inside, 2 - vertex, 3 - edge. + + """ + output = _grid_points_in_poly(shape, verts) + if binarize: + output = output.astype(bool) + return output + + +def points_in_poly(points, verts): + """Test whether points lie inside a polygon. + + Parameters + ---------- + points : (K, 2) array + Input points, ``(x, y)``. + verts : (L, 2) array + Vertices of the polygon, sorted either clockwise or anti-clockwise. + The first point may (but does not need to be) duplicated. + + See Also + -------- + grid_points_in_poly + + Returns + ------- + mask : (K,) array of bool + True if corresponding point is inside the polygon. + + """ + return _points_in_poly(points, verts) diff --git a/envs/kitoverlay/skimage/measure/profile.py b/envs/kitoverlay/skimage/measure/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..246689553d94f33c36f141ebdf143d1bd0bdaf32 --- /dev/null +++ b/envs/kitoverlay/skimage/measure/profile.py @@ -0,0 +1,190 @@ +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _validate_interpolation_order, _fix_ndimage_mode + + +def profile_line( + image, + src, + dst, + linewidth=1, + order=None, + mode='reflect', + cval=0.0, + *, + reduce_func=np.mean, +): + """Return the intensity profile of an image measured along a scan line. + + Parameters + ---------- + image : ndarray, shape (M, N[, C]) + The image, either grayscale (2D array) or multichannel + (3D array, where the final axis contains the channel + information). + src : array_like, shape (2,) + The coordinates of the start point of the scan line. + dst : array_like, shape (2,) + The coordinates of the end point of the scan + line. The destination point is *included* in the profile, in + contrast to standard numpy indexing. + linewidth : int, optional + Width of the scan, perpendicular to the line + order : int in {0, 1, 2, 3, 4, 5}, 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', 'nearest', 'reflect', 'mirror', 'wrap'}, optional + How to compute any values falling outside of the image. + cval : float, optional + If `mode` is 'constant', what constant value to use outside the image. + reduce_func : callable, optional + Function used to calculate the aggregation of pixel values + perpendicular to the profile_line direction when `linewidth` > 1. + If set to None the unreduced array will be returned. + + Returns + ------- + return_value : array + The intensity profile along the scan line. The length of the profile + is the ceil of the computed length of the scan line. + + Examples + -------- + >>> x = np.array([[1, 1, 1, 2, 2, 2]]) + >>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)]) + >>> img + array([[0, 0, 0, 0, 0, 0], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [0, 0, 0, 0, 0, 0]]) + >>> profile_line(img, (2, 1), (2, 4)) + array([1., 1., 2., 2.]) + >>> profile_line(img, (1, 0), (1, 6), cval=4) + array([1., 1., 1., 2., 2., 2., 2.]) + + The destination point is included in the profile, in contrast to + standard numpy indexing. + For example: + + >>> profile_line(img, (1, 0), (1, 6)) # The final point is out of bounds + array([1., 1., 1., 2., 2., 2., 2.]) + >>> profile_line(img, (1, 0), (1, 5)) # This accesses the full first row + array([1., 1., 1., 2., 2., 2.]) + + For different reduce_func inputs: + + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.mean) + array([0.66666667, 0.66666667, 0.66666667, 1.33333333]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.max) + array([1, 1, 1, 2]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sum) + array([2, 2, 2, 4]) + + The unreduced array will be returned when `reduce_func` is None or when + `reduce_func` acts on each pixel value individually. + + >>> profile_line(img, (1, 2), (4, 2), linewidth=3, order=0, + ... reduce_func=None) + array([[1, 1, 2], + [1, 1, 2], + [1, 1, 2], + [0, 0, 0]]) + >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sqrt) + array([[1. , 1. , 0. ], + [1. , 1. , 0. ], + [1. , 1. , 0. ], + [1.41421356, 1.41421356, 0. ]]) + """ + + order = _validate_interpolation_order(image.dtype, order) + mode = _fix_ndimage_mode(mode) + + perp_lines = _line_profile_coordinates(src, dst, linewidth=linewidth) + if image.ndim == 3: + pixels = [ + ndi.map_coordinates( + image[..., i], + perp_lines, + prefilter=order > 1, + order=order, + mode=mode, + cval=cval, + ) + for i in range(image.shape[2]) + ] + pixels = np.transpose(np.asarray(pixels), (1, 2, 0)) + else: + pixels = ndi.map_coordinates( + image, perp_lines, prefilter=order > 1, order=order, mode=mode, cval=cval + ) + # The outputted array with reduce_func=None gives an array where the + # row values (axis=1) are flipped. Here, we make this consistent. + pixels = np.flip(pixels, axis=1) + + if reduce_func is None: + intensities = pixels + else: + try: + intensities = reduce_func(pixels, axis=1) + except TypeError: # function doesn't allow axis kwarg + intensities = np.apply_along_axis(reduce_func, arr=pixels, axis=1) + + return intensities + + +def _line_profile_coordinates(src, dst, linewidth=1): + """Return the coordinates of the profile of an image along a scan line. + + Parameters + ---------- + src : 2-tuple of numeric scalar (float or int) + The start point of the scan line. + dst : 2-tuple of numeric scalar (float or int) + The end point of the scan line. + linewidth : int, optional + Width of the scan, perpendicular to the line + + Returns + ------- + coords : array, shape (2, N, C), float + The coordinates of the profile along the scan line. The length of the + profile is the ceil of the computed length of the scan line. + + Notes + ----- + This is a utility method meant to be used internally by skimage functions. + The destination point is included in the profile, in contrast to + standard numpy indexing. + """ + src_row, src_col = src = np.asarray(src, dtype=float) + dst_row, dst_col = dst = np.asarray(dst, dtype=float) + d_row, d_col = dst - src + theta = np.arctan2(d_row, d_col) + + length = int(np.ceil(np.hypot(d_row, d_col) + 1)) + # we add one above because we include the last point in the profile + # (in contrast to standard numpy indexing) + line_col = np.linspace(src_col, dst_col, length) + line_row = np.linspace(src_row, dst_row, length) + + # we subtract 1 from linewidth to change from pixel-counting + # (make this line 3 pixels wide) to point distances (the + # distance between pixel centers) + col_width = (linewidth - 1) * np.sin(-theta) / 2 + row_width = (linewidth - 1) * np.cos(theta) / 2 + perp_rows = np.stack( + [ + np.linspace(row_i - row_width, row_i + row_width, linewidth) + for row_i in line_row + ] + ) + perp_cols = np.stack( + [ + np.linspace(col_i - col_width, col_i + col_width, linewidth) + for col_i in line_col + ] + ) + return np.stack([perp_rows, perp_cols]) diff --git a/envs/kitoverlay/skimage/morphology/__init__.py b/envs/kitoverlay/skimage/morphology/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c2fa58aa778adae6f3c67cc51e37f53ef40455 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/__init__.py @@ -0,0 +1,87 @@ +"""Morphological algorithms, e.g., closing, opening, skeletonization.""" + +from .binary import binary_closing, binary_dilation, binary_erosion, binary_opening +from .gray import black_tophat, closing, dilation, erosion, opening, white_tophat +from .isotropic import ( + isotropic_erosion, + isotropic_dilation, + isotropic_opening, + isotropic_closing, +) +from .footprints import ( + ball, + cube, + diamond, + disk, + ellipse, + footprint_from_sequence, + footprint_rectangle, + mirror_footprint, + octagon, + octahedron, + pad_footprint, + rectangle, + square, + star, +) +from ..measure._label import label +from ._skeletonize import medial_axis, skeletonize, thin +from .convex_hull import convex_hull_image, convex_hull_object +from .grayreconstruct import reconstruction +from .misc import remove_small_holes, remove_small_objects, remove_objects_by_distance +from .extrema import h_maxima, h_minima, local_minima, local_maxima +from ._flood_fill import flood, flood_fill +from .max_tree import ( + area_opening, + area_closing, + diameter_closing, + diameter_opening, + max_tree, + max_tree_local_maxima, +) + +__all__ = [ + 'area_closing', + 'area_opening', + 'ball', + 'black_tophat', + 'closing', + 'convex_hull_image', + 'convex_hull_object', + 'diameter_closing', + 'diameter_opening', + 'diamond', + 'dilation', + 'disk', + 'ellipse', + 'erosion', + 'flood', + 'flood_fill', + 'footprint_from_sequence', + 'footprint_rectangle', + 'h_maxima', + 'h_minima', + 'isotropic_closing', + 'isotropic_dilation', + 'isotropic_erosion', + 'isotropic_opening', + 'label', + 'local_maxima', + 'local_minima', + 'max_tree', + 'max_tree_local_maxima', + 'medial_axis', + 'mirror_footprint', + 'octagon', + 'octahedron', + 'opening', + 'pad_footprint', + 'reconstruction', + 'remove_small_holes', + 'remove_small_objects', + 'remove_objects_by_distance', + 'skeletonize', + 'star', + 'thin', + 'white_tophat', +] diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7406d51b7d156140942effb8a0a624708517f16 Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/_flood_fill.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/_flood_fill.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c47ccf33ab40dc75f0b5ad5f20c1735cd8765761 Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/_flood_fill.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/_skeletonize.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/_skeletonize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88c0aaff8c0cc42a8fb44a6d2385246cba75bf44 Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/_skeletonize.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/_util.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164f5e3349b30988169b4b4acdaaa4e381a49f35 Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/_util.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/binary.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/binary.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30901c39168af69757e68c5489a4e41f124a835a Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/binary.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/convex_hull.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/convex_hull.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40e6279630a56c15c5a2cb24e9b5e6b41df68c1f Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/convex_hull.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/extrema.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/extrema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fda26460f9dc3e7c8fb5d78573af28566bee235f Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/extrema.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/footprints.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/footprints.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2729723fc9bc9d92429082d2d01ebcb14dce160e Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/footprints.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/gray.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/gray.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496d36c44a466ee2a14fc690663bc8bb28e13d0d Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/gray.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/grayreconstruct.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/grayreconstruct.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d00cbb6edf67b7b5058798d2f51b02b807b0f1a8 Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/grayreconstruct.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/isotropic.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/isotropic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87c9b388df610cacaab838c4230d8ee34dcdd32e Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/isotropic.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/max_tree.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/max_tree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3bb7f6704408b0150dbd378e9b4d89402be5aaa Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/max_tree.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/__pycache__/misc.cpython-311.pyc b/envs/kitoverlay/skimage/morphology/__pycache__/misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9304e0ebfbf592dbe52be560f53e840bdf4c2f9c Binary files /dev/null and b/envs/kitoverlay/skimage/morphology/__pycache__/misc.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/morphology/_flood_fill.py b/envs/kitoverlay/skimage/morphology/_flood_fill.py new file mode 100644 index 0000000000000000000000000000000000000000..330e3b1d3da258fbcd20567cc5c9f0bc32c09eee --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/_flood_fill.py @@ -0,0 +1,310 @@ +"""flood_fill.py - in place flood fill algorithm + +This module provides a function to fill all equal (or within tolerance) values +connected to a given seed point with a different value. +""" + +import numpy as np + +from ..util import crop +from ._flood_fill_cy import _flood_fill_equal, _flood_fill_tolerance +from ._util import ( + _offsets_to_raveled_neighbors, + _resolve_neighborhood, + _set_border_values, +) +from .._shared.dtype import numeric_dtype_min_max + + +def flood_fill( + image, + seed_point, + new_value, + *, + footprint=None, + connectivity=None, + tolerance=None, + in_place=False, +): + """Perform flood filling on an image. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found, then set to `new_value`. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + new_value : `image` type + New value to set the entire fill. This must be chosen in agreement + with the dtype of `image`. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + value of `image` at `seed_point` to be filled. This is fastest. + If a tolerance is provided, adjacent points with values within plus or + minus tolerance from the seed point are filled (inclusive). + in_place : bool, optional + If True, flood filling is applied to `image` in place. If False, the + flood filled result is returned without modifying the input `image` + (default). + + Returns + ------- + filled : ndarray + An array with the same shape as `image` is returned, with values in + areas connected to and equal (or within tolerance of) the seed point + replaced with `new_value`. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. + + Examples + -------- + >>> from skimage.morphology import flood_fill + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> flood_fill(image, (1, 1), 5) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> flood_fill(image, (1, 1), 5, connectivity=1) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> flood_fill(image, (0, 0), 5, tolerance=1) + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + mask = flood( + image, + seed_point, + footprint=footprint, + connectivity=connectivity, + tolerance=tolerance, + ) + + if not in_place: + image = image.copy() + + image[mask] = new_value + return image + + +def flood(image, seed_point, *, footprint=None, connectivity=None, tolerance=None): + """Mask corresponding to a flood fill. + + Starting at a specific `seed_point`, connected points equal or within + `tolerance` of the seed value are found. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + seed_point : tuple or int + The point in `image` used as the starting point for the flood fill. If + the image is 1D, this point may be given as an integer. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel. It must contain only 1's and 0's, have the + same number of dimensions as `image`. If not given, all adjacent pixels + are considered as part of the neighborhood (fully connected). + connectivity : int, optional + A number used to determine the neighborhood of each evaluated pixel. + Adjacent pixels whose squared distance from the center is less than or + equal to `connectivity` are considered neighbors. Ignored if + `footprint` is not None. + tolerance : float or int, optional + If None (default), adjacent values must be strictly equal to the + initial value of `image` at `seed_point`. This is fastest. If a value + is given, a comparison will be done at every point and if within + tolerance of the initial value will also be filled (inclusive). + + Returns + ------- + mask : ndarray + A Boolean array with the same shape as `image` is returned, with True + values for areas connected to and equal (or within tolerance of) the + seed point. All other values are False. + + Notes + ----- + The conceptual analogy of this operation is the 'paint bucket' tool in many + raster graphics programs. This function returns just the mask + representing the fill. + + If indices are desired rather than masks for memory reasons, the user can + simply run `numpy.nonzero` on the result, save the indices, and discard + this mask. + + Examples + -------- + >>> from skimage.morphology import flood + >>> image = np.zeros((4, 7), dtype=int) + >>> image[1:3, 1:3] = 1 + >>> image[3, 0] = 1 + >>> image[1:3, 4:6] = 2 + >>> image[3, 6] = 3 + >>> image + array([[0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 2, 2, 0], + [0, 1, 1, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, with full connectivity (diagonals included): + + >>> mask = flood(image, (1, 1)) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [5, 0, 0, 0, 0, 0, 3]]) + + Fill connected ones with 5, excluding diagonal points (connectivity 1): + + >>> mask = flood(image, (1, 1), connectivity=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[0, 0, 0, 0, 0, 0, 0], + [0, 5, 5, 0, 2, 2, 0], + [0, 5, 5, 0, 2, 2, 0], + [1, 0, 0, 0, 0, 0, 3]]) + + Fill with a tolerance: + + >>> mask = flood(image, (0, 0), tolerance=1) + >>> image_flooded = image.copy() + >>> image_flooded[mask] = 5 + >>> image_flooded + array([[5, 5, 5, 5, 5, 5, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 2, 2, 5], + [5, 5, 5, 5, 5, 5, 3]]) + """ + # Correct start point in ravelled image - only copy if non-contiguous + image = np.asarray(image) + if image.flags.f_contiguous is True: + order = 'F' + elif image.flags.c_contiguous is True: + order = 'C' + else: + image = np.ascontiguousarray(image) + order = 'C' + + # Shortcut for rank zero + if 0 in image.shape: + return np.zeros(image.shape, dtype=bool) + + # Convenience for 1d input + try: + iter(seed_point) + except TypeError: + seed_point = (seed_point,) + + seed_value = image[seed_point] + seed_point = tuple(np.asarray(seed_point) % image.shape) + + footprint = _resolve_neighborhood( + footprint, connectivity, image.ndim, enforce_adjacency=False + ) + center = tuple(s // 2 for s in footprint.shape) + # Compute padding width as the maximum offset to neighbors on each axis. + # Generates a 2-tuple of (pad_start, pad_end) for each axis. + pad_width = [ + (np.max(np.abs(idx - c)),) * 2 for idx, c in zip(np.nonzero(footprint), center) + ] + + # Must annotate borders + working_image = np.pad( + image, pad_width, mode='constant', constant_values=image.min() + ) + # Stride-aware neighbors - works for both C- and Fortran-contiguity + ravelled_seed_idx = np.ravel_multi_index( + [i + pad_start for i, (pad_start, pad_end) in zip(seed_point, pad_width)], + working_image.shape, + order=order, + ) + neighbor_offsets = _offsets_to_raveled_neighbors( + working_image.shape, footprint, center=center, order=order + ) + + # Use a set of flags; see _flood_fill_cy.pyx for meanings + flags = np.zeros(working_image.shape, dtype=np.uint8, order=order) + _set_border_values(flags, value=2, border_width=pad_width) + + try: + if tolerance is not None: + tolerance = abs(tolerance) + # Account for over- & underflow problems with seed_value ± tolerance + # in a way that works with NumPy 1 & 2 + min_value, max_value = numeric_dtype_min_max(seed_value.dtype) + low_tol = max(min_value.item(), seed_value.item() - tolerance) + high_tol = min(max_value.item(), seed_value.item() + tolerance) + + _flood_fill_tolerance( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + low_tol, + high_tol, + ) + else: + _flood_fill_equal( + working_image.ravel(order), + flags.ravel(order), + neighbor_offsets, + ravelled_seed_idx, + seed_value, + ) + except TypeError: + if working_image.dtype == np.float16: + # Provide the user with clearer error message + raise TypeError( + "dtype of `image` is float16 which is not " + "supported, try upcasting to float32" + ) + else: + raise + + # Output what the user requested; view does not create a new copy. + return crop(flags, pad_width, copy=False).view(bool) diff --git a/envs/kitoverlay/skimage/morphology/binary.py b/envs/kitoverlay/skimage/morphology/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe429d1b758c7df0ee9be8591ce0534ac4fc7e7 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/binary.py @@ -0,0 +1,361 @@ +""" +Binary morphological operations +""" + +import warnings + +import numpy as np +from scipy import ndimage as ndi + +from .footprints import _footprint_is_sequence, pad_footprint +from .misc import default_footprint +from .._shared.utils import deprecate_func + + +def _iterate_binary_func(binary_func, image, footprint, out, border_value): + """Helper to call `binary_func` for each footprint in a sequence. + + binary_func is a binary morphology function that accepts "structure", + "output" and "iterations" keyword arguments + (e.g. `scipy.ndimage.binary_erosion`). + """ + fp, num_iter = footprint[0] + binary_func( + image, structure=fp, output=out, iterations=num_iter, border_value=border_value + ) + for fp, num_iter in footprint[1:]: + # Note: out.copy() because the computation cannot be in-place! + # SciPy <= 1.7 did not automatically make a copy if needed. + binary_func( + out.copy(), + structure=fp, + output=out, + iterations=num_iter, + border_value=border_value, + ) + return out + + +# The default_footprint decorator provides a diamond footprint as +# default with the same dimension as the input image and size 3 along each +# axis. +@default_footprint +@deprecate_func( + deprecated_version="0.26", + removed_version="0.28", + hint="Use `skimage.morphology.erosion` instead. " + "Note the pixel shift by 1 for even-sized footprints (see docstring notes).", +) +def binary_erosion(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological erosion of an image. + + This function returns the same result as grayscale erosion but performs + faster for binary images. + + Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all + pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright + regions and enlarges dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'max' or 'ignore', pixels outside the image domain are assumed + to be `True`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + eroded : ndarray of bool or uint + The result of the morphological erosion taking values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For even-sized footprints, :func:`skimage.morphology.erosion` and + this function produce an output that differs: one is shifted by one pixel + compared to the other. :func:`skimage.morphology.pad_footprint´ is available + to account for this. + + See also + -------- + skimage.morphology.isotropic_erosion + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = False if mode == 'min' else True + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_erosion, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +@deprecate_func( + deprecated_version="0.26", + removed_version="0.28", + hint="Use `skimage.morphology.dilation` instead. " + "Note the lack of mirroring for non-symmetric footprints (see docstring notes).", +) +def binary_dilation(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological dilation of an image. + + This function returns the same result as grayscale dilation but performs + faster for binary images. + + Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all + pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright + regions and shrinks dark regions. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'min' or 'ignore', pixels outside the image domain are assumed + to be `False`, which causes them to not influence the result. + Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + dilated : ndarray of bool or uint + The result of the morphological dilation with values in + ``[False, True]``. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + For non-symmetric footprints, :func:`skimage.morphology.binary_dilation` + and :func:`skimage.morphology.dilation` produce an output that differs: + `binary_dilation` mirrors the footprint, whereas `dilation` does not. + :func:`skimage.morphology.mirror_footprint` is available to correct for this. + + See also + -------- + skimage.morphology.isotropic_dilation + + """ + if out is None: + out = np.empty(image.shape, dtype=bool) + + if mode not in {"max", "min", "ignore"}: + raise ValueError(f"unsupported mode, got {mode!r}") + border_value = True if mode == 'max' else False + + footprint = pad_footprint(footprint, pad_end=True) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_binary_func( + binary_func=ndi.binary_dilation, + image=image, + footprint=footprint, + out=out, + border_value=border_value, + ) + return out + + +@default_footprint +@deprecate_func( + deprecated_version="0.26", + removed_version="0.28", + hint="Use `skimage.morphology.opening` instead.", +) +def binary_opening(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological opening of an image. + + This function returns the same result as grayscale opening but performs + faster for binary images. + + The morphological opening on an image is defined as an erosion followed by + a dilation. Opening can remove small bright spots (i.e. "salt") and connect + small dark cracks. This tends to "open" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + opening : ndarray of bool + The result of the morphological opening. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_opening + + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + action="ignore", + message="`binary_(dilation|erosion)` is deprecated", + category=FutureWarning, + module="skimage", + ) + tmp = binary_erosion(image, footprint, mode=mode) + out = binary_dilation(tmp, footprint, out=out, mode=mode) + return out + + +@default_footprint +@deprecate_func( + deprecated_version="0.26", + removed_version="0.28", + hint="Use `skimage.morphology.closing` instead.", +) +def binary_closing(image, footprint=None, out=None, *, mode='ignore'): + """Return fast binary morphological closing of an image. + + This function returns the same result as grayscale closing but performs + faster for binary images. + + The morphological closing on an image is defined as a dilation followed by + an erosion. Closing can remove small dark spots (i.e. "pepper") and connect + small bright cracks. This tends to "close" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Binary input image. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'max', 'min', 'ignore'. + If 'ignore', pixels outside the image domain are assumed to be `True` + for the erosion and `False` for the dilation, which causes them to not + influence the result. Default is 'ignore'. + + .. versionadded:: 0.23 + `mode` was added in 0.23. + + Returns + ------- + closing : ndarray of bool + The result of the morphological closing. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate a + footprint sequence of this type. + + See also + -------- + skimage.morphology.isotropic_closing + + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + action="ignore", + message="`binary_(dilation|erosion)` is deprecated", + category=FutureWarning, + module="skimage", + ) + tmp = binary_dilation(image, footprint, mode=mode) + out = binary_erosion(tmp, footprint, out=out, mode=mode) + return out diff --git a/envs/kitoverlay/skimage/morphology/convex_hull.py b/envs/kitoverlay/skimage/morphology/convex_hull.py new file mode 100644 index 0000000000000000000000000000000000000000..fbacbb390f917c95abdc30543d83b64da29e9737 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/convex_hull.py @@ -0,0 +1,222 @@ +"""Convex Hull.""" + +from itertools import product +import numpy as np +from scipy.spatial import ConvexHull, QhullError +from ..measure.pnpoly import grid_points_in_poly +from ._convex_hull import possible_hull +from ..measure._label import label +from ..util import unique_rows +from .._shared.utils import warn + +__all__ = ['convex_hull_image', 'convex_hull_object'] + + +def _offsets_diamond(ndim): + offsets = np.zeros((2 * ndim, ndim)) + for vertex, (axis, offset) in enumerate(product(range(ndim), (-0.5, 0.5))): + offsets[vertex, axis] = offset + return offsets + + +def _check_coords_in_hull(gridcoords, hull_equations, tolerance): + r"""Checks all the coordinates for inclusiveness in the convex hull. + + Parameters + ---------- + gridcoords : (M, N) ndarray + Coordinates of ``N`` points in ``M`` dimensions. + hull_equations : (M, N) ndarray + Hyperplane equations of the facets of the convex hull. + tolerance : float + Tolerance when determining whether a point is inside the hull. Due + to numerical floating point errors, a tolerance of 0 can result in + some points erroneously being classified as being outside the hull. + + Returns + ------- + coords_in_hull : ndarray of bool + Binary 1D ndarray representing points in n-dimensional space + with value ``True`` set for points inside the convex hull. + + Notes + ----- + Checking the inclusiveness of coordinates in a convex hull requires + intermediate calculations of dot products which are memory-intensive. + Thus, the convex hull equations are checked individually with all + coordinates to keep within the memory limit. + + References + ---------- + .. [1] https://github.com/scikit-image/scikit-image/issues/5019 + + """ + ndim, n_coords = gridcoords.shape + n_hull_equations = hull_equations.shape[0] + coords_in_hull = np.ones(n_coords, dtype=bool) + + # Pre-allocate arrays to cache intermediate results for reducing overheads + dot_array = np.empty(n_coords, dtype=np.float64) + test_ineq_temp = np.empty(n_coords, dtype=np.float64) + coords_single_ineq = np.empty(n_coords, dtype=bool) + + # A point is in the hull if it satisfies all of the hull's inequalities + for idx in range(n_hull_equations): + # Tests a hyperplane equation on all coordinates of volume + np.dot(hull_equations[idx, :ndim], gridcoords, out=dot_array) + np.add(dot_array, hull_equations[idx, ndim:], out=test_ineq_temp) + np.less(test_ineq_temp, tolerance, out=coords_single_ineq) + coords_in_hull *= coords_single_ineq + + return coords_in_hull + + +def convex_hull_image( + image, offset_coordinates=True, tolerance=1e-10, include_borders=True +): + """Compute the convex hull image of a binary image. + + The convex hull is the set of pixels included in the smallest convex + polygon that surround all white pixels in the input image. + + Parameters + ---------- + image : array + Binary input image. This array is cast to bool before processing. + offset_coordinates : bool, optional + If ``True``, a pixel at coordinate, e.g., (4, 7) will be represented + by coordinates (3.5, 7), (4.5, 7), (4, 6.5), and (4, 7.5). This adds + some "extent" to a pixel when computing the hull. + tolerance : float, optional + Tolerance when determining whether a point is inside the hull. Due + to numerical floating point errors, a tolerance of 0 can result in + some points erroneously being classified as being outside the hull. + include_borders : bool, optional + If ``False``, vertices/edges are excluded from the final hull mask. + + Returns + ------- + hull : (M, N) array of bool + Binary image with pixels in convex hull set to True. + + References + ---------- + .. [1] https://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/ + + """ + ndim = image.ndim + if np.count_nonzero(image) == 0: + warn( + "Input image is entirely zero, no valid convex hull. " + "Returning empty image", + UserWarning, + ) + return np.zeros(image.shape, dtype=bool) + # In 2D, we do an optimisation by choosing only pixels that are + # the starting or ending pixel of a row or column. This vastly + # limits the number of coordinates to examine for the virtual hull. + if ndim == 2: + coords = possible_hull(np.ascontiguousarray(image, dtype=np.uint8)) + else: + coords = np.transpose(np.nonzero(image)) + if offset_coordinates: + # when offsetting, we multiply number of vertices by 2 * ndim. + # therefore, we reduce the number of coordinates by using a + # convex hull on the original set, before offsetting. + try: + hull0 = ConvexHull(coords) + except QhullError as err: + warn( + f"Failed to get convex hull image. " + f"Returning empty image, see error message below:\n" + f"{err}" + ) + return np.zeros(image.shape, dtype=bool) + coords = hull0.points[hull0.vertices] + + # Add a vertex for the middle of each pixel edge + if offset_coordinates: + offsets = _offsets_diamond(image.ndim) + coords = (coords[:, np.newaxis, :] + offsets).reshape(-1, ndim) + + # repeated coordinates can *sometimes* cause problems in + # scipy.spatial.ConvexHull, so we remove them. + coords = unique_rows(coords) + + # Find the convex hull + try: + hull = ConvexHull(coords) + except QhullError as err: + warn( + f"Failed to get convex hull image. " + f"Returning empty image, see error message below:\n" + f"{err}" + ) + return np.zeros(image.shape, dtype=bool) + vertices = hull.points[hull.vertices] + + # If 2D, use fast Cython function to locate convex hull pixels + if ndim == 2: + labels = grid_points_in_poly(image.shape, vertices, binarize=False) + # If include_borders is True, we include vertices (2) and edge + # points (3) in the mask, otherwise only the inside of the hull (1) + mask = labels >= 1 if include_borders else labels == 1 + else: + gridcoords = np.reshape(np.mgrid[tuple(map(slice, image.shape))], (ndim, -1)) + + coords_in_hull = _check_coords_in_hull(gridcoords, hull.equations, tolerance) + mask = np.reshape(coords_in_hull, image.shape) + + return mask + + +def convex_hull_object(image, *, connectivity=2): + r"""Compute the convex hull image of individual objects in a binary image. + + The convex hull is the set of pixels included in the smallest convex + polygon that surround all white pixels in the input image. + + Parameters + ---------- + image : (M, N) ndarray + Binary input image. + connectivity : {1, 2}, int, optional + Determines the neighbors of each pixel. Adjacent elements + within a squared distance of ``connectivity`` from pixel center + are considered neighbors.:: + + 1-connectivity 2-connectivity + [ ] [ ] [ ] [ ] + | \ | / + [ ]--[x]--[ ] [ ]--[x]--[ ] + | / | \ + [ ] [ ] [ ] [ ] + + Returns + ------- + hull : ndarray of bool + Binary image with pixels inside convex hull set to ``True``. + + Notes + ----- + This function uses ``skimage.morphology.label`` to define unique objects, + finds the convex hull of each using ``convex_hull_image``, and combines + these regions with logical OR. Be aware the convex hulls of unconnected + objects may overlap in the result. If this is suspected, consider using + convex_hull_image separately on each object or adjust ``connectivity``. + """ + if image.ndim > 2: + raise ValueError("Input must be a 2D image") + + if connectivity not in (1, 2): + raise ValueError('`connectivity` must be either 1 or 2.') + + labeled_im = label(image, connectivity=connectivity, background=0) + convex_obj = np.zeros(image.shape, dtype=bool) + convex_img = np.zeros(image.shape, dtype=bool) + + for i in range(1, labeled_im.max() + 1): + convex_obj = convex_hull_image(labeled_im == i) + convex_img = np.logical_or(convex_img, convex_obj) + + return convex_img diff --git a/envs/kitoverlay/skimage/morphology/footprints.py b/envs/kitoverlay/skimage/morphology/footprints.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb6736ac9accce242eec271fd06c9cb009d0677 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/footprints.py @@ -0,0 +1,1110 @@ +import os +import warnings +from collections.abc import Sequence +from numbers import Integral + +import numpy as np + +from .. import draw +from skimage import morphology +from .._shared.utils import deprecate_func + + +# Precomputed ball and disk decompositions were saved as 2D arrays where the +# radius of the desired decomposition is used to index into the first axis of +# the array. The values at a given radius corresponds to the number of +# repetitions of 3 different types elementary of structuring elements. +# +# See _nsphere_series_decomposition for full details. +_nsphere_decompositions = {} +_nsphere_decompositions[2] = np.load( + os.path.join(os.path.dirname(__file__), 'disk_decompositions.npy') +) +_nsphere_decompositions[3] = np.load( + os.path.join(os.path.dirname(__file__), 'ball_decompositions.npy') +) + + +def _footprint_is_sequence(footprint): + if hasattr(footprint, '__array_interface__'): + return False + + def _validate_sequence_element(t): + return ( + isinstance(t, Sequence) + and len(t) == 2 + and hasattr(t[0], '__array_interface__') + and isinstance(t[1], Integral) + ) + + if isinstance(footprint, Sequence): + if not all(_validate_sequence_element(t) for t in footprint): + raise ValueError( + "All elements of footprint sequence must be a 2-tuple where " + "the first element of the tuple is an ndarray and the second " + "is an integer indicating the number of iterations." + ) + else: + raise ValueError("footprint must be either an ndarray or Sequence") + return True + + +def _shape_from_sequence(footprints, require_odd_size=False): + """Determine the shape of composite footprint + + In the future if we only want to support odd-sized square, we may want to + change this to require_odd_size + """ + if not _footprint_is_sequence(footprints): + raise ValueError("expected a sequence of footprints") + ndim = footprints[0][0].ndim + shape = [0] * ndim + + def _odd_size(size, require_odd_size): + if require_odd_size and size % 2 == 0: + raise ValueError("expected all footprint elements to have odd size") + + for d in range(ndim): + fp, nreps = footprints[0] + _odd_size(fp.shape[d], require_odd_size) + shape[d] = fp.shape[d] + (nreps - 1) * (fp.shape[d] - 1) + for fp, nreps in footprints[1:]: + _odd_size(fp.shape[d], require_odd_size) + shape[d] += nreps * (fp.shape[d] - 1) + return tuple(shape) + + +def footprint_from_sequence(footprints): + """Convert a footprint sequence into an equivalent ndarray. + + Parameters + ---------- + footprints : tuple of 2-tuples + A sequence of footprint tuples where the first element of each tuple + is an array corresponding to a footprint and the second element is the + number of times it is to be applied. Currently, all footprints should + have odd size. + + Returns + ------- + footprint : ndarray + An single array equivalent to applying the sequence of ``footprints``. + """ + + # Create a single pixel image of sufficient size and apply binary dilation. + shape = _shape_from_sequence(footprints) + imag = np.zeros(shape, dtype=bool) + imag[tuple(s // 2 for s in shape)] = 1 + return morphology.dilation(imag, footprints) + + +def footprint_rectangle(shape, *, dtype=np.uint8, decomposition=None): + """Generate a rectangular or hyper-rectangular footprint. + + Generates, depending on the length and dimensions requested with `shape`, + a square, rectangle, cube, cuboid, or even higher-dimensional versions + of these shapes. + + Parameters + ---------- + shape : tuple[int, ...] + The length of the footprint in each dimension. The length of the + sequence determines the number of dimensions of the footprint. + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + give an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : array or tuple[tuple[ndarray, int], ...] + A footprint consisting only of ones, i.e. every pixel belongs to the + neighborhood. When `decomposition` is None, this is just an array. + Otherwise, this will be a tuple whose length is equal to the number of + unique structuring elements to apply (see Examples for more detail). + + Examples + -------- + >>> import skimage as ski + >>> ski.morphology.footprint_rectangle((3, 5)) + array([[1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]], dtype=uint8) + + Decomposition will return multiple footprints that combine into a simple + footprint of the requested shape. + + >>> ski.morphology.footprint_rectangle((9, 9), decomposition="sequence") + ((array([[1, 1, 1], + [1, 1, 1], + [1, 1, 1]], dtype=uint8), + 4),) + + `"sequence"` makes sure that the decomposition only returns 1D footprints. + + >>> ski.morphology.footprint_rectangle((3, 5), decomposition="separable") + ((array([[1], + [1], + [1]], dtype=uint8), + 1), + (array([[1, 1, 1, 1, 1]], dtype=uint8), 1)) + + Generate a 5-dimensional hypercube with 3 samples in each dimension + + >>> ski.morphology.footprint_rectangle((3,) * 5).shape + (3, 3, 3, 3, 3) + """ + has_even_width = any(width % 2 == 0 for width in shape) + if decomposition == "sequence" and has_even_width: + warnings.warn( + "decomposition='sequence' is only supported for uneven footprints, " + "falling back to decomposition='separable'", + stacklevel=2, + ) + decomposition = "sequence_fallback" + + def partial_footprint(dim, width): + shape_ = (1,) * dim + (width,) + (1,) * (len(shape) - dim - 1) + fp = (np.ones(shape_, dtype=dtype), 1) + return fp + + if decomposition is None: + footprint = np.ones(shape, dtype=dtype) + + elif decomposition in ("separable", "sequence_fallback"): + footprint = tuple( + partial_footprint(dim, width) for dim, width in enumerate(shape) + ) + + elif decomposition == "sequence": + min_width = min(shape) + sq_reps = _decompose_size(min_width, 3) + footprint = [(np.ones((3,) * len(shape), dtype=dtype), sq_reps)] + for dim, width in enumerate(shape): + if width > min_width: + nextra = width - min_width + 1 + component = partial_footprint(dim, nextra) + footprint.append(component) + footprint = tuple(footprint) + + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + + return footprint + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def square(width, dtype=np.uint8, *, decomposition=None): + """Generates a flat, square-shaped footprint. + + Every pixel along the perimeter has a chessboard distance + no greater than radius (radius=floor(width/2)) pixels. + + Parameters + ---------- + width : int + The width and height of the square. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + give an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` or + ``decomposition='separable'`` were observed to give better performance than + ``decomposition=None``, with the magnitude of the performance increase + rapidly increasing with footprint size. For grayscale morphology with + square footprints, it is recommended to use ``decomposition=None`` since + the internal SciPy functions that are called already have a fast + implementation based on separable 1D sliding windows. + + The 'sequence' decomposition mode only supports odd valued `width`. If + `width` is even, the sequence used will be identical to the 'separable' + mode. + """ + footprint = footprint_rectangle( + shape=(width, width), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def _decompose_size(size, kernel_size=3): + """Determine number of repeated iterations for a `kernel_size` kernel. + + Returns how many repeated morphology operations with an element of size + `kernel_size` is equivalent to a morphology with a single kernel of size + `n`. + + """ + if kernel_size % 2 != 1: + raise ValueError("only odd length kernel_size is supported") + return 1 + (size - kernel_size) // (kernel_size - 1) + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def rectangle(nrows, ncols, dtype=np.uint8, *, decomposition=None): + """Generates a flat, rectangular-shaped footprint. + + Every pixel in the rectangle generated for a given width and given height + belongs to the neighborhood. + + Parameters + ---------- + nrows : int + The number of rows of the rectangle. + ncols : int + The number of columns of the rectangle. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + With 'separable', this function uses separable 1D footprints for each + axis. Whether 'sequence' or 'separable' is computationally faster may + be architecture-dependent. + + Returns + ------- + footprint : ndarray or tuple + A footprint consisting only of ones, i.e. every pixel belongs to the + neighborhood. When `decomposition` is None, this is just a + numpy.ndarray. Otherwise, this will be a tuple whose length is equal to + the number of unique structuring elements to apply (see Notes for more + detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` + was observed to give better performance, with the magnitude of the + performance increase rapidly increasing with footprint size. For grayscale + morphology with rectangular footprints, it is recommended to use + ``decomposition=None`` since the internal SciPy functions that are called + already have a fast implementation based on separable 1D sliding windows. + + The `sequence` decomposition mode only supports odd valued `nrows` and + `ncols`. If either `nrows` or `ncols` is even, the sequence used will be + identical to ``decomposition='separable'``. + + - The use of ``width`` and ``height`` has been deprecated in + version 0.18.0. Use ``nrows`` and ``ncols`` instead. + """ + footprint = footprint_rectangle( + shape=(nrows, ncols), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def diamond(radius, dtype=np.uint8, *, decomposition=None): + """Generates a flat, diamond-shaped footprint. + + A pixel is part of the neighborhood (i.e. labeled 1) if + the city block/Manhattan distance between it and the center of + the neighborhood is no greater than radius. + + Parameters + ---------- + radius : int + The radius of the diamond-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + + """ + if decomposition is None: + L = np.arange(0, radius * 2 + 1) + I, J = np.meshgrid(L, L) + footprint = np.array( + np.abs(I - radius) + np.abs(J - radius) <= radius, dtype=dtype + ) + elif decomposition == 'sequence': + fp = diamond(1, dtype=dtype, decomposition=None) + nreps = _decompose_size(2 * radius + 1, fp.shape[0]) + footprint = ((fp, nreps),) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def _nsphere_series_decomposition(radius, ndim, dtype=np.uint8): + """Generate a sequence of footprints approximating an n-sphere. + + Morphological operations with an n-sphere (hypersphere) footprint can be + approximated by applying a series of smaller footprints of extent 3 along + each axis. Specific solutions for this are given in [1]_ for the case of + 2D disks with radius 2 through 10. + + Here we used n-dimensional extensions of the "square", "diamond" and + "t-shaped" elements from that publication. All of these elementary elements + have size ``(3,) * ndim``. We numerically computed the number of + repetitions of each element that gives the closest match to the disk + (in 2D) or ball (in 3D) computed with ``decomposition=None``. + + The approach can be extended to higher dimensions, but we have only stored + results for 2D and 3D at this point. + + Empirically, the shapes at large radius approach a hexadecagon + (16-sides [2]_) in 2D and a rhombicuboctahedron (26-faces, [3]_) in 3D. + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Hexadecagon + .. [3] https://en.wikipedia.org/wiki/Rhombicuboctahedron + """ + + if radius == 1: + # for radius 1 just use the exact shape (3,) * ndim solution + kwargs = dict(dtype=dtype, strict_radius=False, decomposition=None) + if ndim == 2: + return ((disk(1, **kwargs), 1),) + elif ndim == 3: + return ((ball(1, **kwargs), 1),) + + # load precomputed decompositions + if ndim not in _nsphere_decompositions: + raise ValueError( + "sequence decompositions are only currently available for " + "2d disks or 3d balls" + ) + precomputed_decompositions = _nsphere_decompositions[ndim] + max_radius = precomputed_decompositions.shape[0] + if radius > max_radius: + raise ValueError( + f"precomputed {ndim}D decomposition unavailable for " + f"radius > {max_radius}" + ) + num_t_series, num_diamond, num_square = precomputed_decompositions[radius] + + sequence = [] + if num_t_series > 0: + # shape (3,) * ndim "T-shaped" footprints + all_t = _t_shaped_element_series(ndim=ndim, dtype=dtype) + [sequence.append((t, num_t_series)) for t in all_t] + if num_diamond > 0: + d = np.zeros((3,) * ndim, dtype=dtype) + sl = [slice(1, 2)] * ndim + for ax in range(ndim): + sl[ax] = slice(None) + d[tuple(sl)] = 1 + sl[ax] = slice(1, 2) + sequence.append((d, num_diamond)) + if num_square > 0: + sq = np.ones((3,) * ndim, dtype=dtype) + sequence.append((sq, num_square)) + return tuple(sequence) + + +def _t_shaped_element_series(ndim=2, dtype=np.uint8): + """A series of T-shaped structuring elements. + + In the 2D case this is a T-shaped element and its rotation at multiples of + 90 degrees. This series is used in efficient decompositions of disks of + various radius as published in [1]_. + + The generalization to the n-dimensional case can be performed by having the + "top" of the T to extend in (ndim - 1) dimensions and then producing a + series of rotations such that the bottom end of the T points along each of + ``2 * ndim`` orthogonal directions. + """ + if ndim == 2: + # The n-dimensional case produces the same set of footprints, but + # the 2D example is retained here for clarity. + t0 = np.array([[1, 1, 1], [0, 1, 0], [0, 1, 0]], dtype=dtype) + t90 = np.rot90(t0, 1) + t180 = np.rot90(t0, 2) + t270 = np.rot90(t0, 3) + return t0, t90, t180, t270 + else: + # ndimensional generalization of the 2D case above + all_t = [] + for ax in range(ndim): + for idx in [0, 2]: + t = np.zeros((3,) * ndim, dtype=dtype) + sl = [slice(None)] * ndim + sl[ax] = slice(idx, idx + 1) + t[tuple(sl)] = 1 + sl = [slice(1, 2)] * ndim + sl[ax] = slice(None) + t[tuple(sl)] = 1 + all_t.append(t) + return tuple(all_t) + + +def disk(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None): + """Generates a flat, disk-shaped footprint. + + A pixel is within the neighborhood if the Euclidean distance between + it and the origin is no greater than radius (This is only approximately + True, when `decomposition == 'sequence'`). + + Parameters + ---------- + radius : int + The radius of the disk-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + strict_radius : bool, optional + If False, extend the radius by 0.5. This allows the circle to expand + further within a cube that remains of size ``2 * radius + 1`` along + each axis. This parameter is ignored if decomposition is not None. + decomposition : {None, 'sequence', 'crosses'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given a result equivalent to a single, larger footprint, but with + better computational performance. For disk footprints, the 'sequence' + or 'crosses' decompositions are not always exactly equivalent to + ``decomposition=None``. See Notes for more details. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + The disk produced by the ``decomposition='sequence'`` mode may not be + identical to that with ``decomposition=None``. A disk footprint can be + approximated by applying a series of smaller footprints of extent 3 along + each axis. Specific solutions for this are given in [1]_ for the case of + 2D disks with radius 2 through 10. Here, we numerically computed the number + of repetitions of each element that gives the closest match to the disk + computed with kwargs ``strict_radius=False, decomposition=None``. + + Empirically, the series decomposition at large radius approaches a + hexadecagon (a 16-sided polygon [2]_). In [3]_, the authors demonstrate + that a hexadecagon is the closest approximation to a disk that can be + achieved for decomposition with footprints of shape (3, 3). + + The disk produced by the ``decomposition='crosses'`` is often but not + always identical to that with ``decomposition=None``. It tends to give a + closer approximation than ``decomposition='sequence'``, at a performance + that is fairly comparable. The individual cross-shaped elements are not + limited to extent (3, 3) in size. Unlike the 'seqeuence' decomposition, the + 'crosses' decomposition can also accurately approximate the shape of disks + with ``strict_radius=True``. The method is based on an adaption of + algorithm 1 given in [4]_. + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Hexadecagon + .. [3] Vanrell, M and Vitrià, J. Optimal 3 × 3 decomposable disks for + morphological transformations. Image and Vision Computing, Vol. 15, + Issue 11, 1997. + :DOI:`10.1016/S0262-8856(97)00026-7` + .. [4] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + """ + if decomposition is None: + L = np.arange(-radius, radius + 1) + X, Y = np.meshgrid(L, L) + if not strict_radius: + radius += 0.5 + return np.array((X**2 + Y**2) <= radius**2, dtype=dtype) + elif decomposition == 'sequence': + sequence = _nsphere_series_decomposition(radius, ndim=2, dtype=dtype) + elif decomposition == 'crosses': + fp = disk(radius, dtype, strict_radius=strict_radius, decomposition=None) + sequence = _cross_decomposition(fp) + return sequence + + +def _cross(r0, r1, dtype=np.uint8): + """Cross-shaped structuring element of shape (r0, r1). + + Only the central row and column are ones. + """ + s0 = int(2 * r0 + 1) + s1 = int(2 * r1 + 1) + c = np.zeros((s0, s1), dtype=dtype) + if r1 != 0: + c[r0, :] = 1 + if r0 != 0: + c[:, r1] = 1 + return c + + +def _cross_decomposition(footprint, dtype=np.uint8): + """Decompose a symmetric convex footprint into cross-shaped elements. + + This is a decomposition of the footprint into a sequence of + (possibly asymmetric) cross-shaped elements. This technique was proposed in + [1]_ and corresponds roughly to algorithm 1 of that publication (some + details had to be modified to get reliable operation). + + .. [1] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + """ + quadrant = footprint[footprint.shape[0] // 2 :, footprint.shape[1] // 2 :] + col_sums = quadrant.sum(0, dtype=int) + col_sums = np.concatenate((col_sums, np.asarray([0], dtype=int))) + i_prev = 0 + idx = {} + sum0 = 0 + for i in range(col_sums.size - 1): + if col_sums[i] > col_sums[i + 1]: + if i == 0: + continue + key = (col_sums[i_prev] - col_sums[i], i - i_prev) + sum0 += key[0] + if key not in idx: + idx[key] = 1 + else: + idx[key] += 1 + i_prev = i + n = quadrant.shape[0] - 1 - sum0 + if n > 0: + key = (n, 0) + idx[key] = idx.get(key, 0) + 1 + return tuple([(_cross(r0, r1, dtype), n) for (r0, r1), n in idx.items()]) + + +def ellipse(width, height, dtype=np.uint8, *, decomposition=None): + """Generates a flat, ellipse-shaped footprint. + + Every pixel along the perimeter of ellipse satisfies + the equation ``(x/width+1)**2 + (y/height+1)**2 = 1``. + + Parameters + ---------- + width : int + The width of the ellipse-shaped footprint. + height : int + The height of the ellipse-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'crosses'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + The footprint will have shape ``(2 * height + 1, 2 * width + 1)``. + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + The ellipse produced by the ``decomposition='crosses'`` is often but not + always identical to that with ``decomposition=None``. The method is based + on an adaption of algorithm 1 given in [1]_. + + References + ---------- + .. [1] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric + Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological + Image Processing, (1 November 1990). + :DOI:`10.1117/12.23608` + + Examples + -------- + >>> from skimage.morphology import footprints + >>> footprints.ellipse(5, 3) + array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [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], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=uint8) + + """ + if decomposition is None: + footprint = np.zeros((2 * height + 1, 2 * width + 1), dtype=dtype) + rows, cols = draw.ellipse(height, width, height + 1, width + 1) + footprint[rows, cols] = 1 + return footprint + elif decomposition == 'crosses': + fp = ellipse(width, height, dtype, decomposition=None) + sequence = _cross_decomposition(fp) + return sequence + + +@deprecate_func( + deprecated_version="0.25", + removed_version="0.27", + hint="Use `skimage.morphology.footprint_rectangle` instead.", +) +def cube(width, dtype=np.uint8, *, decomposition=None): + """Generates a cube-shaped footprint. + + This is the 3D equivalent of a square. + Every pixel along the perimeter has a chessboard distance + no greater than radius (radius=floor(width/2)) pixels. + + Parameters + ---------- + width : int + The width, height and depth of the cube. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'separable', 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but often with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For binary morphology, using ``decomposition='sequence'`` + was observed to give better performance, with the magnitude of the + performance increase rapidly increasing with footprint size. For grayscale + morphology with square footprints, it is recommended to use + ``decomposition=None`` since the internal SciPy functions that are called + already have a fast implementation based on separable 1D sliding windows. + + The 'sequence' decomposition mode only supports odd valued `width`. If + `width` is even, the sequence used will be identical to the 'separable' + mode. + """ + footprint = footprint_rectangle( + shape=(width, width, width), dtype=dtype, decomposition=decomposition + ) + return footprint + + +def octahedron(radius, dtype=np.uint8, *, decomposition=None): + """Generates a octahedron-shaped footprint. + + This is the 3D equivalent of a diamond. + A pixel is part of the neighborhood (i.e. labeled 1) if + the city block/Manhattan distance between it and the center of + the neighborhood is no greater than radius. + + Parameters + ---------- + radius : int + The radius of the octahedron-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + """ + # note that in contrast to diamond(), this method allows non-integer radii + if decomposition is None: + n = 2 * radius + 1 + Z, Y, X = np.mgrid[ + -radius : radius : n * 1j, + -radius : radius : n * 1j, + -radius : radius : n * 1j, + ] + s = np.abs(X) + np.abs(Y) + np.abs(Z) + footprint = np.array(s <= radius, dtype=dtype) + elif decomposition == 'sequence': + fp = octahedron(1, dtype=dtype, decomposition=None) + nreps = _decompose_size(2 * radius + 1, fp.shape[0]) + footprint = ((fp, nreps),) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def ball(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None): + """Generates a ball-shaped footprint. + + This is the 3D equivalent of a disk. + A pixel is within the neighborhood if the Euclidean distance between + it and the origin is no greater than radius. + + Parameters + ---------- + radius : float + The radius of the ball-shaped footprint. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + strict_radius : bool, optional + If False, extend the radius by 0.5. This allows the circle to expand + further within a cube that remains of size ``2 * radius + 1`` along + each axis. This parameter is ignored if decomposition is not None. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given a result equivalent to a single, larger footprint, but with + better computational performance. For ball footprints, the sequence + decomposition is not exactly equivalent to decomposition=None. + See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + Notes + ----- + The disk produced by the decomposition='sequence' mode is not identical + to that with decomposition=None. Here we extend the approach taken in [1]_ + for disks to the 3D case, using 3-dimensional extensions of the "square", + "diamond" and "t-shaped" elements from that publication. All of these + elementary elements have size ``(3,) * ndim``. We numerically computed the + number of repetitions of each element that gives the closest match to the + ball computed with kwargs ``strict_radius=False, decomposition=None``. + + Empirically, the equivalent composite footprint to the sequence + decomposition approaches a rhombicuboctahedron (26-faces [2]_). + + References + ---------- + .. [1] Park, H and Chin R.T. Decomposition of structuring elements for + optimal implementation of morphological operations. In Proceedings: + 1997 IEEE Workshop on Nonlinear Signal and Image Processing, London, + UK. + https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf + .. [2] https://en.wikipedia.org/wiki/Rhombicuboctahedron + """ + if decomposition is None: + n = 2 * radius + 1 + Z, Y, X = np.mgrid[ + -radius : radius : n * 1j, + -radius : radius : n * 1j, + -radius : radius : n * 1j, + ] + s = X**2 + Y**2 + Z**2 + if not strict_radius: + radius += 0.5 + return np.array(s <= radius * radius, dtype=dtype) + elif decomposition == 'sequence': + sequence = _nsphere_series_decomposition(radius, ndim=3, dtype=dtype) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return sequence + + +def octagon(m, n, dtype=np.uint8, *, decomposition=None): + """Generates an octagon shaped footprint. + + For a given size of (m) horizontal and vertical sides + and a given (n) height or width of slanted sides octagon is generated. + The slanted sides are 45 or 135 degrees to the horizontal axis + and hence the widths and heights are equal. The overall size of the + footprint along a single axis will be ``m + 2 * n``. + + Parameters + ---------- + m : int + The size of the horizontal and vertical sides. + n : int + The height or width of the slanted sides. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + decomposition : {None, 'sequence'}, optional + If None, a single array is returned. For 'sequence', a tuple of smaller + footprints is returned. Applying this series of smaller footprints will + given an identical result to a single, larger footprint, but with + better computational performance. See Notes for more details. + + Returns + ------- + footprint : ndarray or tuple + The footprint where elements of the neighborhood are 1 and 0 otherwise. + When `decomposition` is None, this is just a numpy.ndarray. Otherwise, + this will be a tuple whose length is equal to the number of unique + structuring elements to apply (see Notes for more detail) + + Notes + ----- + When `decomposition` is not None, each element of the `footprint` + tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a + footprint array and the number of iterations it is to be applied. + + For either binary or grayscale morphology, using + ``decomposition='sequence'`` was observed to have a performance benefit, + with the magnitude of the benefit increasing with increasing footprint + size. + """ + if m == n == 0: + raise ValueError("m and n cannot both be zero") + + # TODO?: warn about even footprint size when m is even + + if decomposition is None: + from . import convex_hull_image + + footprint = np.zeros((m + 2 * n, m + 2 * n)) + footprint[0, n] = 1 + footprint[n, 0] = 1 + footprint[0, m + n - 1] = 1 + footprint[m + n - 1, 0] = 1 + footprint[-1, n] = 1 + footprint[n, -1] = 1 + footprint[-1, m + n - 1] = 1 + footprint[m + n - 1, -1] = 1 + footprint = convex_hull_image(footprint).astype(dtype) + elif decomposition == 'sequence': + # special handling for edge cases with small m and/or n + if m <= 2 and n <= 2: + return ((octagon(m, n, dtype=dtype, decomposition=None), 1),) + + # general approach for larger m and/or n + if m == 0: + m = 2 + n -= 1 + sequence = [] + if m > 1: + sequence += list( + footprint_rectangle((m, m), dtype=dtype, decomposition='sequence') + ) + if n > 0: + sequence += [(diamond(1, dtype=dtype, decomposition=None), n)] + footprint = tuple(sequence) + else: + raise ValueError(f"Unrecognized decomposition: {decomposition}") + return footprint + + +def star(a, dtype=np.uint8): + """Generates a star shaped footprint. + + Start has 8 vertices and is an overlap of square of size `2*a + 1` + with its 45 degree rotated version. + The slanted sides are 45 or 135 degrees to the horizontal axis. + + Parameters + ---------- + a : int + Parameter deciding the size of the star structural element. The side + of the square array returned is `2*a + 1 + 2*floor(a / 2)`. + + Other Parameters + ---------------- + dtype : data-type, optional + The data type of the footprint. + + Returns + ------- + footprint : ndarray + The footprint where elements of the neighborhood are 1 and 0 otherwise. + + """ + from . import convex_hull_image + + if a == 1: + bfilter = np.zeros((3, 3), dtype) + bfilter[:] = 1 + return bfilter + + m = 2 * a + 1 + n = a // 2 + footprint_square = np.zeros((m + 2 * n, m + 2 * n)) + footprint_square[n : m + n, n : m + n] = 1 + + c = (m + 2 * n - 1) // 2 + footprint_rotated = np.zeros((m + 2 * n, m + 2 * n)) + footprint_rotated[0, c] = footprint_rotated[-1, c] = 1 + footprint_rotated[c, 0] = footprint_rotated[c, -1] = 1 + footprint_rotated = convex_hull_image(footprint_rotated).astype(int) + + footprint = footprint_square + footprint_rotated + footprint[footprint > 0] = 1 + + return footprint.astype(dtype) + + +def mirror_footprint(footprint): + """Mirror each dimension in the footprint. + + Parameters + ---------- + footprint : ndarray or tuple + The input footprint or sequence of footprints + + Returns + ------- + inverted : ndarray or tuple + The footprint, mirrored along each dimension. + + Examples + -------- + >>> footprint = np.array([[0, 0, 0], + ... [0, 1, 1], + ... [0, 1, 1]], np.uint8) + >>> mirror_footprint(footprint) + array([[1, 1, 0], + [1, 1, 0], + [0, 0, 0]], dtype=uint8) + + """ + if _footprint_is_sequence(footprint): + return tuple((mirror_footprint(fp), n) for fp, n in footprint) + footprint = np.asarray(footprint) + return footprint[(slice(None, None, -1),) * footprint.ndim] + + +def pad_footprint(footprint, *, pad_end=True): + """Pad the footprint to an odd size along each dimension. + + Parameters + ---------- + footprint : ndarray or tuple + The input footprint or sequence of footprints + pad_end : bool, optional + If ``True``, pads at the end of each dimension (right side), otherwise + pads on the front (left side). + + Returns + ------- + padded : ndarray or tuple + The footprint, padded to an odd size along each dimension. + + Examples + -------- + >>> footprint = np.array([[0, 0], + ... [1, 1], + ... [1, 1]], np.uint8) + >>> pad_footprint(footprint) + array([[0, 0, 0], + [1, 1, 0], + [1, 1, 0]], dtype=uint8) + + """ + if _footprint_is_sequence(footprint): + return tuple((pad_footprint(fp, pad_end=pad_end), n) for fp, n in footprint) + footprint = np.asarray(footprint) + padding = [] + for sz in footprint.shape: + padding.append(((0, 1) if pad_end else (1, 0)) if sz % 2 == 0 else (0, 0)) + return np.pad(footprint, padding) diff --git a/envs/kitoverlay/skimage/morphology/gray.py b/envs/kitoverlay/skimage/morphology/gray.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2c99dc09244629083415eb8ecfc320c9fafdf2 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/gray.py @@ -0,0 +1,624 @@ +""" +Grayscale morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + +from .footprints import _footprint_is_sequence, mirror_footprint, pad_footprint +from .misc import default_footprint + + +__all__ = ['erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat'] + + +def _iterate_gray_func(gray_func, image, footprints, out, mode, cval): + """Helper to call `gray_func` for each footprint in a sequence. + + `gray_func` is a morphology function that accepts `footprint`, `output`, + `mode` and `cval` keyword arguments (e.g. `scipy.ndimage.grey_erosion`). + """ + fp, num_iter = footprints[0] + gray_func(image, footprint=fp, output=out, mode=mode, cval=cval) + for _ in range(1, num_iter): + gray_func(out.copy(), footprint=fp, output=out, mode=mode, cval=cval) + for fp, num_iter in footprints[1:]: + # Note: out.copy() because the computation cannot be in-place! + for _ in range(num_iter): + gray_func(out.copy(), footprint=fp, output=out, mode=mode, cval=cval) + return out + + +def _min_max_to_constant_mode(dtype, mode, cval): + """Replace 'max' and 'min' with appropriate 'cval' and 'constant' mode.""" + if mode == "max": + mode = "constant" + if np.issubdtype(dtype, bool): + cval = True + elif np.issubdtype(dtype, np.integer): + cval = np.iinfo(dtype).max + else: + cval = np.inf + elif mode == "min": + mode = "constant" + if np.issubdtype(dtype, bool): + cval = False + elif np.issubdtype(dtype, np.integer): + cval = np.iinfo(dtype).min + else: + cval = -np.inf + return mode, cval + + +_SUPPORTED_MODES = { + "reflect", + "constant", + "nearest", + "mirror", + "wrap", + "max", + "min", + "ignore", +} + + +@default_footprint +def erosion( + image, + footprint=None, + out=None, + *, + mode="reflect", + cval=0.0, +): + """Return grayscale morphological erosion of an image. + + Morphological erosion sets a pixel at (i,j) to the minimum over all pixels + in the neighborhood centered at (i,j). Erosion shrinks bright regions and + enlarges dark regions. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarrays, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'max' or 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype, which causes them to not + influence the result. Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + eroded : array, same shape as `image` + The result of the morphological erosion. + + Notes + ----- + For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the + lower algorithm complexity makes the :func:`skimage.filters.rank.minimum` + function more efficient for larger images and footprints. + + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + For even-sized footprints, :func:`skimage.morphology.binary_erosion` and + this function produce an output that differs: one is shifted by one pixel + compared to the other. :func:`skimage.morphology.pad_footprint` is available + to account for this. + + Examples + -------- + >>> # Erosion shrinks bright regions + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bright_square = np.array([[0, 0, 0, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> erosion(bright_square, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + if out is None: + out = np.empty_like(image) + + if mode not in _SUPPORTED_MODES: + raise ValueError(f"unsupported mode, got {mode!r}") + if mode == "ignore": + mode = "max" + mode, cval = _min_max_to_constant_mode(image.dtype, mode, cval) + + footprint = pad_footprint(footprint, pad_end=False) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_gray_func( + gray_func=ndi.grey_erosion, + image=image, + footprints=footprint, + out=out, + mode=mode, + cval=cval, + ) + return out + + +@default_footprint +def dilation( + image, + footprint=None, + out=None, + *, + mode="reflect", + cval=0.0, +): + """Return grayscale morphological dilation of an image. + + Morphological dilation sets the value of a pixel to the maximum over all + pixel values within a local neighborhood centered about it. The values + where the footprint is 1 define this neighborhood. + Dilation enlarges bright regions and shrinks dark regions. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'min' or 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype, which causes them to not + influence the result. Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + dilated : uint8 array, same shape and type as `image` + The result of the morphological dilation. + + Notes + ----- + For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the lower + algorithm complexity makes the :func:`skimage.filters.rank.maximum` + function more efficient for larger images and footprints. + + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + For non-symmetric footprints, :func:`skimage.morphology.binary_dilation` + and :func:`skimage.morphology.dilation` produce an output that differs: + `binary_dilation` mirrors the footprint, whereas `dilation` does not. + :func:`skimage.morphology.mirror_footprint` is available to correct for this. + + Examples + -------- + >>> # Dilation enlarges bright regions + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bright_pixel = np.array([[0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0], + ... [0, 0, 1, 0, 0], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> dilation(bright_pixel, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + if out is None: + out = np.empty_like(image) + + if mode not in _SUPPORTED_MODES: + raise ValueError(f"unsupported mode, got {mode!r}") + if mode == "ignore": + mode = "min" + mode, cval = _min_max_to_constant_mode(image.dtype, mode, cval) + + footprint = pad_footprint(footprint, pad_end=False) + # Note that `ndi.grey_dilation` mirrors the footprint and this + # additional inversion should be removed in skimage2, see gh-6676. + footprint = mirror_footprint(footprint) + if not _footprint_is_sequence(footprint): + footprint = [(footprint, 1)] + + out = _iterate_gray_func( + gray_func=ndi.grey_dilation, + image=image, + footprints=footprint, + out=out, + mode=mode, + cval=cval, + ) + return out + + +@default_footprint +def opening(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return grayscale morphological opening of an image. + + The morphological opening of an image is defined as an erosion followed by + a dilation. Opening can remove small bright spots (i.e. "salt") and connect + small dark cracks. This tends to "open" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype in the erosion, and minimum + in the dilation, which causes them to not influence the result. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + opening : array, same shape and type as `image` + The result of the morphological opening. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + Examples + -------- + >>> # Open up gap between two bright regions (but also shrink regions) + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bad_connection = np.array([[1, 0, 0, 0, 1], + ... [1, 1, 0, 1, 1], + ... [1, 1, 1, 1, 1], + ... [1, 1, 0, 1, 1], + ... [1, 0, 0, 0, 1]], dtype=np.uint8) + >>> opening(bad_connection, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [1, 1, 0, 1, 1], + [1, 1, 0, 1, 1], + [1, 1, 0, 1, 1], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + footprint = pad_footprint(footprint, pad_end=False) + eroded = erosion(image, footprint, mode=mode, cval=cval) + out = dilation(eroded, mirror_footprint(footprint), out=out, mode=mode, cval=cval) + return out + + +@default_footprint +def closing(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return grayscale morphological closing of an image. + + The morphological closing of an image is defined as a dilation followed by + an erosion. Closing can remove small dark spots (i.e. "pepper") and connect + small bright cracks. This tends to "close" up (dark) gaps between (bright) + features. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None, + a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. + If 'ignore', pixels outside the image domain are assumed + to be the maximum for the image's dtype in the erosion, and minimum + in the dilation, which causes them to not influence the result. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + closing : array, same shape and type as `image` + The result of the morphological closing. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + Examples + -------- + >>> # Close a gap between two bright lines + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> broken_line = np.array([[0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0], + ... [1, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0]], dtype=np.uint8) + >>> closing(broken_line, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + footprint = pad_footprint(footprint, pad_end=False) + dilated = dilation(image, footprint, mode=mode, cval=cval) + out = erosion(dilated, mirror_footprint(footprint), out=out, mode=mode, cval=cval) + return out + + +@default_footprint +def white_tophat(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return white top hat of an image. + + The white top hat of an image is defined as the image minus its + morphological opening. This operation returns the bright spots of the image + that are smaller than the footprint. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. See :func:`skimage.morphology.opening`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + out : array, same shape and type as `image` + The result of the morphological white top hat. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + See Also + -------- + black_tophat + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Top-hat_transform + + Examples + -------- + >>> # Subtract gray background from bright peak + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> bright_on_gray = np.array([[2, 3, 3, 3, 2], + ... [3, 4, 5, 4, 3], + ... [3, 5, 9, 5, 3], + ... [3, 4, 5, 4, 3], + ... [2, 3, 3, 3, 2]], dtype=np.uint8) + >>> white_tophat(bright_on_gray, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + if out is image: + # We need a temporary image + opened = opening(image, footprint, mode=mode, cval=cval) + if np.issubdtype(opened.dtype, bool): + np.logical_xor(out, opened, out=out) + else: + out -= opened + return out + + # Else write intermediate result into output image + out = opening(image, footprint, out=out, mode=mode, cval=cval) + if np.issubdtype(out.dtype, bool): + np.logical_xor(image, out, out=out) + else: + np.subtract(image, out, out=out) + return out + + +@default_footprint +def black_tophat(image, footprint=None, out=None, *, mode="reflect", cval=0.0): + """Return black top hat of an image. + + The black top hat of an image is defined as its morphological closing minus + the original image. This operation returns the dark spots of the image that + are smaller than the footprint. Note that dark spots in the + original image are bright spots after the black top hat. + + Parameters + ---------- + image : ndarray + Image array. + footprint : ndarray or tuple, optional + The neighborhood expressed as a 2-D array of 1's and 0's. + If None, use a cross-shaped footprint (connectivity=1). The footprint + can also be provided as a sequence of smaller footprints as described + in the notes below. + out : ndarray, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + mode : str, optional + The `mode` parameter determines how the array borders are handled. + Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap', + 'max', 'min', or 'ignore'. See :func:`skimage.morphology.closing`. + Default is 'reflect'. + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0. + + .. versionadded:: 0.23 + `mode` and `cval` were added in 0.23. + + Returns + ------- + out : array, same shape and type as `image` + The result of the morphological black top hat. + + Notes + ----- + The footprint can also be a provided as a sequence of 2-tuples where the + first element of each 2-tuple is a footprint ndarray and the second element + is an integer describing the number of times it should be iterated. For + example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]`` + would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net + effect that is the same as ``footprint=np.ones((9, 9))``, but with lower + computational cost. Most of the builtin footprints such as + :func:`skimage.morphology.disk` provide an option to automatically generate + a footprint sequence of this type. + + See Also + -------- + white_tophat + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Top-hat_transform + + Examples + -------- + >>> # Change dark peak to bright peak and subtract background + >>> import numpy as np + >>> from skimage.morphology import footprint_rectangle + >>> dark_on_gray = np.array([[7, 6, 6, 6, 7], + ... [6, 5, 4, 5, 6], + ... [6, 4, 0, 4, 6], + ... [6, 5, 4, 5, 6], + ... [7, 6, 6, 6, 7]], dtype=np.uint8) + >>> black_tophat(dark_on_gray, footprint_rectangle((3, 3))) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 5, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + + """ + if out is image: + # We need a temporary image + closed = closing(image, footprint, mode=mode, cval=cval) + if np.issubdtype(closed.dtype, bool): + np.logical_xor(closed, out, out=out) + else: + np.subtract(closed, out, out=out) + return out + + out = closing(image, footprint, out=out, mode=mode, cval=cval) + if np.issubdtype(out.dtype, np.bool_): + np.logical_xor(out, image, out=out) + else: + out -= image + return out diff --git a/envs/kitoverlay/skimage/morphology/grayreconstruct.py b/envs/kitoverlay/skimage/morphology/grayreconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..e924fab6c8a347b5d5e061b5bb5b056f11c2d1a2 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/grayreconstruct.py @@ -0,0 +1,217 @@ +import numpy as np + +from .._shared.utils import _supported_float_type +from ..filters._rank_order import rank_order +from ._grayreconstruct import reconstruction_loop + + +def reconstruction(seed, mask, method='dilation', footprint=None, offset=None): + """Perform a morphological reconstruction of an image. + + Morphological reconstruction by dilation is similar to basic morphological + dilation: high-intensity values will replace nearby low-intensity values. + The basic dilation operator, however, uses a footprint to + determine how far a value in the input image can spread. In contrast, + reconstruction uses two images: a "seed" image, which specifies the values + that spread, and a "mask" image, which gives the maximum allowed value at + each pixel. The mask image, like the footprint, limits the spread + of high-intensity values. Reconstruction by erosion is simply the inverse: + low-intensity values spread from the seed image and are limited by the mask + image, which represents the minimum allowed value. + + Alternatively, you can think of reconstruction as a way to isolate the + connected regions of an image. For dilation, reconstruction connects + regions marked by local maxima in the seed image: neighboring pixels + less-than-or-equal-to those seeds are connected to the seeded region. + Local maxima with values larger than the seed image will get truncated to + the seed value. + + Parameters + ---------- + seed : ndarray + The seed image (a.k.a. marker image), which specifies the values that + are dilated or eroded. + mask : ndarray + The maximum (dilation) / minimum (erosion) allowed value at each pixel. + method : {'dilation'|'erosion'}, optional + Perform reconstruction by dilation or erosion. In dilation (or + erosion), the seed image is dilated (or eroded) until limited by the + mask image. For dilation, each seed value must be less than or equal + to the corresponding mask value; for erosion, the reverse is true. + Default is 'dilation'. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the n-D square of radius equal to 1 (i.e. a 3x3 square + for 2D images, a 3x3x3 cube for 3D images, etc.) + offset : ndarray, optional + The coordinates of the center of the footprint. + Default is located on the geometrical center of the footprint, in that + case footprint dimensions must be odd. + + Returns + ------- + reconstructed : ndarray + The result of morphological reconstruction. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import reconstruction + + First, we create a sinusoidal mask image with peaks at middle and ends. + + >>> x = np.linspace(0, 4 * np.pi) + >>> y_mask = np.cos(x) + + Then, we create a seed image initialized to the minimum mask value (for + reconstruction by dilation, min-intensity values don't spread) and add + "seeds" to the left and right peak, but at a fraction of peak value (1). + + >>> y_seed = y_mask.min() * np.ones_like(x) + >>> y_seed[0] = 0.5 + >>> y_seed[-1] = 0 + >>> y_rec = reconstruction(y_seed, y_mask) + + The reconstructed image (or curve, in this case) is exactly the same as the + mask image, except that the peaks are truncated to 0.5 and 0. The middle + peak disappears completely: Since there were no seed values in this peak + region, its reconstructed value is truncated to the surrounding value (-1). + + As a more practical example, we try to extract the bright features of an + image by subtracting a background image created by reconstruction. + + >>> y, x = np.mgrid[:20:0.5, :20:0.5] + >>> bumps = np.sin(x) + np.sin(y) + + To create the background image, set the mask image to the original image, + and the seed image to the original image with an intensity offset, `h`. + + >>> h = 0.3 + >>> seed = bumps - h + >>> background = reconstruction(seed, bumps) + + The resulting reconstructed image looks exactly like the original image, + but with the peaks of the bumps cut off. Subtracting this reconstructed + image from the original image leaves just the peaks of the bumps + + >>> hdome = bumps - background + + This operation is known as the h-dome of the image and leaves features + of height `h` in the subtracted image. + + Notes + ----- + The algorithm is taken from [1]_. Applications for grayscale reconstruction + are discussed in [2]_ and [3]_. + + References + ---------- + .. [1] Robinson, "Efficient morphological reconstruction: a downhill + filter", Pattern Recognition Letters 25 (2004) 1759-1767. + .. [2] Vincent, L., "Morphological Grayscale Reconstruction in Image + Analysis: Applications and Efficient Algorithms", IEEE Transactions + on Image Processing (1993) + .. [3] Soille, P., "Morphological Image Analysis: Principles and + Applications", Chapter 6, 2nd edition (2003), ISBN 3540429883. + """ + assert tuple(seed.shape) == tuple(mask.shape) + if method == 'dilation' and np.any(seed > mask): + raise ValueError( + "Intensity of seed image must be less than that " + "of the mask image for reconstruction by dilation." + ) + elif method == 'erosion' and np.any(seed < mask): + raise ValueError( + "Intensity of seed image must be greater than that " + "of the mask image for reconstruction by erosion." + ) + + if footprint is None: + footprint = np.ones([3] * seed.ndim, dtype=bool) + else: + footprint = footprint.astype(bool, copy=True) + + if offset is None: + if not all([d % 2 == 1 for d in footprint.shape]): + raise ValueError("Footprint dimensions must all be odd") + offset = np.array([d // 2 for d in footprint.shape]) + else: + if offset.ndim != footprint.ndim: + raise ValueError("Offset and footprint ndims must be equal.") + if not all([(0 <= o < d) for o, d in zip(offset, footprint.shape)]): + raise ValueError("Offset must be included inside footprint") + + # Cross out the center of the footprint + footprint[tuple(slice(d, d + 1) for d in offset)] = False + + # Make padding for edges of reconstructed image so we can ignore boundaries + dims = np.zeros(seed.ndim + 1, dtype=int) + dims[1:] = np.array(seed.shape) + (np.array(footprint.shape) - 1) + dims[0] = 2 + inside_slices = tuple(slice(o, o + s) for o, s in zip(offset, seed.shape)) + # Set padded region to minimum image intensity and mask along first axis so + # we can interleave image and mask pixels when sorting. + if method == 'dilation': + pad_value = np.min(seed) + elif method == 'erosion': + pad_value = np.max(seed) + else: + raise ValueError( + "Reconstruction method can be one of 'erosion' " + f"or 'dilation'. Got '{method}'." + ) + float_dtype = _supported_float_type(mask.dtype) + images = np.full(dims, pad_value, dtype=float_dtype) + images[(0, *inside_slices)] = seed + images[(1, *inside_slices)] = mask + + # determine whether image is large enough to require 64-bit integers + isize = images.size + # use -isize so we get a signed dtype rather than an unsigned one + signed_int_dtype = np.result_type(np.min_scalar_type(-isize), np.int32) + # the corresponding unsigned type has same char, but uppercase + unsigned_int_dtype = np.dtype(signed_int_dtype.char.upper()) + + # Create a list of strides across the array to get the neighbors within + # a flattened array + value_stride = np.array(images.strides[1:]) // images.dtype.itemsize + image_stride = images.strides[0] // images.dtype.itemsize + footprint_mgrid = np.mgrid[ + [slice(-o, d - o) for d, o in zip(footprint.shape, offset)] + ] + footprint_offsets = footprint_mgrid[:, footprint].transpose() + nb_strides = np.array( + [ + np.sum(value_stride * footprint_offset) + for footprint_offset in footprint_offsets + ], + signed_int_dtype, + ) + images = images.reshape(-1) + + # Erosion goes smallest to largest; dilation goes largest to smallest. + index_sorted = np.argsort(images).astype(signed_int_dtype, copy=False) + if method == 'dilation': + index_sorted = index_sorted[::-1] + + # Make a linked list of pixels sorted by value. -1 is the list terminator. + prev = np.full(isize, -1, signed_int_dtype) + next = np.full(isize, -1, signed_int_dtype) + prev[index_sorted[1:]] = index_sorted[:-1] + next[index_sorted[:-1]] = index_sorted[1:] + + # Cython inner-loop compares the rank of pixel values. + if method == 'dilation': + value_rank, value_map = rank_order(images) + elif method == 'erosion': + value_rank, value_map = rank_order(-images) + value_map = -value_map + + start = index_sorted[0] + value_rank = value_rank.astype(unsigned_int_dtype, copy=False) + reconstruction_loop(value_rank, prev, next, nb_strides, start, image_stride) + + # Reshape reconstructed image to original image shape and remove padding. + rec_img = value_map[value_rank[:image_stride]] + rec_img.shape = np.array(seed.shape) + (np.array(footprint.shape) - 1) + return rec_img[inside_slices] diff --git a/envs/kitoverlay/skimage/morphology/isotropic.py b/envs/kitoverlay/skimage/morphology/isotropic.py new file mode 100644 index 0000000000000000000000000000000000000000..c4777f592c6e4b6b2d9fd4e95cd09329e966e5b2 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/isotropic.py @@ -0,0 +1,274 @@ +""" +Binary morphological operations +""" + +import numpy as np +from scipy import ndimage as ndi + + +def isotropic_erosion(image, radius, out=None, spacing=None): + """Return binary morphological erosion of an image. + + Compared to the more general :func:`skimage.morphology.erosion`, this + function only supports binary inputs and circular footprints. + However, it performs typically faster for large (circular) footprints. + This works by applying a threshold to the exact Euclidean distance map + of the image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius of the footprint used for the operation. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + eroded : ndarray of bool + The result of the morphological erosion taking values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + + Examples + -------- + Erosion shrinks bright regions + + >>> import numpy as np + >>> import skimage as ski + >>> image = np.array([[0, 0, 1, 0, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=bool) + >>> result = ski.morphology.isotropic_erosion(image, radius=1) + >>> result.view(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + """ + + dist = ndi.distance_transform_edt(image, sampling=spacing) + return np.greater(dist, radius, out=out) + + +def isotropic_dilation(image, radius, out=None, spacing=None): + """Return binary morphological dilation of an image. + + Compared to the more general :func:`skimage.morphology.dilation`, this + function only supports binary inputs and circular footprints. + However, it performs typically faster for large (circular) footprints. + This works by applying a threshold to the exact Euclidean distance map + of the inverted image [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius of the footprint used for the operation. + out : ndarray of bool, optional + The array to store the result of the morphology. If None is + passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + dilated : ndarray of bool + The result of the morphological dilation with values in + ``[False, True]``. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + + Examples + -------- + Dilation enlarges bright regions + + >>> import numpy as np + >>> import skimage as ski + >>> image = np.array([[0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0], + ... [0, 0, 1, 0, 0], + ... [0, 0, 1, 1, 0], + ... [0, 0, 0, 0, 0]], dtype=bool) + >>> result = ski.morphology.isotropic_dilation(image, radius=1) + >>> result.view(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 1], + [0, 0, 1, 1, 0]], dtype=uint8) + """ + + dist = ndi.distance_transform_edt(np.logical_not(image), sampling=spacing) + return np.less_equal(dist, radius, out=out) + + +def isotropic_opening(image, radius, out=None, spacing=None): + """Return binary morphological opening of an image. + + Compared to the more general :func:`skimage.morphology.opening`, this + function only supports binary inputs and circular footprints. + However, it performs typically faster for large (circular) footprints. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius of the footprint used for the operation. + out : ndarray of bool, optional + The array to store the result of the morphology. If None + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + opened : ndarray of bool + The result of the morphological opening. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + + Examples + -------- + Remove connection between two bright regions + + >>> import numpy as np + >>> import skimage as ski + >>> image = np.array([[1, 0, 0, 0, 1], + ... [1, 1, 0, 1, 1], + ... [1, 1, 1, 1, 1], + ... [1, 1, 0, 1, 1], + ... [1, 0, 0, 0, 1]], dtype=bool) + >>> result = ski.morphology.isotropic_opening(image, radius=1) + >>> result.view(np.uint8) + array([[1, 0, 0, 0, 1], + [1, 1, 0, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 0, 1, 1], + [1, 0, 0, 0, 1]], dtype=uint8) + """ + + eroded = isotropic_erosion(image, radius, out=out, spacing=spacing) + return isotropic_dilation(eroded, radius, out=out, spacing=spacing) + + +def isotropic_closing(image, radius, out=None, spacing=None): + """Return binary morphological closing of an image. + + Compared to the more general :func:`skimage.morphology.closing`, this + function only supports binary inputs and circular footprints. + However, it performs typically faster for large (circular) footprints. + This works by thresholding the exact Euclidean distance map [1]_, [2]_. + The implementation is based on: func:`scipy.ndimage.distance_transform_edt`. + + Parameters + ---------- + image : ndarray + Binary input image. + radius : float + The radius of the footprint used for the operation. + out : ndarray of bool, optional + The array to store the result of the morphology. If None, + is passed, a new array will be allocated. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. + If a sequence, must be of length equal to the input's dimension (number of axes). + If a single number, this value is used for all axes. + If not specified, a grid spacing of unity is implied. + + Returns + ------- + closed : ndarray of bool + The result of the morphological closing. + + References + ---------- + .. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators + using local distance transformation by propagation, and applications," + Image Processing And Its Applications, 1999. Seventh International + Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2. + :DOI:`10.1049/cp:19990446` + + .. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing + and thresholding of distance maps, Pattern Recognition Letters, + Volume 13, Issue 3, 1992, Pages 161-166. + :DOI:`10.1016/0167-8655(92)90055-5` + + Examples + -------- + Close gap between two bright lines + + >>> import numpy as np + >>> import skimage as ski + >>> image = np.array([[0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0], + ... [1, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0]], dtype=bool) + >>> result = ski.morphology.isotropic_closing(image, radius=1) + >>> result.view(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [1, 1, 0, 1, 1], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + """ + + dilated = isotropic_dilation(image, radius, out=out, spacing=spacing) + return isotropic_erosion(dilated, radius, out=out, spacing=spacing) diff --git a/envs/kitoverlay/skimage/morphology/max_tree.py b/envs/kitoverlay/skimage/morphology/max_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..d385b0e4d13c4e570d928371665864939d1dfa03 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/max_tree.py @@ -0,0 +1,700 @@ +"""max_tree.py - max_tree representation of images. + +This module provides operators based on the max-tree representation of images. +A grayscale image can be seen as a pile of nested sets, each of which is the +result of a threshold operation. These sets can be efficiently represented by +max-trees, where the inclusion relation between connected components at +different levels are represented by parent-child relationships. + +These representations allow efficient implementations of many algorithms, such +as attribute operators. Unlike morphological openings and closings, these +operators do not require a fixed footprint, but rather act with a flexible +footprint that meets a certain criterion. + +This implementation provides functions for: +1. max-tree generation +2. area openings / closings +3. diameter openings / closings +4. local maxima + +References: + .. [1] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [2] Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., + Bertin, E. (2007). Effective Component Tree Computation with + Application to Pattern Recognition in Astronomical Imaging. + In International Conference on Image Processing (ICIP) (pp. 41-44). + :DOI:`10.1109/ICIP.2007.4379949` + .. [3] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [4] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` +""" + +import numpy as np + +from ._util import _validate_connectivity, _offsets_to_raveled_neighbors +from ..util import invert + +from . import _max_tree + +unsigned_int_types = [np.uint8, np.uint16, np.uint32, np.uint64] +signed_int_types = [np.int8, np.int16, np.int32, np.int64] +signed_float_types = [np.float16, np.float32, np.float64] + + +# building the max tree. +def max_tree(image, connectivity=1): + """Build the max tree from an image. + + Component trees represent the hierarchical structure of the connected + components resulting from sequential thresholding operations applied to an + image. A connected component at one level is parent of a component at a + higher level if the latter is included in the first. A max-tree is an + efficient representation of a component tree. A connected component at + one level is represented by one reference pixel at this level, which is + parent to all other pixels at that level and to the reference pixel at the + level above. The max-tree is the basis for many morphological operators, + namely connected operators. + + Parameters + ---------- + image : ndarray + The input image for which the max-tree is to be calculated. + This image can be of any type. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + + Returns + ------- + parent : ndarray, int64 + Array of same shape as image. The value of each pixel is the index of + its parent in the ravelled array. + tree_traverser : 1D array, int64 + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + References + ---------- + .. [1] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [2] Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., + Bertin, E. (2007). Effective Component Tree Computation with + Application to Pattern Recognition in Astronomical Imaging. + In International Conference on Image Processing (ICIP) (pp. 41-44). + :DOI:`10.1109/ICIP.2007.4379949` + .. [3] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [4] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create a small sample image (Figure 1 from [4]) and build the max-tree. + + >>> image = np.array([[15, 13, 16], [12, 12, 10], [16, 12, 14]]) + >>> P, S = max_tree(image, connectivity=2) + """ + # User defined masks are not allowed, as there might be more than one + # connected component in the mask (and therefore not a single tree that + # represents the image). Mask here is an image that is 0 on the border + # and 1 everywhere else. + mask = np.ones(image.shape) + for k in range(len(image.shape)): + np.moveaxis(mask, k, 0)[0] = 0 + np.moveaxis(mask, k, 0)[-1] = 0 + + neighbors, offset = _validate_connectivity(image.ndim, connectivity, offset=None) + + # initialization of the parent image + parent = np.zeros(image.shape, dtype=np.int64) + + # flat_neighborhood contains a list of offsets allowing one to find the + # neighbors in the ravelled image. + flat_neighborhood = _offsets_to_raveled_neighbors( + image.shape, neighbors, offset + ).astype(np.int32) + + # pixels need to be sorted according to their gray level. + tree_traverser = np.argsort(image.ravel(), kind="stable").astype(np.int64) + + # call of cython function. + _max_tree._max_tree( + image.ravel(), + mask.ravel().astype(np.uint8), + flat_neighborhood, + offset.astype(np.int32), + np.array(image.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + return parent, tree_traverser + + +def area_opening( + image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None +): + """Perform an area opening of the image. + + Area opening removes all bright structures of an image with + a surface smaller than area_threshold. + The output image is thus the largest image smaller than the input + for which all local maxima have at least a surface of + area_threshold pixels. + + Area openings are similar to morphological openings, but + they do not use a fixed footprint, but rather a deformable + one, with surface = area_threshold. Consequently, the area_opening + with area_threshold=1 is the identity. + + In the binary case, area openings are equivalent to + remove_small_objects; this operator is thus extended to gray-level images. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_opening is to be calculated. + This image can be of any type. + area_threshold : unsigned int + The size parameter (number of pixels). The default value is arbitrarily + chosen to be 64. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the image. The + value of each pixel is the index of its parent in the ravelled array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as the input image. + + See Also + -------- + skimage.morphology.area_closing + skimage.morphology.diameter_opening + skimage.morphology.diameter_closing + skimage.morphology.max_tree + skimage.morphology.remove_small_objects + skimage.morphology.remove_small_holes + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional local maxima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the area opening: + + >>> open = area_opening(f, 8, connectivity=1) + + The peaks with a surface smaller than 8 are removed. + """ + output = image.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + area = _max_tree._compute_area(image.ravel(), parent.ravel(), tree_traverser) + + _max_tree._direct_filter( + image.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + area, + area_threshold, + ) + return output + + +def diameter_opening( + image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None +): + """Perform a diameter opening of the image. + + Diameter opening removes all bright structures of an image with + maximal extension smaller than diameter_threshold. The maximal + extension is defined as the maximal extension of the bounding box. + The operator is also called Bounding Box Opening. In practice, + the result is similar to a morphological opening, but long and thin + structures are not removed. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_opening is to be calculated. + This image can be of any type. + diameter_threshold : unsigned int + The maximal extension parameter (number of pixels). The default value + is 8. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the image. The + value of each pixel is the index of its parent in the ravelled array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as the input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.area_closing + skimage.morphology.diameter_closing + skimage.morphology.max_tree + + References + ---------- + .. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of + Microaneurysms in Color Fundus Images of the Human Retina by Means + of the Bounding Box Closing. In A. Colosimo, P. Sirabella, + A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer + Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. + :DOI:`10.1007/3-540-36104-9_23` + .. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional local maxima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the diameter opening: + + >>> open = diameter_opening(f, 3, connectivity=1) + + The peaks with a maximal extension of 2 or less are removed. + The remaining peaks have all a maximal extension of at least 3. + """ + output = image.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + diam = _max_tree._compute_extension( + image.ravel(), + np.array(image.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + _max_tree._direct_filter( + image.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + diam, + diameter_threshold, + ) + return output + + +def area_closing( + image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None +): + """Perform an area closing of the image. + + Area closing removes all dark structures of an image with + a surface smaller than area_threshold. + The output image is larger than or equal to the input image + for every pixel and all local minima have at least a surface of + area_threshold pixels. + + Area closings are similar to morphological closings, but + they do not use a fixed footprint, but rather a deformable + one, with surface = area_threshold. + + In the binary case, area closings are equivalent to + remove_small_holes; this operator is thus extended to gray-level images. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the area_closing is to be calculated. + This image can be of any type. + area_threshold : unsigned int + The size parameter (number of pixels). The default value is arbitrarily + chosen to be 64. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Parent image representing the max tree of the inverted image. The + value of each pixel is the index of its parent in the ravelled array. + See Note for further details. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + output : ndarray + Output image of the same shape and type as input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.diameter_opening + skimage.morphology.diameter_closing + skimage.morphology.max_tree + skimage.morphology.remove_small_objects + skimage.morphology.remove_small_holes + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a minimum in the center and + 4 additional local minima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the area closing: + + >>> closed = area_closing(f, 8, connectivity=1) + + All small minima are removed, and the remaining minima have at least + a size of 8. + + Notes + ----- + If a max-tree representation (parent and tree_traverser) are given to the + function, they must be calculated from the inverted image for this + function, i.e.: + >>> P, S = max_tree(invert(f)) + >>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S) + """ + # inversion of the input image + image_inv = invert(image) + output = image_inv.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image_inv, connectivity) + + area = _max_tree._compute_area(image_inv.ravel(), parent.ravel(), tree_traverser) + + _max_tree._direct_filter( + image_inv.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + area, + area_threshold, + ) + + # inversion of the output image + output = invert(output) + + return output + + +def diameter_closing( + image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None +): + """Perform a diameter closing of the image. + + Diameter closing removes all dark structures of an image with + maximal extension smaller than diameter_threshold. The maximal + extension is defined as the maximal extension of the bounding box. + The operator is also called Bounding Box Closing. In practice, + the result is similar to a morphological closing, but long and thin + structures are not removed. + + Technically, this operator is based on the max-tree representation of + the image. + + Parameters + ---------- + image : ndarray + The input image for which the diameter_closing is to be calculated. + This image can be of any type. + diameter_threshold : unsigned int + The maximal extension parameter (number of pixels). The default value + is 8. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + Precomputed parent image representing the max tree of the inverted + image. This function is fast, if precomputed parent and tree_traverser + are provided. See Note for further details. + tree_traverser : 1D array, int64, optional + Precomputed traverser, where the pixels are ordered such that every + pixel is preceded by its parent (except for the root which has no + parent). This function is fast, if precomputed parent and + tree_traverser are provided. See Note for further details. + + Returns + ------- + output : ndarray + Output image of the same shape and type as input image. + + See Also + -------- + skimage.morphology.area_opening + skimage.morphology.area_closing + skimage.morphology.diameter_opening + skimage.morphology.max_tree + + References + ---------- + .. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of + Microaneurysms in Color Fundus Images of the Human Retina by Means + of the Bounding Box Closing. In A. Colosimo, P. Sirabella, + A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer + Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. + :DOI:`10.1007/3-540-36104-9_23` + .. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a minimum in the center and + 4 additional local minima. + + >>> w = 12 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 + >>> f[9:10,9:11] = 100; f[10,10] = 100 + >>> f = f.astype(int) + + We can calculate the diameter closing: + + >>> closed = diameter_closing(f, 3, connectivity=1) + + All small minima with a maximal extension of 2 or less are removed. + The remaining minima have all a maximal extension of at least 3. + + Notes + ----- + If a max-tree representation (parent and tree_traverser) are given to the + function, they must be calculated from the inverted image for this + function, i.e.: + >>> P, S = max_tree(invert(f)) + >>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S) + """ + # inversion of the input image + image_inv = invert(image) + output = image_inv.copy() + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image_inv, connectivity) + + diam = _max_tree._compute_extension( + image_inv.ravel(), + np.array(image_inv.shape, dtype=np.int32), + parent.ravel(), + tree_traverser, + ) + + _max_tree._direct_filter( + image_inv.ravel(), + output.ravel(), + parent.ravel(), + tree_traverser, + diam, + diameter_threshold, + ) + output = invert(output) + return output + + +def max_tree_local_maxima(image, connectivity=1, parent=None, tree_traverser=None): + """Determine all local maxima of the image. + + The local maxima are defined as connected sets of pixels with equal + gray level strictly greater than the gray levels of all pixels in direct + neighborhood of the set. The function labels the local maxima. + + Technically, the implementation is based on the max-tree representation + of an image. The function is very efficient if the max-tree representation + has already been computed. Otherwise, it is preferable to use + the function local_maxima. + + Parameters + ---------- + image : ndarray + The input image for which the maxima are to be calculated. + connectivity : unsigned int, optional + The neighborhood connectivity. The integer represents the maximum + number of orthogonal steps to reach a neighbor. In 2D, it is 1 for + a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. + parent : ndarray, int64, optional + The value of each pixel is the index of its parent in the ravelled + array. + tree_traverser : 1D array, int64, optional + The ordered pixel indices (referring to the ravelled array). The pixels + are ordered such that every pixel is preceded by its parent (except for + the root which has no parent). + + Returns + ------- + local_max : ndarray, uint64 + Labeled local maxima of the image. + + See Also + -------- + skimage.morphology.local_maxima + skimage.morphology.max_tree + + References + ---------- + .. [1] Vincent L., Proc. "Grayscale area openings and closings, + their efficient implementation and applications", + EURASIP Workshop on Mathematical Morphology and its + Applications to Signal Processing, Barcelona, Spain, pp.22-27, + May 1993. + .. [2] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + :DOI:`10.1007/978-3-662-05088-0` + .. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive + Connected Operators for Image and Sequence Processing. + IEEE Transactions on Image Processing, 7(4), 555-570. + :DOI:`10.1109/83.663500` + .. [4] Najman, L., & Couprie, M. (2006). Building the component tree in + quasi-linear time. IEEE Transactions on Image Processing, 15(11), + 3531-3539. + :DOI:`10.1109/TIP.2006.877518` + .. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of + Component Tree Computation Algorithms. IEEE Transactions on Image + Processing, 23(9), 3885-3895. + :DOI:`10.1109/TIP.2014.2336551` + + Examples + -------- + We create an image (quadratic function with a maximum in the center and + 4 additional constant maxima. + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all local maxima: + + >>> maxima = max_tree_local_maxima(f) + + The resulting image contains the labeled local maxima. + """ + + output = np.ones(image.shape, dtype=np.uint64) + + if parent is None or tree_traverser is None: + parent, tree_traverser = max_tree(image, connectivity) + + _max_tree._max_tree_local_maxima( + image.ravel(), output.ravel(), parent.ravel(), tree_traverser + ) + + return output diff --git a/envs/kitoverlay/skimage/morphology/misc.py b/envs/kitoverlay/skimage/morphology/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..f32e7547da3700e080a6c2907e46ed463af7d90b --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/misc.py @@ -0,0 +1,509 @@ +"""Miscellaneous morphology functions.""" + +import numpy as np +import functools +import warnings +from scipy import ndimage as ndi +from scipy.spatial import cKDTree + +from .._shared.utils import warn, deprecate_parameter, DEPRECATED +from ._misc_cy import _remove_objects_by_distance + + +# Our function names don't exactly correspond to ndimages. +# This dictionary translates from our names to scipy's. +funcs = ('erosion', 'dilation', 'opening', 'closing') +skimage2ndimage = {x: 'grey_' + x for x in funcs} + +# These function names are the same in ndimage. +funcs = ( + 'black_tophat', + 'white_tophat', +) +skimage2ndimage.update({x: x for x in funcs}) + + +def default_footprint(func): + """Decorator to add a default footprint to morphology functions. + + Parameters + ---------- + func : function + A morphology function such as erosion, dilation, opening, closing, + white_tophat, or black_tophat. + + Returns + ------- + func_out : function + The function, using a default footprint of same dimension + as the input image with connectivity 1. + + """ + + @functools.wraps(func) + def func_out(image, footprint=None, *args, **kwargs): + if footprint is None: + footprint = ndi.generate_binary_structure(image.ndim, 1) + return func(image, footprint=footprint, *args, **kwargs) + + return func_out + + +def _check_dtype_supported(ar): + # Should use `issubdtype` for bool below, but there's a bug in numpy 1.7 + if not (ar.dtype == bool or np.issubdtype(ar.dtype, np.integer)): + raise TypeError( + "Only bool or integer image types are supported. " f"Got {ar.dtype}." + ) + + +@deprecate_parameter( + deprecated_name="min_size", + new_name="max_size", + start_version="0.26.0", + stop_version="2.0.0", + template=f"{deprecate_parameter.replace_parameter_template} " + "Note that the new threshold removes objects smaller than **or equal to** " + "its value, while the previous parameter only removed smaller ones.", +) +def remove_small_objects( + ar, min_size=DEPRECATED, connectivity=1, *, max_size=64, out=None +): + """Remove objects smaller than the specified size. + + Expects `ar` to be an array with labeled objects, and removes objects + smaller than or equal to `max_size`. If `ar` is bool, the image is first + labeled. This leads to potentially different behavior for bool vs. 0-and-1 + arrays. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the objects of interest. If the array type is + int, the ints must be non-negative. + max_size : int, optional (default: 64) + Remove objects whose contiguous area (or volume, in N-D) contains this + number of pixels or fewer. + + .. versionadded:: 0.26 + To make the naming clearer, replaces deprecated `min_size` + which only removed objects strictly smaller than its size. + + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. Used during + labelling if `ar` is bool. + out : ndarray + Array of the same shape as `ar`, into which the output is + placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small connected components removed. + + See Also + -------- + skimage.morphology.remove_small_holes + skimage.morphology.remove_objects_by_distance + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[0, 0, 0, 1, 0], + ... [1, 1, 1, 0, 0], + ... [1, 1, 1, 0, 1]], bool) + >>> b = morphology.remove_small_objects(a, max_size=5) + >>> b + array([[False, False, False, False, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> c = morphology.remove_small_objects(a, max_size=6, connectivity=2) + >>> c + array([[False, False, False, True, False], + [ True, True, True, False, False], + [ True, True, True, False, False]]) + >>> d = morphology.remove_small_objects(a, max_size=5, out=a) + >>> d is a + True + + """ + # Raising type error if not int or bool + _check_dtype_supported(ar) + + if out is None: + out = ar.copy() + else: + out[:] = ar + + if max_size == 0: # shortcut for efficiency + return out + + if out.dtype == bool: + footprint = ndi.generate_binary_structure(ar.ndim, connectivity) + ccs = np.zeros_like(ar, dtype=np.int32) + ndi.label(ar, footprint, output=ccs) + else: + ccs = out + + try: + component_sizes = np.bincount(ccs.ravel()) + except ValueError: + raise ValueError( + "Negative value labels are not supported. Try " + "relabeling the input with `scipy.ndimage.label` or " + "`skimage.morphology.label`." + ) + + if len(component_sizes) == 2 and out.dtype != bool: + warn( + "Only one label was provided to `remove_small_objects`. " + "Did you mean to use a boolean array?" + ) + + if min_size is not DEPRECATED: + # Exclusive threshold is deprecated behavior + too_small = component_sizes < min_size + else: + # New behavior uses inclusive threshold + too_small = component_sizes <= max_size + too_small_mask = too_small[ccs] + out[too_small_mask] = 0 + + return out + + +@deprecate_parameter( + deprecated_name="area_threshold", + new_name="max_size", + start_version="0.26.0", + stop_version="2.0.0", + template=f"{deprecate_parameter.replace_parameter_template} " + "Note that the new threshold removes objects smaller than **or equal to** " + "its value, while the previous parameter only removed smaller ones.", +) +def remove_small_holes( + ar, area_threshold=DEPRECATED, connectivity=1, *, max_size=64, out=None +): + """Remove contiguous holes smaller than the specified size. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the connected components of interest. + max_size : int, optional (default: 64) + Remove holes whose contiguous area (or volume, in N-D) contains this + number of pixels or fewer. + + .. versionadded:: 0.26 + To make the naming clearer, replaces deprecated `area_threshold` + which only removed holes strictly smaller than its size. + + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. + out : ndarray + Array of the same shape as `ar` and bool dtype, into which the + output is placed. By default, a new array is created. + + Raises + ------ + TypeError + If the input array is of an invalid type, such as float or string. + ValueError + If the input array contains negative values. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small holes within connected components removed. + + See Also + -------- + skimage.morphology.remove_small_objects + skimage.morphology.remove_objects_by_distance + + Examples + -------- + >>> from skimage import morphology + >>> a = np.array([[1, 1, 1, 1, 1, 0], + ... [1, 1, 1, 0, 1, 0], + ... [1, 0, 0, 1, 1, 0], + ... [1, 1, 1, 1, 1, 0]], bool) + >>> b = morphology.remove_small_holes(a, max_size=1) + >>> b + array([[ True, True, True, True, True, False], + [ True, True, True, True, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> c = morphology.remove_small_holes(a, max_size=1, connectivity=2) + >>> c + array([[ True, True, True, True, True, False], + [ True, True, True, False, True, False], + [ True, False, False, True, True, False], + [ True, True, True, True, True, False]]) + >>> d = morphology.remove_small_holes(a, max_size=1, out=a) + >>> d is a + True + + Notes + ----- + If the array type is int, it is assumed that it contains already-labeled + objects. The labels are not kept in the output image (this function always + outputs a bool image). It is suggested that labeling is completed after + using this function. + + """ + _check_dtype_supported(ar) + + # Creates warning if image is an integer image + if ar.dtype != bool: + warn( + "Any labeled images will be returned as a boolean array. " + "Did you mean to use a boolean array?", + UserWarning, + ) + + if out is not None: + if out.dtype != bool: + raise TypeError("out dtype must be bool") + else: + out = ar.astype(bool, copy=True) + + # Creating the inverse of ar + np.logical_not(ar, out=out) + + # removing small objects from the inverse of ar + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Parameter `min_size` is deprecated", + category=FutureWarning, + ) + out = remove_small_objects( + out, + min_size=area_threshold, + max_size=max_size, + connectivity=connectivity, + out=out, + ) + + np.logical_not(out, out=out) + + return out + + +def remove_objects_by_distance( + label_image, + min_distance, + *, + priority=None, + p_norm=2, + spacing=None, + out=None, +): + """Remove objects, in specified order, until remaining are a minimum distance apart. + + Remove labeled objects from an image until the remaining ones are spaced + more than a given distance from one another. By default, smaller objects + are removed first. + + Parameters + ---------- + label_image : ndarray of integers + An n-dimensional array containing object labels, e.g. as returned by + :func:`~.label`. A value of zero is considered background, all other + object IDs must be positive integers. + min_distance : int or float + Remove objects whose distance to other objects is not greater than this + positive value. Objects with a lower `priority` are removed first. + priority : ndarray, optional + Defines the priority with which objects are removed. Expects a + 1-dimensional array of length + :func:`np.amax(label_image) + 1 ` that contains the priority + for each object's label at the respective index. Objects with a lower value + are removed first until all remaining objects fulfill the distance + requirement. If not given, priority is given to objects with a higher + number of samples and their label value second. + p_norm : int or float, optional + The Minkowski distance of order p, used to calculate the distance + between objects. The default ``2`` corresponds to the Euclidean + distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the + Chebyshev distance. + spacing : sequence of float, optional + The pixel spacing along each axis of `label_image`. If not specified, + a grid spacing of unity (1) is implied. + out : ndarray, optional + Array of the same shape and dtype as `image`, into which the output is + placed. By default, a new array is created. + + Returns + ------- + out : ndarray + Array of the same shape as `label_image`, for which objects that violate + the `min_distance` condition were removed. + + See Also + -------- + skimage.morphology.remove_small_objects + Remove objects smaller than the specified size. + skimage.morphology.remove_small_holes + Remove holes smaller than the specified size. + + Notes + ----- + The basic steps of this algorithm work as follows: + + 1. Find the indices for of all given objects and separate them depending on + if they point to an object's border or not. + 2. Sort indices by their label value, ensuring that indices which point to + the same object are next to each other. This optimization allows finding + all parts of an object, simply by stepping to the neighboring indices. + 3. Sort boundary indices by `priority`. Use a stable-sort to preserve the + ordering from the previous sorting step. If `priority` is not given, + use :func:`numpy.bincount` as a fallback. + 4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices. + 5. Iterate across boundary indices in priority-sorted order, and query the + kd-tree for objects that are too close. Remove ones that are and don't + take them into account when evaluating other objects later on. + + The performance of this algorithm depends on the number of samples in + `label_image` that belong to an object's border. + + Examples + -------- + >>> import skimage as ski + >>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2) + array([0, 0, 1, 1]) + >>> ski.morphology.remove_objects_by_distance( + ... np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9]) + ... ) + array([2, 0, 0, 0]) + >>> label_image = np.array( + ... [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + ... [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + ... [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0], + ... [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]] + ... ) + >>> ski.morphology.remove_objects_by_distance( + ... label_image, min_distance=3 + ... ) + array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9], + [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9], + [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [2, 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, 7, 7]]) + """ + if min_distance < 0: + raise ValueError(f"min_distance must be >= 0, was {min_distance}") + if not np.issubdtype(label_image.dtype, np.integer): + raise ValueError( + f"`label_image` must be of integer dtype, got {label_image.dtype}" + ) + if out is None: + out = label_image.copy(order="C") + elif out is not label_image: + out[:] = label_image + # May create a copy if order is not C, account for that later + out_raveled = out.ravel(order="C") + + if spacing is not None: + spacing = np.array(spacing) + if spacing.shape != (out.ndim,) or spacing.min() <= 0: + raise ValueError( + "`spacing` must contain exactly one positive factor " + "for each dimension of `label_image`" + ) + + indices = np.flatnonzero(out_raveled) + # Optimization: Split indices into those on the object boundaries and inner + # ones. The KDTree is built only from the boundary indices, which reduces + # the size of the critical loop significantly! Remaining indices are only + # used to remove the inner parts of objects as well. + if (spacing is None or np.all(spacing[0] == spacing)) and p_norm <= 2: + # For unity spacing we can make the borders more sparse by using a + # lower connectivity + footprint = ndi.generate_binary_structure(out.ndim, 1) + else: + footprint = ndi.generate_binary_structure(out.ndim, out.ndim) + border = ( + ndi.maximum_filter(out, footprint=footprint) + != ndi.minimum_filter(out, footprint=footprint) + ).ravel()[indices] + border_indices = indices[border] + inner_indices = indices[~border] + + if border_indices.size == 0: + # Image without any or only one object, return early + return out + + # Sort by label ID first, so that IDs of the same object are contiguous + # in the sorted index. This allows fast discovery of the whole object by + # simple iteration up or down the index! + border_indices = border_indices[np.argsort(out_raveled[border_indices])] + inner_indices = inner_indices[np.argsort(out_raveled[inner_indices])] + + if priority is None: + if not np.can_cast(out.dtype, np.intp, casting="safe"): + # bincount expects intp (32-bit) on WASM or i386, so down-cast to that + priority = np.bincount(out_raveled.astype(np.intp, copy=False)) + else: + priority = np.bincount(out_raveled) + # `priority` can only be indexed by positive object IDs, + # `border_indices` contains all unique sorted IDs so check the lowest / first + smallest_id = out_raveled[border_indices[0]] + if smallest_id < 0: + raise ValueError(f"found object with negative ID {smallest_id!r}") + + try: + # Sort by priority second using a stable sort to preserve the contiguous + # sorting of objects. Because each pixel in an object has the same + # priority we don't need to worry about separating objects. + border_indices = border_indices[ + np.argsort(priority[out_raveled[border_indices]], kind="stable")[::-1] + ] + except IndexError as error: + # Use np.amax only for the exception path to provide a nicer error message + expected_shape = (np.amax(out_raveled) + 1,) + if priority.shape != expected_shape: + raise ValueError( + "shape of `priority` must be (np.amax(label_image) + 1,), " + f"expected {expected_shape}, got {priority.shape} instead" + ) from error + else: + raise + + # Construct kd-tree from unraveled border indices (optionally scale by `spacing`) + unraveled_indices = np.unravel_index(border_indices, out.shape) + if spacing is not None: + unraveled_indices = tuple( + unraveled_indices[dim] * spacing[dim] for dim in range(out.ndim) + ) + kdtree = cKDTree(data=np.asarray(unraveled_indices, dtype=np.float64).T) + + _remove_objects_by_distance( + out=out_raveled, + border_indices=border_indices, + inner_indices=inner_indices, + kdtree=kdtree, + min_distance=min_distance, + p_norm=p_norm, + shape=label_image.shape, + ) + + if out_raveled.base is not out: + # `out_raveled` is a copy, re-assign + out[:] = out_raveled.reshape(out.shape) + return out