diff --git a/envs/kitoverlay/skimage/data/README.txt b/envs/kitoverlay/skimage/data/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b8c30aff89b1572bb836c13e1f2ec0c2ccd27c8 --- /dev/null +++ b/envs/kitoverlay/skimage/data/README.txt @@ -0,0 +1,9 @@ +This directory contains sample data from scikit-image. + +By default, it only contains a small subset of the entire dataset. + +The full detaset can be downloaded by using the following commands from +a python console. + + >>> from skimage.data import download_all + >>> download_all() diff --git a/envs/kitoverlay/skimage/data/__init__.py b/envs/kitoverlay/skimage/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d89f7efee556205748bd35278518f591de6c2391 --- /dev/null +++ b/envs/kitoverlay/skimage/data/__init__.py @@ -0,0 +1,13 @@ +"""Example images and datasets. + +A curated set of general purpose and scientific images used in tests, examples, +and documentation. + +Newer datasets are no longer included as part of the package, but are +downloaded on demand. To make data available offline, use :func:`download_all`. + +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/data/__init__.pyi b/envs/kitoverlay/skimage/data/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..71dddcc7df4c8df11164fa7a9777aeea45d53236 --- /dev/null +++ b/envs/kitoverlay/skimage/data/__init__.pyi @@ -0,0 +1,88 @@ +__all__ = [ + 'astronaut', + 'binary_blobs', + 'brain', + 'brick', + 'camera', + 'cat', + 'cell', + 'cells3d', + 'checkerboard', + 'chelsea', + 'clock', + 'coffee', + 'coins', + 'colorwheel', + 'data_dir', + 'download_all', + 'eagle', + 'file_hash', + 'grass', + 'gravel', + 'horse', + 'hubble_deep_field', + 'human_mitosis', + 'immunohistochemistry', + 'kidney', + 'lbp_frontal_face_cascade_filename', + 'lfw_subset', + 'lily', + 'logo', + 'microaneurysms', + 'moon', + 'nickel_solidification', + 'page', + 'protein_transport', + 'retina', + 'rocket', + 'shepp_logan_phantom', + 'skin', + 'stereo_motorcycle', + 'text', + 'vortex', +] + +from ._binary_blobs import binary_blobs +from ._fetchers import ( + astronaut, + brain, + brick, + camera, + cat, + cell, + cells3d, + checkerboard, + chelsea, + clock, + coffee, + coins, + colorwheel, + data_dir, + download_all, + eagle, + file_hash, + grass, + gravel, + horse, + hubble_deep_field, + human_mitosis, + immunohistochemistry, + kidney, + lbp_frontal_face_cascade_filename, + lfw_subset, + lily, + logo, + microaneurysms, + moon, + nickel_solidification, + page, + palisades_of_vogt, + protein_transport, + retina, + rocket, + shepp_logan_phantom, + skin, + stereo_motorcycle, + text, + vortex, +) diff --git a/envs/kitoverlay/skimage/data/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4703bf307a87a27141bc7ac504670a0f4f46971c Binary files /dev/null and b/envs/kitoverlay/skimage/data/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/data/__pycache__/_binary_blobs.cpython-311.pyc b/envs/kitoverlay/skimage/data/__pycache__/_binary_blobs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72f800400f87be7e177606598e54030dfc2289d4 Binary files /dev/null and b/envs/kitoverlay/skimage/data/__pycache__/_binary_blobs.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/data/__pycache__/_fetchers.cpython-311.pyc b/envs/kitoverlay/skimage/data/__pycache__/_fetchers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..415ab4d12ddce1a1b520a7d7c5cb9910a064000e Binary files /dev/null and b/envs/kitoverlay/skimage/data/__pycache__/_fetchers.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/data/__pycache__/_registry.cpython-311.pyc b/envs/kitoverlay/skimage/data/__pycache__/_registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e0bedc2e22367120f5ef31df08c819c9a788305 Binary files /dev/null and b/envs/kitoverlay/skimage/data/__pycache__/_registry.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/data/_binary_blobs.py b/envs/kitoverlay/skimage/data/_binary_blobs.py new file mode 100644 index 0000000000000000000000000000000000000000..4cafc916ed5ec530b1ea8804fc7248ec61bcd84d --- /dev/null +++ b/envs/kitoverlay/skimage/data/_binary_blobs.py @@ -0,0 +1,106 @@ +import warnings + +import numpy as np + +from .._shared.filters import gaussian + + +def binary_blobs( + length=512, + blob_size_fraction=0.1, + n_dim=2, + volume_fraction=0.5, + rng=None, + *, + boundary_mode='nearest', +): + """ + Generate synthetic binary image with several rounded blob-like objects. + + Parameters + ---------- + length : int, optional + Linear size of output image. + blob_size_fraction : float, optional + Typical linear size of blob, as a fraction of ``length``, should be + smaller than 1. + n_dim : int, optional + Number of dimensions of output image. + volume_fraction : float, default 0.5 + Fraction of image pixels covered by the blobs (where the output is 1). + Should be in [0, 1]. + 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. + boundary_mode : {'nearest', 'wrap'}, optional + The blobs are created by smoothing and then thresholding an + array consisting of ones at seed positions. This mode determines which values are + filled in when the smoothing kernel overlaps the seed array's boundary. + + 'nearest' (`a a a a | a b c d | d d d d`) + By default, when applying the Gaussian filter, the seed array is extended by replicating the last + boundary value. This will increase the size of blobs whose seed or + center lies exactly on the edge. + + 'wrap' (`a b c d | a b c d | a b c d`) + The seed array is extended by wrapping around to the opposite edge. + The resulting blob array can be tiled and blobs will be contiguous and + have smooth edges across tile boundaries. + + boundary_mode : str, default "nearest" + The `mode` parameter passed to the Gaussian filter. + Use "wrap" for periodic boundary conditions. + + Returns + ------- + blobs : ndarray of bools + Output binary image + + Examples + -------- + >>> from skimage import data + >>> data.binary_blobs(length=5, blob_size_fraction=0.2) # doctest: +SKIP + array([[ True, False, True, True, True], + [ True, True, True, False, True], + [False, True, False, True, True], + [ True, False, False, True, True], + [ True, False, False, False, True]]) + >>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.1) + >>> # Finer structures + >>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.05) + >>> # Blobs cover a smaller volume fraction of the image + >>> blobs = data.binary_blobs(length=256, volume_fraction=0.3) + """ + if boundary_mode not in {"nearest", "wrap"}: + raise ValueError(f"unsupported `boundary_mode`: {boundary_mode!r}") + + blob_size = blob_size_fraction * length + if blob_size < 0.1: + clamped_size_fraction = 0.1 / length + clamped_blob_size = clamped_size_fraction * length + warnings.warn( + f"`{blob_size_fraction=}` together with `{length=}` would result in a blob " + f"size of {blob_size} pixels. Small blob sizes likely lead to unexpected " + f"results! " + f"Clamping to `blob_size_fraction={clamped_size_fraction}` and a blob size " + f"of {clamped_blob_size} pixels to avoid allocating excessive memory.", + category=RuntimeWarning, + stacklevel=2, + ) + blob_size_fraction = clamped_size_fraction + + rs = np.random.default_rng(rng) + shape = tuple([length] * n_dim) + mask = np.zeros(shape) + n_pts = max(int(1.0 / blob_size_fraction) ** n_dim, 1) + points = (length * rs.random((n_dim, n_pts))).astype(int) + mask[tuple(indices for indices in points)] = 1 + mask = gaussian( + mask, + sigma=0.25 * length * blob_size_fraction, + preserve_range=False, + mode=boundary_mode, + ) + threshold = np.percentile(mask, 100 * (1 - volume_fraction)) + return np.logical_not(mask < threshold) diff --git a/envs/kitoverlay/skimage/data/_fetchers.py b/envs/kitoverlay/skimage/data/_fetchers.py new file mode 100644 index 0000000000000000000000000000000000000000..f05259b400fa27ebc52563fdd778654ff2412cb1 --- /dev/null +++ b/envs/kitoverlay/skimage/data/_fetchers.py @@ -0,0 +1,1271 @@ +"""Standard test images. + +For more images, see + + - http://sipi.usc.edu/database/database.php + +""" + +import numpy as np +import shutil + +from ..util.dtype import img_as_bool +from ._registry import registry, registry_urls + +from .. import __version__ + +import os.path as osp +import os + +_LEGACY_DATA_DIR = osp.dirname(__file__) +_DISTRIBUTION_DIR = osp.dirname(_LEGACY_DATA_DIR) + +try: + from pooch import file_hash +except ModuleNotFoundError: + # Function taken from + # https://github.com/fatiando/pooch/blob/master/pooch/utils.py + def file_hash(fname, alg="sha256"): + """ + Calculate the hash of a given file. + Useful for checking if a file has changed or been corrupted. + Parameters + ---------- + fname : str + The name of the file. + alg : str + The type of the hashing algorithm + Returns + ------- + hash : str + The hash of the file. + Examples + -------- + >>> fname = "test-file-for-hash.txt" + >>> with open(fname, "w") as f: + ... __ = f.write("content of the file") + >>> print(file_hash(fname)) + 0fc74468e6a9a829f103d069aeb2bb4f8646bad58bf146bb0e3379b759ec4a00 + >>> import os + >>> os.remove(fname) + """ + import hashlib + + if alg not in hashlib.algorithms_available: + raise ValueError(f'Algorithm \'{alg}\' not available in hashlib') + # Calculate the hash in chunks to avoid overloading the memory + chunksize = 65536 + hasher = hashlib.new(alg) + with open(fname, "rb") as fin: + buff = fin.read(chunksize) + while buff: + hasher.update(buff) + buff = fin.read(chunksize) + return hasher.hexdigest() + + +def _has_hash(path, expected_hash): + """Check if the provided path has the expected hash.""" + if not osp.exists(path): + return False + return file_hash(path) == expected_hash + + +def _create_image_fetcher(prefix=None): + try: + import pooch + + # older versions of Pooch don't have a __version__ attribute + if not hasattr(pooch, '__version__'): + retry = {} + else: + retry = {'retry_if_failed': 3} + except ImportError: + # Without pooch, fallback on the standard data directory + # which for now, includes a few limited data samples + return None, _LEGACY_DATA_DIR + + # Pooch expects a `+` to exist in development versions. + # Since scikit-image doesn't follow that convention, we have to manually + # remove `.dev` with a `+` if it exists. + # This helps pooch understand that it should look in master + # to find the required files + if '+git' in __version__: + skimage_version_for_pooch = __version__.replace('.dev0+git', '+git') + else: + skimage_version_for_pooch = __version__.replace('.dev', '+') + + if '+' in skimage_version_for_pooch: + if prefix is not None: + url = ( + "https://github.com/scikit-image/scikit-image/raw/" + "{version}/tests/skimage/" + ) + else: + url = ( + "https://github.com/scikit-image/scikit-image/raw/" + "{version}/src/skimage/" + ) + else: + if prefix is not None: + url = ( + "https://github.com/scikit-image/scikit-image/raw/" + "v{version}/tests/skimage/" + ) + else: + url = ( + "https://github.com/scikit-image/scikit-image/raw/" + "v{version}/src/skimage/" + ) + + # Create a new friend to manage your sample data storage + image_fetcher = pooch.create( + # Pooch uses appdirs to select an appropriate directory for the cache + # on each platform. + # https://github.com/ActiveState/appdirs + # On linux this converges to + # '$HOME/.cache/scikit-image' + # With a version qualifier + path=pooch.os_cache("scikit-image"), + base_url=url, + version=skimage_version_for_pooch, + version_dev="main", + env="SKIMAGE_DATADIR", + registry=registry, + urls=registry_urls, + # Note: this should read `retry_if_failed=3,`, but we generate that + # dynamically at import time above, in case installed pooch is a less + # recent version + **retry, + ) + + data_dir = osp.join(str(image_fetcher.abspath), 'data') + return image_fetcher, data_dir + + +_image_fetcher, data_dir = _create_image_fetcher(prefix='tests') + + +def _skip_pytest_case_requiring_pooch(data_filename): + """If a test case is calling pooch, skip it. + + This running the test suite in environments without internet + access, skipping only the tests that try to fetch external data. + """ + + # Check if pytest is currently running. + # Packagers might use pytest to run the tests suite, but may not + # want to run it online with pooch as a dependency. + # As such, we will avoid failing the test, and silently skipping it. + if 'PYTEST_CURRENT_TEST' in os.environ: + # https://docs.pytest.org/en/latest/example/simple.html#pytest-current-test-environment-variable + import pytest + + # Pytest skip raises an exception that allows the + # tests to be skipped + pytest.skip(f'Unable to download {data_filename}', allow_module_level=True) + + +def _ensure_cache_dir(*, target_dir): + """Prepare local cache directory if it doesn't exist already. + + Creates:: + + /path/to/target_dir/ + └─ data/ + └─ README.txt + """ + os.makedirs(osp.join(target_dir, "data"), exist_ok=True) + readme_src = osp.join(_DISTRIBUTION_DIR, "data/README.txt") + readme_dest = osp.join(target_dir, "data/README.txt") + if not osp.exists(readme_dest): + shutil.copy2(readme_src, readme_dest) + + +def _fetch(data_filename, prefix=None): + """Fetch a given data file from either the local cache or the repository. + + This function provides the path location of the data file given + its name in the scikit-image repository. If a data file is not included in the + distribution and pooch is available, it is downloaded and cached. + + Parameters + ---------- + data_filename : str + Name of the file in the scikit-image repository. e.g. + 'restoration/camera_rl.npy'. + + Returns + ------- + file_path : str + Path of the local file. + + Raises + ------ + KeyError: + If the filename is not known to the scikit-image distribution. + + ModuleNotFoundError: + If the filename is known to the scikit-image distribution but pooch + is not installed. + + ConnectionError: + If scikit-image is unable to connect to the internet but the + dataset has not been downloaded yet. + """ + if prefix is not None: + return osp.join("tests", "skimage", data_filename) + + expected_hash = registry[data_filename] + if _image_fetcher is None: + cache_dir = osp.dirname(data_dir) + else: + cache_dir = str(_image_fetcher.abspath) + + # Case 1: the file is already cached in `data_cache_dir` + cached_file_path = osp.join(cache_dir, data_filename) + if _has_hash(cached_file_path, expected_hash): + # Nothing to be done, file is where it is expected to be + return cached_file_path + + # Case 2: file is present in `legacy_data_dir` + legacy_file_path = osp.join(_DISTRIBUTION_DIR, data_filename) + if _has_hash(legacy_file_path, expected_hash): + return legacy_file_path + + # Case 3: file is not present locally + if _image_fetcher is None: + _skip_pytest_case_requiring_pooch(data_filename) + raise ModuleNotFoundError( + "The requested file is part of the scikit-image distribution, " + "but requires the installation of an optional dependency, pooch. " + "To install pooch, use your preferred python package manager. " + "Follow installation instruction found at " + "https://scikit-image.org/docs/stable/user_guide/install.html" + ) + # Download the data with pooch which caches it automatically + _ensure_cache_dir(target_dir=cache_dir) + try: + cached_file_path = _image_fetcher.fetch(data_filename) + return cached_file_path + except ConnectionError as err: + _skip_pytest_case_requiring_pooch(data_filename) + # If we decide in the future to suppress the underlying 'requests' + # error, change this to `raise ... from None`. See PEP 3134. + raise ConnectionError( + 'Tried to download a scikit-image dataset, but no internet ' + 'connection is available. To avoid this message in the ' + 'future, try `skimage.data.download_all()` when you are ' + 'connected to the internet.' + ) from err + + +def download_all(directory=None): + """Download all datasets for use with scikit-image offline. + + Scikit-image datasets are no longer shipped with the library by default. + This allows us to use higher quality datasets, while keeping the + library download size small. + + This function requires the installation of an optional dependency, pooch, + to download the full dataset. Follow installation instruction found at + + https://scikit-image.org/docs/stable/user_guide/install.html + + Call this function to download all sample images making them available + offline on your machine. + + Parameters + ---------- + directory : path-like, optional + The directory where the dataset should be stored. + + Raises + ------ + ModuleNotFoundError: + If pooch is not install, this error will be raised. + + Notes + ----- + scikit-image will only search for images stored in the default directory. + Only specify the directory if you wish to download the images to your own + folder for a particular reason. You can access the location of the default + data directory by inspecting the variable ``skimage.data.data_dir``. + """ + + if _image_fetcher is None: + raise ModuleNotFoundError( + "To download all package data, scikit-image needs an optional " + "dependency, pooch." + "To install pooch, follow our installation instructions found at " + "https://scikit-image.org/docs/stable/user_guide/install.html" + ) + # Consider moving this kind of logic to Pooch + old_dir = _image_fetcher.path + try: + if directory is not None: + directory = osp.expanduser(directory) + _image_fetcher.path = directory + _ensure_cache_dir(target_dir=_image_fetcher.path) + + for data_filename in _image_fetcher.registry: + file_path = _fetch(data_filename) + + # Copy to `directory` or implicit cache if it is not already there + if not file_path.startswith(str(_image_fetcher.path)): + dest_path = osp.join(_image_fetcher.path, data_filename) + os.makedirs(osp.dirname(dest_path), exist_ok=True) + shutil.copy2(file_path, dest_path) + finally: + _image_fetcher.path = old_dir + + +def lbp_frontal_face_cascade_filename(): + """Return the path to the XML file containing the weak classifier cascade. + + These classifiers were trained using LBP features. The file is part + of the OpenCV repository [1]_. + + References + ---------- + .. [1] OpenCV lbpcascade trained files + https://github.com/opencv/opencv/tree/master/data/lbpcascades + """ + + return _fetch('data/lbpcascade_frontalface_opencv.xml') + + +def _load(f, as_gray=False): + """Load an image file located in the data directory. + + Parameters + ---------- + f : string + File name. + as_gray : bool, optional + Whether to convert the image to grayscale. + + Returns + ------- + img : ndarray + Image loaded from ``skimage.data_dir``. + """ + # importing io is quite slow since it scans all the backends + # we lazy import it here + from ..io import imread + + return imread(_fetch(f), as_gray=as_gray) + + +def camera(): + """Gray-level "camera" image. + + Can be used for segmentation and denoising examples. + + Returns + ------- + camera : (512, 512) uint8 ndarray + Camera image. + + Notes + ----- + No copyright restrictions. CC0 by the photographer (Lav Varshney). + + .. versionchanged:: 0.18 + This image was replaced due to copyright restrictions. For more + information, please see [1]_. + + References + ---------- + .. [1] https://github.com/scikit-image/scikit-image/issues/3927 + """ + return _load("data/camera.png") + + +def eagle(): + """A golden eagle. + + Suitable for examples on segmentation, Hough transforms, and corner + detection. + + Notes + ----- + No copyright restrictions. CC0 by the photographer (Dayane Machado). + + Returns + ------- + eagle : (2019, 1826) uint8 ndarray + Eagle image. + """ + return _load("data/eagle.png") + + +def astronaut(): + """Color image of the astronaut Eileen Collins. + + Photograph of Eileen Collins, an American astronaut. She was selected + as an astronaut in 1992 and first piloted the space shuttle STS-63 in + 1995. She retired in 2006 after spending a total of 38 days, 8 hours + and 10 minutes in outer space. + + This image was downloaded from the NASA Great Images database + `__. + + No known copyright restrictions, released into the public domain. + + Returns + ------- + astronaut : (512, 512, 3) uint8 ndarray + Astronaut image. + """ + + return _load("data/astronaut.png") + + +def brick(): + """Brick wall. + + Returns + ------- + brick : (512, 512) uint8 image + A small section of a brick wall. + + Notes + ----- + The original image was downloaded from + `CC0Textures `_ and licensed + under the Creative Commons CC0 License. + + A perspective transform was then applied to the image, prior to + rotating it by 90 degrees, cropping and scaling it to obtain the final + image. + """ + + """ + The following code was used to obtain the final image. + + >>> import sys; print(sys.version) + >>> import platform; print(platform.platform()) + >>> import skimage; print(f'scikit-image version: {skimage.__version__}') + >>> import numpy; print(f'numpy version: {numpy.__version__}') + >>> import imageio; print(f'imageio version {imageio.__version__}') + 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) + [GCC 7.3.0] + Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid + scikit-image version: 0.16.dev0 + numpy version: 1.16.4 + imageio version 2.4.1 + + >>> import requests + >>> import zipfile + >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Bricks25/%5B2K%5DBricks25.zip' + >>> r = requests.get(url) + >>> with open('[2K]Bricks25.zip', 'bw') as f: + ... f.write(r.content) + >>> with zipfile.ZipFile('[2K]Bricks25.zip') as z: + ... z.extract('Bricks25_col.jpg') + + >>> from numpy.linalg import inv + >>> from skimage.transform import rescale, warp, rotate + >>> from skimage.color import rgb2gray + >>> from imageio import imread, imwrite + >>> from skimage import img_as_ubyte + >>> import numpy as np + + + >>> # Obtained playing around with GIMP 2.10 with their perspective tool + >>> H = inv(np.asarray([[ 0.54764, -0.00219, 0], + ... [-0.12822, 0.54688, 0], + ... [-0.00022, 0, 1]])) + + + >>> brick_orig = imread('Bricks25_col.jpg') + >>> brick = warp(brick_orig, H) + >>> brick = rescale(brick[:1024, :1024], (0.5, 0.5, 1)) + >>> brick = rotate(brick, -90) + >>> imwrite('brick.png', img_as_ubyte(rgb2gray(brick))) + """ + return _load("data/brick.png", as_gray=True) + + +def grass(): + """Grass. + + Returns + ------- + grass : (512, 512) uint8 image + Some grass. + + Notes + ----- + The original image was downloaded from + `DeviantArt `__ + and licensed under the Creative Commons CC0 License. + + The downloaded image was cropped to include a region of ``(512, 512)`` + pixels around the top left corner, converted to grayscale, then to uint8 + prior to saving the result in PNG format. + + """ + + """ + The following code was used to obtain the final image. + + >>> import sys; print(sys.version) + >>> import platform; print(platform.platform()) + >>> import skimage; print(f'scikit-image version: {skimage.__version__}') + >>> import numpy; print(f'numpy version: {numpy.__version__}') + >>> import imageio; print(f'imageio version {imageio.__version__}') + 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) + [GCC 7.3.0] + Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid + scikit-image version: 0.16.dev0 + numpy version: 1.16.4 + imageio version 2.4.1 + + >>> import requests + >>> import zipfile + >>> url = 'https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a407467e-4ff0-49f1-923f-c9e388e84612/d76wfef-2878b78d-5dce-43f9-be36-26ec9bc0df3b.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E0MDc0NjdlLTRmZjAtNDlmMS05MjNmLWM5ZTM4OGU4NDYxMlwvZDc2d2ZlZi0yODc4Yjc4ZC01ZGNlLTQzZjktYmUzNi0yNmVjOWJjMGRmM2IuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.98hIcOTCqXWQ67Ec5bM5eovKEn2p91mWB3uedH61ynI' + >>> r = requests.get(url) + >>> with open('grass_orig.jpg', 'bw') as f: + ... f.write(r.content) + >>> grass_orig = imageio.imread('grass_orig.jpg') + >>> grass = skimage.img_as_ubyte(skimage.color.rgb2gray(grass_orig[:512, :512])) + >>> imageio.imwrite('grass.png', grass) + """ + return _load("data/grass.png", as_gray=True) + + +def gravel(): + """Gravel + + Returns + ------- + gravel : (512, 512) uint8 image + Grayscale gravel sample. + + Notes + ----- + The original image was downloaded from + `CC0Textures `__ and + licensed under the Creative Commons CC0 License. + + The downloaded image was then rescaled to ``(1024, 1024)``, then the + top left ``(512, 512)`` pixel region was cropped prior to converting the + image to grayscale and uint8 data type. The result was saved using the + PNG format. + """ + + """ + The following code was used to obtain the final image. + + >>> import sys; print(sys.version) + >>> import platform; print(platform.platform()) + >>> import skimage; print(f'scikit-image version: {skimage.__version__}') + >>> import numpy; print(f'numpy version: {numpy.__version__}') + >>> import imageio; print(f'imageio version {imageio.__version__}') + 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) + [GCC 7.3.0] + Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid + scikit-image version: 0.16.dev0 + numpy version: 1.16.4 + imageio version 2.4.1 + + >>> import requests + >>> import zipfile + + >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Gravel04/%5B2K%5DGravel04.zip' + >>> r = requests.get(url) + >>> with open('[2K]Gravel04.zip', 'bw') as f: + ... f.write(r.content) + + >>> with zipfile.ZipFile('[2K]Gravel04.zip') as z: + ... z.extract('Gravel04_col.jpg') + + >>> from skimage.transform import resize + >>> gravel_orig = imageio.imread('Gravel04_col.jpg') + >>> gravel = resize(gravel_orig, (1024, 1024)) + >>> gravel = skimage.img_as_ubyte(skimage.color.rgb2gray(gravel[:512, :512])) + >>> imageio.imwrite('gravel.png', gravel) + """ + return _load("data/gravel.png", as_gray=True) + + +def text(): + """Gray-level "text" image used for corner detection. + + Notes + ----- + This image was downloaded from Wikipedia + `__. + + No known copyright restrictions, released into the public domain. + + Returns + ------- + text : (172, 448) uint8 ndarray + Text image. + """ + + return _load("data/text.png") + + +def checkerboard(): + """Checkerboard image. + + Checkerboards are often used in image calibration, since the + corner-points are easy to locate. Because of the many parallel + edges, they also visualise distortions particularly well. + + Returns + ------- + checkerboard : (200, 200) uint8 ndarray + Checkerboard image. + """ + return _load("data/chessboard_GRAY.png") + + +def cells3d(): + """3D fluorescence microscopy image of cells. + + The returned data is a 3D multichannel array with dimensions provided in + ``(z, c, y, x)`` order. Each voxel has a size of ``(0.29 0.26 0.26)`` + micrometer. Channel 0 contains cell membranes, channel 1 contains nuclei. + + Returns + ------- + cells3d: (60, 2, 256, 256) uint16 ndarray + The volumetric images of cells taken with an optical microscope. + + Notes + ----- + The data for this was provided by the Allen Institute for Cell Science. + + It has been downsampled by a factor of 4 in the row and column dimensions + to reduce computational time. + + The microscope reports the following voxel spacing in microns: + + * Original voxel size is ``(0.290, 0.065, 0.065)``. + * Scaling factor is ``(1, 4, 4)`` in each dimension. + * After rescaling the voxel size is ``(0.29 0.26 0.26)``. + """ + + return _load("data/cells3d.tif") + + +def human_mitosis(): + """Image of human cells undergoing mitosis. + + Returns + ------- + human_mitosis: (512, 512) uint8 ndarray + Data of human cells undergoing mitosis taken during the preparation + of the manuscript in [1]_. + + Notes + ----- + Copyright David Root. Licensed under CC-0 [2]_. + + References + ---------- + .. [1] Moffat J, Grueneberg DA, Yang X, Kim SY, Kloepfer AM, Hinkle G, + Piqani B, Eisenhaure TM, Luo B, Grenier JK, Carpenter AE, Foo SY, + Stewart SA, Stockwell BR, Hacohen N, Hahn WC, Lander ES, + Sabatini DM, Root DE (2006) A lentiviral RNAi library for human and + mouse genes applied to an arrayed viral high-content screen. Cell, + 124(6):1283-98 / :DOI: `10.1016/j.cell.2006.01.040` PMID 16564017 + + .. [2] GitHub licensing discussion + https://github.com/CellProfiler/examples/issues/41 + + """ + return _load('data/mitosis.tif') + + +def cell(): + """Cell floating in saline. + + This is a quantitative phase image retrieved from a digital hologram using + the Python library ``qpformat``. The image shows a cell with high phase + value, above the background phase. + + Because of a banding pattern artifact in the background, this image is a + good test of thresholding algorithms. The pixel spacing is 0.107 µm. + + These data were part of a comparison between several refractive index + retrieval techniques for spherical objects as part of [1]_. + + This image is CC0, dedicated to the public domain. You may copy, modify, or + distribute it without asking permission. + + Returns + ------- + cell : (660, 550) uint8 array + Image of a cell. + + References + ---------- + .. [1] Paul Müller, Mirjam Schürmann, Salvatore Girardo, Gheorghe Cojoc, + and Jochen Guck. "Accurate evaluation of size and refractive index + for spherical objects in quantitative phase imaging." Optics Express + 26(8): 10729-10743 (2018). :DOI:`10.1364/OE.26.010729` + """ + return _load('data/cell.png') + + +def coins(): + """Greek coins from Pompeii. + + This image shows several coins outlined against a gray background. + It is especially useful in, e.g. segmentation tests, where + individual objects need to be identified against a background. + The background shares enough grey levels with the coins that a + simple segmentation is not sufficient. + + Notes + ----- + This image was downloaded from the + `Brooklyn Museum Collection + `__. + + No known copyright restrictions. + + Returns + ------- + coins : (303, 384) uint8 ndarray + Coins image. + """ + return _load("data/coins.png") + + +def kidney(): + """Mouse kidney tissue. + + This biological tissue on a pre-prepared slide was imaged with confocal + fluorescence microscopy (Nikon C1 inverted microscope). + Image shape is (16, 512, 512, 3). That is 512x512 pixels in X-Y, + 16 image slices in Z, and 3 color channels + (emission wavelengths 450nm, 515nm, and 605nm, respectively). + Real-space voxel size is 1.24 microns in X-Y, and 1.25 microns in Z. + Data type is unsigned 16-bit integers. + + Notes + ----- + This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in + 2018. + License: CC0 + + Returns + ------- + kidney : (16, 512, 512, 3) uint16 ndarray + Kidney 3D multichannel image. + """ + return _load("data/kidney.tif") + + +def lily(): + """Lily of the valley plant stem. + + This plant stem on a pre-prepared slide was imaged with confocal + fluorescence microscopy (Nikon C1 inverted microscope). + Image shape is (922, 922, 4). That is 922x922 pixels in X-Y, + with 4 color channels. + Real-space voxel size is 1.24 microns in X-Y. + Data type is unsigned 16-bit integers. + + Notes + ----- + This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in + 2018. + License: CC0 + + Returns + ------- + lily : (922, 922, 4) uint16 ndarray + Lily 2D multichannel image. + """ + return _load("data/lily.tif") + + +def logo(): + """Scikit-image logo, a RGBA image. + + Returns + ------- + logo : (500, 500, 4) uint8 ndarray + Logo image. + """ + return _load("data/logo.png") + + +def microaneurysms(): + """Gray-level "microaneurysms" image. + + Detail from an image of the retina (green channel). + The image is a crop of image 07_dr.JPG from the + High-Resolution Fundus (HRF) Image Database: + https://www5.cs.fau.de/research/data/fundus-images/ + + Notes + ----- + No copyright restrictions. CC0 given by owner (Andreas Maier). + + Returns + ------- + microaneurysms : (102, 102) uint8 ndarray + Retina image with lesions. + + References + ---------- + .. [1] Budai, A., Bock, R, Maier, A., Hornegger, J., + Michelson, G. (2013). Robust Vessel Segmentation in Fundus + Images. International Journal of Biomedical Imaging, vol. 2013, + 2013. + :DOI:`10.1155/2013/154860` + """ + return _load("data/microaneurysms.png") + + +def moon(): + """Surface of the moon. + + This low-contrast image of the surface of the moon is useful for + illustrating histogram equalization and contrast stretching. + + Returns + ------- + moon : (512, 512) uint8 ndarray + Moon image. + """ + return _load("data/moon.png") + + +def page(): + """Scanned page. + + This image of printed text is useful for demonstrations requiring uneven + background illumination. + + Returns + ------- + page : (191, 384) uint8 ndarray + Page image. + """ + return _load("data/page.png") + + +def horse(): + """Black and white silhouette of a horse. + + This image was downloaded from + `openclipart ` + + No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)). + + Returns + ------- + horse : (328, 400) bool ndarray + Horse image. + """ + return img_as_bool(_load("data/horse.png", as_gray=True)) + + +def clock(): + """Motion blurred clock. + + This photograph of a wall clock was taken while moving the camera in an + approximately horizontal direction. It may be used to illustrate + inverse filters and deconvolution. + + Released into the public domain by the photographer (Stefan van der Walt). + + Returns + ------- + clock : (300, 400) uint8 ndarray + Clock image. + """ + return _load("data/clock_motion.png") + + +def immunohistochemistry(): + """Immunohistochemical (IHC) staining with hematoxylin counterstaining. + + This picture shows colonic glands where the IHC expression of FHL2 protein + is revealed with DAB. Hematoxylin counterstaining is applied to enhance the + negative parts of the tissue. + + This image was acquired at the Center for Microscopy And Molecular Imaging + (CMMI). + + No known copyright restrictions. + + Returns + ------- + immunohistochemistry : (512, 512, 3) uint8 ndarray + Immunohistochemistry image. + """ + return _load("data/ihc.png") + + +def chelsea(): + """Chelsea the cat. + + An example with texture, prominent edges in horizontal and diagonal + directions, as well as features of differing scales. + + Notes + ----- + No copyright restrictions. CC0 by the photographer (Stefan van der Walt). + + Returns + ------- + chelsea : (300, 451, 3) uint8 ndarray + Chelsea image. + """ + return _load("data/chelsea.png") + + +# Define an alias for chelsea that is more descriptive. +cat = chelsea + + +def coffee(): + """Coffee cup. + + This photograph is courtesy of Pikolo Espresso Bar. + It contains several elliptical shapes as well as varying texture (smooth + porcelain to coarse wood grain). + + Notes + ----- + No copyright restrictions. CC0 by the photographer (Rachel Michetti). + + Returns + ------- + coffee : (400, 600, 3) uint8 ndarray + Coffee image. + """ + return _load("data/coffee.png") + + +def hubble_deep_field(): + """Hubble eXtreme Deep Field. + + This photograph contains the Hubble Telescope's farthest ever view of + the universe. It can be useful as an example for multi-scale + detection. + + Notes + ----- + This image was downloaded from + `HubbleSite + `__. + + The image was captured by NASA and `may be freely used in the public domain + `_. + + Returns + ------- + hubble_deep_field : (872, 1000, 3) uint8 ndarray + Hubble deep field image. + """ + return _load("data/hubble_deep_field.jpg") + + +def retina(): + """Human retina. + + This image of a retina is useful for demonstrations requiring circular + images. + + Notes + ----- + This image was downloaded from + `wikimedia `. + This file is made available under the Creative Commons CC0 1.0 Universal + Public Domain Dedication. + + References + ---------- + .. [1] Häggström, Mikael (2014). "Medical gallery of Mikael Häggström 2014". + WikiJournal of Medicine 1 (2). :DOI:`10.15347/wjm/2014.008`. + ISSN 2002-4436. Public Domain + + Returns + ------- + retina : (1411, 1411, 3) uint8 ndarray + Retina image in RGB. + """ + return _load("data/retina.jpg") + + +def shepp_logan_phantom(): + """Shepp Logan Phantom. + + References + ---------- + .. [1] L. A. Shepp and B. F. Logan, "The Fourier reconstruction of a head + section," in IEEE Transactions on Nuclear Science, vol. 21, + no. 3, pp. 21-43, June 1974. :DOI:`10.1109/TNS.1974.6499235` + + Returns + ------- + phantom : (400, 400) float64 image + Image of the Shepp-Logan phantom in grayscale. + """ + return _load("data/phantom.png", as_gray=True) + + +def colorwheel(): + """Color Wheel. + + Returns + ------- + colorwheel : (370, 371, 3) uint8 image + A colorwheel. + """ + return _load("data/color.png") + + +def palisades_of_vogt(): + """Return image sequence of in-vivo tissue showing the palisades of Vogt. + + In the human eye, the palisades of Vogt are normal features of the corneal + limbus, which is the border between the cornea and the sclera (i.e., the + white of the eye). + In the image sequence, there are some dark spots due to the presence of + dust on the reference mirror. + + Returns + ------- + palisades_of_vogt: (60, 1440, 1440) uint16 ndarray + + Notes + ----- + See info under `in-vivo-cornea-spots.tif` at + https://gitlab.com/scikit-image/data/-/blob/master/README.md#data. + + """ + return _load('data/palisades_of_vogt.tif') + + +def rocket(): + """Launch photo of DSCOVR on Falcon 9 by SpaceX. + + This is the launch photo of Falcon 9 carrying DSCOVR lifted off from + SpaceX's Launch Complex 40 at Cape Canaveral Air Force Station, FL. + + Notes + ----- + This image was downloaded from + `SpaceX Photos + `__. + + The image was captured by SpaceX and `released in the public domain + `_. + + Returns + ------- + rocket : (427, 640, 3) uint8 ndarray + Rocket image. + """ + return _load("data/rocket.jpg") + + +def stereo_motorcycle(): + """Rectified stereo image pair with ground-truth disparities. + + The two images are rectified such that every pixel in the left image has + its corresponding pixel on the same scanline in the right image. That means + that both images are warped such that they have the same orientation but a + horizontal spatial offset (baseline). The ground-truth pixel offset in + column direction is specified by the included disparity map. + + The two images are part of the Middlebury 2014 stereo benchmark. The + dataset was created by Nera Nesic, Porter Westling, Xi Wang, York Kitajima, + Greg Krathwohl, and Daniel Scharstein at Middlebury College. A detailed + description of the acquisition process can be found in [1]_. + + The images included here are down-sampled versions of the default exposure + images in the benchmark. The images are down-sampled by a factor of 4 using + the function `skimage.transform.downscale_local_mean`. The calibration data + in the following and the included ground-truth disparity map are valid for + the down-sampled images:: + + Focal length: 994.978px + Principal point x: 311.193px + Principal point y: 254.877px + Principal point dx: 31.086px + Baseline: 193.001mm + + Returns + ------- + img_left : (500, 741, 3) uint8 ndarray + Left stereo image. + img_right : (500, 741, 3) uint8 ndarray + Right stereo image. + disp : (500, 741, 3) float ndarray + Ground-truth disparity map, where each value describes the offset in + column direction between corresponding pixels in the left and the right + stereo images. E.g. the corresponding pixel of + ``img_left[10, 10 + disp[10, 10]]`` is ``img_right[10, 10]``. + NaNs denote pixels in the left image that do not have ground-truth. + + Notes + ----- + The original resolution images, images with different exposure and + lighting, and ground-truth depth maps can be found at the Middlebury + website [2]_. + + References + ---------- + .. [1] D. Scharstein, H. Hirschmueller, Y. Kitajima, G. Krathwohl, N. + Nesic, X. Wang, and P. Westling. High-resolution stereo datasets + with subpixel-accurate ground truth. In German Conference on Pattern + Recognition (GCPR 2014), Muenster, Germany, September 2014. + .. [2] http://vision.middlebury.edu/stereo/data/scenes2014/ + + """ + filename = _fetch("data/motorcycle_disp.npz") + # np.load of npz file holds onto open file handle. + with np.load(filename) as data: + disp = data['arr_0'] + return (_load("data/motorcycle_left.png"), _load("data/motorcycle_right.png"), disp) + + +def lfw_subset(): + """Subset of data from the LFW dataset. + + This database is a subset of the LFW database containing: + + * 100 faces + * 100 non-faces + + The full dataset is available at [2]_. + + Returns + ------- + images : (200, 25, 25) uint8 ndarray + 100 first images are faces and subsequent 100 are non-faces. + + Notes + ----- + The faces were randomly selected from the LFW dataset and the non-faces + were extracted from the background of the same dataset. The cropped ROIs + have been resized to a 25 x 25 pixels. + + References + ---------- + .. [1] Huang, G., Mattar, M., Lee, H., & Learned-Miller, E. G. (2012). + Learning to align from scratch. In Advances in Neural Information + Processing Systems (pp. 764-772). + .. [2] http://vis-www.cs.umass.edu/lfw/ + + """ + return np.load(_fetch('data/lfw_subset.npy')) + + +def skin(): + """Microscopy image of dermis and epidermis (skin layers). + + Hematoxylin and eosin stained slide at 10x of normal epidermis and dermis + with a benign intradermal nevus. + + Notes + ----- + This image requires an Internet connection the first time it is called, + and to have the ``pooch`` package installed, in order to fetch the image + file from the scikit-image datasets repository. + + The source of this image is + https://en.wikipedia.org/wiki/File:Normal_Epidermis_and_Dermis_with_Intradermal_Nevus_10x.JPG + + The image was released in the public domain by its author Kilbad. + + Returns + ------- + skin : (960, 1280, 3) RGB image of uint8 + """ + return _load('data/skin.jpg') + + +def nickel_solidification(): + """Image sequence of synchrotron x-radiographs showing the rapid + solidification of a nickel alloy sample. + + Returns + ------- + nickel_solidification: (11, 384, 512) uint16 ndarray + + Notes + ----- + See info under `nickel_solidification.tif` at + https://gitlab.com/scikit-image/data/-/blob/master/README.md#data. + + """ + return _load('data/solidification.tif') + + +def protein_transport(): + """Microscopy image sequence with fluorescence tagging of proteins + re-localizing from the cytoplasmic area to the nuclear envelope. + + Returns + ------- + protein_transport: (15, 2, 180, 183) uint8 ndarray + + Notes + ----- + See info under `NPCsingleNucleus.tif` at + https://gitlab.com/scikit-image/data/-/blob/master/README.md#data. + + """ + return _load('data/protein_transport.tif') + + +def brain(): + """Subset of data from the University of North Carolina Volume Rendering + Test Data Set. + + The full dataset is available at [1]_. + + Returns + ------- + image : (10, 256, 256) uint16 ndarray + + Notes + ----- + The 3D volume consists of 10 layers from the larger volume. + + References + ---------- + .. [1] https://graphics.stanford.edu/data/voldata/ + + """ + return _load("data/brain.tiff") + + +def vortex(): + """Case B1 image pair from the first PIV challenge. + + Returns + ------- + image0, image1 : (512, 512) grayscale images + A pair of images featuring synthetic moving particles. + + Notes + ----- + This image was licensed as CC0 by its author, Prof. Koji Okamoto, with + thanks to Prof. Jun Sakakibara, who maintains the PIV Challenge site. + + References + ---------- + .. [1] Particle Image Velocimetry (PIV) Challenge site + http://pivchallenge.org + .. [2] 1st PIV challenge Case B: http://pivchallenge.org/pub/index.html#b + """ + return ( + _load('data/pivchallenge-B-B001_1.tif'), + _load('data/pivchallenge-B-B001_2.tif'), + ) diff --git a/envs/kitoverlay/skimage/data/_registry.py b/envs/kitoverlay/skimage/data/_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..017d268bc4b9f07cc9bb82318e9f0bee961871cd --- /dev/null +++ b/envs/kitoverlay/skimage/data/_registry.py @@ -0,0 +1,191 @@ +# Registry of datafiles that can be downloaded along with their SHA256 hashes +# To generate the SHA256 hash, use the command +# openssl sha256 filename +registry = { + "color/data/lab_array_a_10.npy": "a3ef76f1530e374f9121020f1f220bc89767dc866f4bbd1b1f47e5b84891a38c", + "color/data/lab_array_a_2.npy": "793d5981cbffceb14b5fb589f998a2b1acdb5ff9c14d364c8e9e8bd45a80b275", + "color/data/lab_array_a_r.npy": "3d3613da109d0c87827525fc49b58111aefc12438fa6426654979f66807b9227", + "color/data/lab_array_b_10.npy": "e8d648b28077c1bfcef55ec6dc8679819612b56a01647f8c0a78625bb06f99b6", + "color/data/lab_array_b_2.npy": "da9c6aa99e4ab3af8ec3107bbf11647cc483a0760285dd5c9fb66988be393ca1", + "color/data/lab_array_b_r.npy": "d9eee96f4d65a2fbba82039508aac8c18304752ee8e33233e2a013e65bb91464", + "color/data/lab_array_c_10.npy": "88b4ff2a2d2c4f48e7bb265609221d4b9ef439a4e2d8a86989696bfdb47790e6", + "color/data/lab_array_c_2.npy": "e1b8acfdc7284ab9cd339de66948134304073b6f734ecf9ad42f8297b83d3405", + "color/data/lab_array_c_r.npy": "09ffba2ed69e467864fea883493cd2d2706da028433464e3e858a8086842867e", + "color/data/lab_array_d50_10.npy": "42e2ff26cb10e2a98fcf1bc06c2483302ff4fabf971fe8d49b530f490b5d24c7", + "color/data/lab_array_d50_2.npy": "4aa03b7018ff7276643d3c082123cf07304f9d8d898ae92a5756a86955de4faf", + "color/data/lab_array_d50_r.npy": "57db02009f9a68dade33ce1ecffead0418d8ac8113b2a589fc02a20e6bf7e799", + "color/data/lab_array_d55_10.npy": "ab4f21368b6d8351578ab093381c44b49ae87a6b7f25c11aa094b07f215eed7d", + "color/data/lab_array_d55_2.npy": "0319723de4632a252bae828b7c96d038fb075a7df05beadfbad653da05efe372", + "color/data/lab_array_d55_r.npy": "060ebc446f7b4da4df58a60f0006133dbca735da87ba61854f4a75d28db67a3a", + "color/data/lab_array_d65_10.npy": "5cb9e9c384d2577aaf8b7d2d21ff5b505708b80605a2f59d10e89d22c3d308d2", + "color/data/lab_array_d65_2.npy": "16e847160f7ba4f19806d8194ed44a6654c9367e5a2cb240aa6e7eece44a6649", + "color/data/lab_array_d65_r.npy": "82d0dd7a46741f627b8868793e64cdc2f9944fe1e049b573f752a93760a1577c", + "color/data/lab_array_d75_10.npy": "c2d3de5422c785c925926b0c6223aeaf50b9393619d1c30830190d433606cbe1", + "color/data/lab_array_d75_2.npy": "c94d53da398d36e076471ff7e0dafcaffc64ce4ba33b4d04849c32d19c87494a", + "color/data/lab_array_e_2.npy": "ac05f17a83961b020ceccbdd46bddc86943d43e678dabcc898caf4a1e4be6165", + "color/data/luv_array_a_10.npy": "c8af67f9fd64a6e9c610ac0c12c5315a49ca229363f048e5d851409d4a3ae5b6", + "color/data/luv_array_a_2.npy": "eaf05dc61f4a70ece367d5e751a14d42b7c397c7b1c2df4cfecec9ddf26e1c1a", + "color/data/luv_array_a_r.npy": "2c0891add787ec757601f9c61ad14dd9621dd969af4e32753f2e64df437081b7", + "color/data/luv_array_b_10.npy": "a5407736b8a43071139ca178d12cdf930f32f52a0644f0b13f89d8895c8b43db", + "color/data/luv_array_b_2.npy": "8e74173d54dc549b6c0ebd1f1d70489d2905cad87744e41ed74384f21f22986d", + "color/data/luv_array_b_r.npy": "0a74c41df369cbb5fc0a00c16d60dc6f946ebf144bc5e506545b0d160fa53dfa", + "color/data/luv_array_c_10.npy": "3a5f975ffa57f69a1be9e02b153e8161f83040ce3002ea1b0a05b9fbdd0d8ec4", + "color/data/luv_array_c_2.npy": "32506cd50ea2181997cb88d3511e275740e8151d6c693cd178f5eafd8b0c6e47", + "color/data/luv_array_c_r.npy": "c0fbf98cc0e62ed426ab4d228986d6660089444a7bbfcc64cbb1c632644067bb", + "color/data/luv_array_d50_10.npy": "fe223db556222ce3a59198bed3a3324c2c719b8083fb84dc5b00f214b4773b16", + "color/data/luv_array_d50_2.npy": "48e8989048904bdf2c3c1ada265c1c29c5eff60f02f848a25cde622982c84901", + "color/data/luv_array_d50_r.npy": "f93f0def9c93f872dd10ce4a91fdb3f06eea61ddb6e72387b7669909827d4f9c", + "color/data/luv_array_d55_10.npy": "d88d53d2bad230c2331442187712ec52ffdee62bf0f60b200c33411bfed76c60", + "color/data/luv_array_d55_2.npy": "c761b40475df591ae9c0475d54ef712d067190ca4652efc6308b69080a652061", + "color/data/luv_array_d55_r.npy": "05fbd57e3602ee4d5202b9f18f9b5fc05b545891a9b4456d2a88aa798a5a774a", + "color/data/luv_array_d65_10.npy": "41a5452ffac4d31dd579d9528e725432c60d77b5f505d801898d9401429c89bf", + "color/data/luv_array_d65_2.npy": "962ce180132c6c11798cbc423b2b204d1d10187670f6eb5dec1058eaad301e0e", + "color/data/luv_array_d65_r.npy": "78db8c19af26dd802ce98b039a33855f7c8d6a103a2721d094b1d9c619717449", + "color/data/luv_array_d75_10.npy": "e1cc70d56eb6789633d4c2a4059b9533f616a7c8592c9bd342403e41d72f45e4", + "color/data/luv_array_d75_2.npy": "07db3bd59bd89de8e5ff62dad786fe5f4b299133495ba9bea30495b375133a98", + "color/data/luv_array_e_2.npy": "41b1037d81b267305ffe9e8e97e0affa9fa54b18e60413b01b8f11861cb32213", + "color/ciede2000_test_data.txt": "2e005c6f76ddfb7bbcc8f68490f1f7b4b4a2a4b06b36a80c985677a2799c0e40", + "data/astronaut.png": "88431cd9653ccd539741b555fb0a46b61558b301d4110412b5bc28b5e3ea6cb5", + "data/brick.png": "7966caf324f6ba843118d98f7a07746d22f6a343430add0233eca5f6eaaa8fcf", + "data/cell.png": "8d23a7fb81f7cc877cd09f330357fc7f595651306e84e17252f6e0a1b3f61515", + "data/camera.png": "b0793d2adda0fa6ae899c03989482bff9a42d3d5690fc7e3648f2795d730c23a", + "data/chessboard_GRAY.png": "3e51870774515af4d07d820bd8827364c70839bf9b573c746e485095e893df90", + "data/chessboard_RGB.png": "1ac01eff2d4e50f4eda55a2ddecdc28a6576623a58d7a7ef84513c5cc19a0331", + "data/chelsea.png": "596aa1e7cb875eb79f437e310381d26b338a81c2da23439704a73c4651e8c4bb", + "data/clock_motion.png": "f029226b28b642e80113d86622e9b215ee067a0966feaf5e60604a1e05733955", + "data/coffee.png": "cc02f8ca188b167c775a7101b5d767d1e71792cf762c33d6fa15a4599b5a8de7", + "data/coins.png": "f8d773fc9cfa6f4d8e5942dc34d0a0788fcaed2a4fefbbed0aef5398d7ef4cba", + "data/color.png": "7d2df993de2b4fa2a78e04e5df8050f49a9c511aa75e59ab3bd56ac9c98aef7e", + "data/eagle.png": "928f1bbe7403b533265f56db3a6b07c835dfa8e2513f5c5075ca2f1960f6179e", + "data/horse.png": "c7fb60789fe394c485f842291ea3b21e50d140f39d6dcb5fb9917cc178225455", + "data/grass.png": "b6b6022426b38936c43a4ac09635cd78af074e90f42ffa8227ac8b7452d39f89", + "data/hubble_deep_field.jpg": "3a19c5dd8a927a9334bb1229a6d63711b1c0c767fb27e2286e7c84a3e2c2f5f4", + "data/ihc.png": "f8dd1aa387ddd1f49d8ad13b50921b237df8e9b262606d258770687b0ef93cef", + "data/logo.png": "f2c57fe8af089f08b5ba523d95573c26e62904ac5967f4c8851b27d033690168", + "data/lfw_subset.npy": "9560ec2f5edfac01973f63a8a99d00053fecd11e21877e18038fbe500f8e872c", + "data/microaneurysms.png": "a1e1be59aa447f8ce082f7fa809997ab369a2b137cb6c4202abc647c7ccf6456", + "data/moon.png": "78739619d11f7eb9c165bb5d2efd4772cee557812ec847532dbb1d92ef71f577", + "data/motorcycle_left.png": "db18e9c4157617403c3537a6ba355dfeafe9a7eabb6b9b94cb33f6525dd49179", + "data/motorcycle_right.png": "5fc913ae870e42a4b662314bc904d1786bcad8e2f0b9b67dba5a229406357797", + "data/motorcycle_disp.npz": "2e49c8cebff3fa20359a0cc6880c82e1c03bbb106da81a177218281bc2f113d7", + "data/mssim_matlab_output.npz": "cc11a14bfa040c75b02db32282439f2e2e3e96779196c171498afaa70528ed7a", + "data/page.png": "341a6f0a61557662b02734a9b6e56ec33a915b2c41886b97509dedf2a43b47a3", + "data/phantom.png": "552ff698167aa402cceb17981130607a228a0a0aa7c519299eaa4d5f301ba36c", + "data/retina.jpg": "38a07f36f27f095e818aea7b96d34202c05176d30253c66733f2e00379e9e0e6", + "data/rocket.jpg": "c2dd0de7c538df8d111e479619b129464d0269d0ae5fd18ca91d33a7fdfea95c", + "data/gravel.png": "c48615b451bf1e606fbd72c0aa9f8cc0f068ab7111ef7d93bb9b0f2586440c12", + "data/text.png": "bd84aa3a6e3c9887850d45d606c96b2e59433fbef50338570b63c319e668e6d1", + "data/chessboard_GRAY_U16.tif": "9fd3392c5b6cbc5f686d8ff83eb57ef91d038ee0852ac26817e5ac99df4c7f45", + "data/chessboard_GRAY_U16B.tif": "b0a9270751f0fc340c90b8b615b62b88187b9ab5995942717566735d523cddb2", + "data/chessboard_GRAY_U8.npy": "71f394694b721e8a33760a355b3666c9b7d7fc1188ff96b3cd23c2a1d73a38d8", + "data/lbpcascade_frontalface_opencv.xml": "03097789a3dcbb0e40d20b9ef82537dbc3b670b6a7f2268d735470f22e003a91", + "data/astronaut_GRAY_hog_L1.npy": "5d8ab22b166d1dd49c12caeff9d178ed28132efea3852b952e9d75f7f7f94954", + "data/astronaut_GRAY_hog_L2-Hys.npy": "c4dd6e50d1129aada358311cf8880ce8c775f31e0e550fc322c16e43a96d56fe", + "data/rank_filter_tests.npz": "efaf5699630f4a53255e91681dc72a965acd4a8aa1f84671c686fb93e7df046d", + "data/rank_filters_tests_3d.npz": "1741c2b978424e93558a07d345b2a0d9bfbb33c095c123da147fca066714ab16", + "data/palette_color.png": "c4e817035fb9f7730fe95cff1da3866dea01728efc72b6e703d78f7ab9717bdd", + "data/palette_gray.png": "bace7f73783bf3ab3b7fdaf701707e4fa09f0dbd0ea72cf5b12ddc73d50b02a9", + "data/green_palette.png": "42d49d94be8f9bc76e50639d3701ed0484258721f6b0bd7f50bb1b9274a010f0", + "data/truncated.jpg": "4c226038acc78012d335efba29c6119a24444a886842182b7e18db378f4a557d", + "data/multipage.tif": "4da0ad0d3df4807a9847247d1b5e565b50d46481f643afb5c37c14802c78130f", + "data/multipage_rgb.tif": "1d23b844fd38dce0e2d06f30432817cdb85e52070d8f5460a2ba58aebf34a0de", + "data/no_time_for_that_tiny.gif": "20abe94ba9e45f18de416c5fbef8d1f57a499600be40f9a200fae246010eefce", + "data/foo3x5x4indexed.png": "48a64c25c6da000ffdb5fcc34ebafe9ba3b1c9b61d7984ea7ca6dc54f9312dfa", + "data/gray_morph_output.npz": "49a0dae607cd8d31e134b4bfcbf0d86b13751fdce9667d8bf1ade93d435191b1", + "data/disk-matlab-output.npz": "8a39d5c866f6216d6a9c9166312aa4bbf4d18fab3d0dcd963c024985bde5856b", + "data/diamond-matlab-output.npz": "02fca68907e2b252b501dfe977eef71ae39fadaaa3702ebdc855195422ae1cc2", + "data/bw_text.png": "308c2b09f8975a69b212e103b18520e8cbb7a4eccfce0f757836cd371f1b9094", + "data/bw_text_skeleton.npy": "9ff4fc23c6a01497d7987f14e3a97cbcc39cce54b2b3b7ee33b84c1b661d0ae1", + "data/_blobs_3d_fiji_skeleton.tif": "e3449ad9819425959952050c147278555e5ffe1c2c4a30df29f6a1f9023e10c3", + "data/checker_bilevel.png": "2e207e486545874a2a3e69ba653b28fdef923157be9017559540e65d1bcb8e28", + "restoration/astronaut_rl.npy": "3f8373e2c6182a89366e51cef6624e3625deac75fdda1079cbdad2a33322152c", + "restoration/camera_rl.npy": "fd4f59af84dd471fbbe79ee70c1b7e68a69864c461f0db5ac587e7975363f78f", + "restoration/camera_unsup.npy": "3de10a0b97267352b18886b25d66a967f9e1d78ada61050577d78586cab82baa", + "restoration/camera_unsup2.npy": "29cdc60605eb528c5f014baa8564d7d1ba0bd4b3170a66522058cbe5aed0960b", + "restoration/camera_wiener.npy": "4505ea8b0d63d03250c6d756560d615751b76dd6ffc4a95972fa260c0c84633e", + "registration/data/OriginalX-130Y130.png": "bf24a06d99ae131c97e582ef5e1cd0c648a8dad0caab31281f3564045492811f", + "registration/data/OriginalX130Y130.png": "7fdd4c06d504fec35ee0703bd7ed2c08830b075a74c8506bae4a70d682f5a2db", + "registration/data/OriginalX75Y75.png": "c5cd58893c93140df02896df80b13ecf432f5c86eeaaf8fb311aec52a65c7016", + "registration/data/TransformedX-130Y130.png": "1cda90ed69c921eb7605b73b76d141cf4ea03fb8ce3336445ca08080e40d7375", + "registration/data/TransformedX130Y130.png": "bb10c6ae3f91a313b0ac543efdb7ca69c4b95e55674c65a88472a6c4f4692a25", + "registration/data/TransformedX75Y75.png": "a1e9ead5f8e4a0f604271e1f9c50e89baf53f068f1d19fab2876af4938e695ea", + "data/brain.tiff": "bcdbaf424fbad7b1fb0f855f608c68e5a838f35affc323ff04ea17f678eef5c6", + "data/cells3d.tif": "afc7c7d80d38bfde09788b4064ac1e64ec14e88454ab785ebdc8dbba5ca3b222", + "data/palisades_of_vogt.tif": "7f205b626407e194974cead67c4d3909344cf59c42d229a349da0198183e5bd0", + "data/kidney.tif": "80c0799bc58b08cf6eaa53ecd202305eb42fd7bc73746cb6c5064dbeae7e8476", + "data/lily.tif": "395c2f0194c25b9824a8cd79266920362a0816bc9e906dd392adce2d8309af03", + "data/mitosis.tif": "2751ba667c4067c5d30817cff004aa06f6f6287f1cdbb5b8c9c6a500308cb456", + "data/skin.jpg": "8759fe080509712163453f4b17106582b8513e73b0788d80160abf840e272075", + "data/pivchallenge-B-B001_1.tif": "e95e09abbcecba723df283ac7d361766328abd943701a2ec2f345d4a2014da2a", + "data/pivchallenge-B-B001_2.tif": "4ceb5407e4e333476a0f264c14b7a3f6c0e753fcdc99ee1c4b8196e5f823805e", + "data/protein_transport.tif": "a8e24e8d187f33e92ee28508d5615286c850ca75374af7e74e527d290e8b06ea", + "data/solidification.tif": "50ef9a52c621b7c0c506ad1fe1b8ee8a158a4d7c8e50ddfce1e273a422dca3f9", +} + +registry_urls = { + "data/brain.tiff": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/brain.tiff", + "data/cells3d.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/cells3d.tif", + "data/palisades_of_vogt.tif": "https://gitlab.com/scikit-image/data/-/raw/b2bc880f3bac23a583724befe8388dae368c52fe/in-vivo-cornea-spots.tif", + "data/eagle.png": "https://gitlab.com/scikit-image/data/-/raw/1e4f62ac31ba4553d176d4473a5967ad1b076d62/eagle.png", + "data/kidney.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/kidney-tissue-fluorescence.tif", + "data/lily.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/lily-of-the-valley-fluorescence.tif", + "data/mitosis.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/AS_09125_050116030001_D03f00d0.tif", + "data/rank_filters_tests_3d.npz": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/Tests_besides_Equalize_Otsu/add18_entropy/rank_filters_tests_3d.npz", + "data/skin.jpg": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/Normal_Epidermis_and_Dermis_with_Intradermal_Nevus_10x.JPG", + "data/pivchallenge-B-B001_1.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/pivchallenge/B/B001_1.tif", + "data/pivchallenge-B-B001_2.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/pivchallenge/B/B001_2.tif", + "data/protein_transport.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/NPCsingleNucleus.tif", + "data/solidification.tif": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/nickel_solidification.tif", + "restoration/astronaut_rl.npy": "https://gitlab.com/scikit-image/data/-/raw/2cdc5ce89b334d28f06a58c9f0ca21aa6992a5ba/astronaut_rl.npy", + "data/gray_morph_output.npz": "https://gitlab.com/scikit-image/data/-/raw/806548e112bcf2b708a9a32275d335cb592480fd/Tests_besides_Equalize_Otsu/gray_morph_output.npz", + "data/_blobs_3d_fiji_skeleton.tif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/_blobs_3d_fiji_skeleton.tif", + "data/astronaut.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/astronaut.png", + "data/astronaut_GRAY_hog_L1.npy": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/astronaut_GRAY_hog_L1.npy", + "data/astronaut_GRAY_hog_L2-Hys.npy": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/astronaut_GRAY_hog_L2-Hys.npy", + "data/brick.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/brick.png", + "data/bw_text.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/bw_text.png", + "data/bw_text_skeleton.npy": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/bw_text_skeleton.npy", + "data/camera.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/camera.png", + "data/cell.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/cell.png", + "data/checker_bilevel.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/checker_bilevel.png", + "data/chelsea.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chelsea.png", + "data/chessboard_GRAY.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chessboard_GRAY.png", + "data/chessboard_GRAY_U16.tif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chessboard_GRAY_U16.tif", + "data/chessboard_GRAY_U16B.tif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chessboard_GRAY_U16B.tif", + "data/chessboard_GRAY_U8.npy": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chessboard_GRAY_U8.npy", + "data/chessboard_RGB.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/chessboard_RGB.png", + "data/clock_motion.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/clock_motion.png", + "data/coffee.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/coffee.png", + "data/coins.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/coins.png", + "data/color.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/color.png", + "data/diamond-matlab-output.npz": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/diamond-matlab-output.npz", + "data/disk-matlab-output.npz": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/disk-matlab-output.npz", + "data/foo3x5x4indexed.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/foo3x5x4indexed.png", + "data/grass.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/grass.png", + "data/gravel.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/gravel.png", + "data/green_palette.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/green_palette.png", + "data/horse.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/horse.png", + "data/hubble_deep_field.jpg": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/hubble_deep_field.jpg", + "data/ihc.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/ihc.png", + "data/lbpcascade_frontalface_opencv.xml": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/lbpcascade_frontalface_opencv.xml", + "data/lfw_subset.npy": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/lfw_subset.npy", + "data/logo.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/logo.png", + "data/microaneurysms.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/microaneurysms.png", + "data/moon.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/moon.png", + "data/motorcycle_disp.npz": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/motorcycle_disp.npz", + "data/motorcycle_left.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/motorcycle_left.png", + "data/motorcycle_right.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/motorcycle_right.png", + "data/mssim_matlab_output.npz": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/mssim_matlab_output.npz", + "data/multipage.tif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/multipage.tif", + "data/multipage_rgb.tif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/multipage_rgb.tif", + "data/no_time_for_that_tiny.gif": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/no_time_for_that_tiny.gif", + "data/page.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/page.png", + "data/palette_color.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/palette_color.png", + "data/palette_gray.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/palette_gray.png", + "data/phantom.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/phantom.png", + "data/rank_filter_tests.npz": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/rank_filter_tests.npz", + "data/retina.jpg": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/retina.jpg", + "data/rocket.jpg": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/rocket.jpg", + "data/text.png": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/text.png", + "data/truncated.jpg": "https://gitlab.com/scikit-image/data/-/raw/5c090b56df3988d988ff97928e2ef2d2cbe38e1b/truncated.jpg", +} diff --git a/envs/kitoverlay/skimage/data/lbpcascade_frontalface_opencv.xml b/envs/kitoverlay/skimage/data/lbpcascade_frontalface_opencv.xml new file mode 100644 index 0000000000000000000000000000000000000000..b6bd1de10acfc9fa305146a6d6061f323884035b --- /dev/null +++ b/envs/kitoverlay/skimage/data/lbpcascade_frontalface_opencv.xml @@ -0,0 +1,1505 @@ + + + + + BOOST + LBP + 24 + 24 + + GAB + 0.9950000047683716 + 0.5000000000000000 + 0.9500000000000000 + 1 + 100 + + 256 + 20 + + + <_> + 3 + -0.7520892024040222 + + + <_> + + 0 -1 46 -67130709 -21569 -1426120013 -1275125205 -21585 + -16385 587145899 -24005 + + -0.6543210148811340 0.8888888955116272 + + <_> + + 0 -1 13 -163512766 -769593758 -10027009 -262145 -514457854 + -193593353 -524289 -1 + + -0.7739216089248657 0.7278633713722229 + + <_> + + 0 -1 2 -363936790 -893203669 -1337948010 -136907894 + 1088782736 -134217726 -741544961 -1590337 + + -0.7068563103675842 0.6761534214019775 + + <_> + 4 + -0.4872078299522400 + + + <_> + + 0 -1 84 2147483647 1946124287 -536870913 2147450879 + 738132490 1061101567 243204619 2147446655 + + -0.8083735704421997 0.7685696482658386 + + <_> + + 0 -1 21 2147483647 263176079 1879048191 254749487 1879048191 + -134252545 -268435457 801111999 + + -0.7698410153388977 0.6592915654182434 + + <_> + + 0 -1 106 -98110272 1610939566 -285484400 -850010381 + -189334372 -1671954433 -571026695 -262145 + + -0.7506558895111084 0.5444605946540833 + + <_> + + 0 -1 48 -798690576 -131075 1095771153 -237144073 -65569 -1 + -216727745 -69206049 + + -0.7775990366935730 0.5465461611747742 + + <_> + 4 + -1.1592328548431396 + + + <_> + + 0 -1 47 -21585 -20549 -100818262 -738254174 -20561 -36865 + -151016790 -134238549 + + -0.5601882934570313 0.7743113040924072 + + <_> + + 0 -1 12 -286003217 183435247 -268994614 -421330945 + -402686081 1090387966 -286785545 -402653185 + + -0.6124526262283325 0.6978127956390381 + + <_> + + 0 -1 26 -50347012 970882927 -50463492 -1253377 -134218251 + -50364513 -33619992 -172490753 + + -0.6114496588706970 0.6537628173828125 + + <_> + + 0 -1 8 -273 -135266321 1877977738 -2088243418 -134217987 + 2146926575 -18910642 1095231247 + + -0.6854077577590942 0.5403239130973816 + + <_> + 5 + -0.7562355995178223 + + + <_> + + 0 -1 96 -1273 1870659519 -20971602 -67633153 -134250731 + 2004875127 -250 -150995969 + + -0.4051094949245453 0.7584033608436585 + + <_> + + 0 -1 33 -868162224 -76810262 -4262145 -257 1465211989 + -268959873 -2656269 -524289 + + -0.7388162612915039 0.5340843200683594 + + <_> + + 0 -1 57 -12817 -49 -541103378 -152950 -38993 -20481 -1153876 + -72478976 + + -0.6582943797111511 0.5339496731758118 + + <_> + + 0 -1 125 -269484161 -452984961 -319816180 -1594032130 -2111 + -990117891 -488975296 -520947741 + + -0.5981323719024658 0.5323504805564880 + + <_> + + 0 -1 53 557787431 670265215 -1342193665 -1075892225 + 1998528318 1056964607 -33570977 -1 + + -0.6498787999153137 0.4913350641727448 + + <_> + 5 + -0.8085358142852783 + + + <_> + + 0 -1 60 -536873708 880195381 -16842788 -20971521 -176687276 + -168427659 -16777260 -33554626 + + -0.5278195738792419 0.6946372389793396 + + <_> + + 0 -1 7 -1 -62981529 -1090591130 805330978 -8388827 -41945787 + -39577 -531118985 + + -0.5206505060195923 0.6329920291900635 + + <_> + + 0 -1 98 -725287348 1347747543 -852489 -16809993 1489881036 + -167903241 -1 -1 + + -0.7516061067581177 0.4232024252414703 + + <_> + + 0 -1 44 -32777 1006582562 -65 935312171 -8388609 -1078198273 + -1 733886267 + + -0.7639313936233521 0.4123568832874298 + + <_> + + 0 -1 24 -85474705 2138828511 -1036436754 817625855 + 1123369029 -58796809 -1013468481 -194513409 + + -0.5123769044876099 0.5791834592819214 + + <_> + 5 + -0.5549971461296082 + + + <_> + + 0 -1 42 -17409 -20481 -268457797 -134239493 -17473 -1 -21829 + -21846 + + -0.3763174116611481 0.7298233509063721 + + <_> + + 0 -1 6 -805310737 -2098262358 -269504725 682502698 + 2147483519 1740574719 -1090519233 -268472385 + + -0.5352765917778015 0.5659480094909668 + + <_> + + 0 -1 61 -67109678 -6145 -8 -87884584 -20481 -1073762305 + -50856216 -16849696 + + -0.5678374171257019 0.4961479902267456 + + <_> + + 0 -1 123 -138428633 1002418167 -1359008245 -1908670465 + -1346685918 910098423 -1359010520 -1346371657 + + -0.5706262588500977 0.4572288393974304 + + <_> + + 0 -1 9 -89138513 -4196353 1256531674 -1330665426 1216308261 + -36190633 33498198 -151796633 + + -0.5344601869583130 0.4672054052352905 + + <_> + 5 + -0.8776460289955139 + + + <_> + + 0 -1 105 1073769576 206601725 -34013449 -33554433 -789514004 + -101384321 -690225153 -264193 + + -0.7700348496437073 0.5943940877914429 + + <_> + + 0 -1 30 -1432340997 -823623681 -49153 -34291724 -269484035 + -1342767105 -1078198273 -1277955 + + -0.5043668746948242 0.6151274442672730 + + <_> + + 0 -1 35 -1067385040 -195758209 -436748425 -134217731 + -50855988 -129 -1 -1 + + -0.6808040738105774 0.4667325913906097 + + <_> + + 0 -1 119 832534325 -34111555 -26050561 -423659521 -268468364 + 2105014143 -2114244 -17367185 + + -0.4927591383457184 0.5401885509490967 + + <_> + + 0 -1 82 -1089439888 -1080524865 2143059967 -1114121 + -1140949004 -3 -2361356 -739516 + + -0.6445107460021973 0.4227822124958038 + + <_> + 6 + -1.1139287948608398 + + + <_> + + 0 -1 52 -1074071553 -1074003969 -1 -1280135430 -5324817 -1 + -335548482 582134442 + + -0.5307556986808777 0.6258179545402527 + + <_> + + 0 -1 99 -706937396 -705364068 -540016724 -570495027 + -570630659 -587857963 -33628164 -35848193 + + -0.5227634310722351 0.5049746036529541 + + <_> + + 0 -1 18 -2035630093 42119158 -268503053 -1671444 261017599 + 1325432815 1954394111 -805306449 + + -0.4983572661876679 0.5106441378593445 + + <_> + + 0 -1 111 -282529488 -1558073088 1426018736 -170526448 + -546832487 -5113037 -34243375 -570427929 + + -0.4990860521793366 0.5060507059097290 + + <_> + + 0 -1 92 1016332500 -606301707 915094269 -1080086049 + -1837027144 -1361600280 2147318747 1067975613 + + -0.5695009231567383 0.4460467398166657 + + <_> + + 0 -1 51 -656420166 -15413034 -141599534 -603435836 + 1505950458 -787556946 -79823438 -1326199134 + + -0.6590405106544495 0.3616424500942230 + + <_> + 7 + -0.8243625760078430 + + + <_> + + 0 -1 28 -901591776 -201916417 -262 -67371009 -143312112 + -524289 -41943178 -1 + + -0.4972776770591736 0.6027074456214905 + + <_> + + 0 -1 112 -4507851 -411340929 -268437513 -67502145 -17350859 + -32901 -71344315 -29377 + + -0.4383158981800079 0.5966237187385559 + + <_> + + 0 -1 69 -75894785 -117379438 -239063587 -12538500 1485072126 + 2076233213 2123118847 801906927 + + -0.6386105418205261 0.3977999985218048 + + <_> + + 0 -1 19 -823480413 786628589 -16876049 -1364262914 242165211 + 1315930109 -696268833 -455082829 + + -0.5512794256210327 0.4282079637050629 + + <_> + + 0 -1 73 -521411968 6746762 -1396236286 -2038436114 + -185612509 57669627 -143132877 -1041235973 + + -0.6418755054473877 0.3549866080284119 + + <_> + + 0 -1 126 -478153869 1076028979 -1645895615 1365298272 + -557859073 -339771473 1442574528 -1058802061 + + -0.4841901361942291 0.4668019413948059 + + <_> + + 0 -1 45 -246350404 -1650402048 -1610612745 -788400696 + 1467604861 -2787397 1476263935 -4481349 + + -0.5855734348297119 0.3879135847091675 + + <_> + 7 + -1.2237116098403931 + + + <_> + + 0 -1 114 -24819 1572863935 -16809993 -67108865 2146778388 + 1433927541 -268608444 -34865205 + + -0.2518476545810700 0.7088654041290283 + + <_> + + 0 -1 97 -1841359 -134271049 -32769 -5767369 -1116675 -2185 + -8231 -33603327 + + -0.4303432404994965 0.5283288359642029 + + <_> + + 0 -1 25 -1359507589 -1360593090 -1073778729 -269553812 + -809512977 1744707583 -41959433 -134758978 + + -0.4259553551673889 0.5440809130668640 + + <_> + + 0 -1 34 729753407 -134270989 -1140907329 -235200777 + 658456383 2147467263 -1140900929 -16385 + + -0.5605589151382446 0.4220733344554901 + + <_> + + 0 -1 134 -310380553 -420675595 -193005472 -353568129 + 1205338070 -990380036 887604324 -420544526 + + -0.5192656517028809 0.4399855434894562 + + <_> + + 0 -1 16 -1427119361 1978920959 -287119734 -487068946 + 114759245 -540578051 -707510259 -671660453 + + -0.5013077259063721 0.4570254683494568 + + <_> + + 0 -1 74 -738463762 -889949281 -328301948 -121832450 + -1142658284 -1863576559 2146417353 -263185 + + -0.4631414115428925 0.4790246188640595 + + <_> + 7 + -0.5544230937957764 + + + <_> + + 0 -1 113 -76228780 -65538 -1 -67174401 -148007 -33 -221796 + -272842924 + + -0.3949716091156006 0.6082032322883606 + + <_> + + 0 -1 110 369147696 -1625232112 2138570036 -1189900 790708019 + -1212613127 799948719 -4456483 + + -0.4855885505676270 0.4785369932651520 + + <_> + + 0 -1 37 784215839 -290015241 536832799 -402984963 + -1342414991 -838864897 -176769 -268456129 + + -0.4620285332202911 0.4989669024944305 + + <_> + + 0 -1 41 -486418688 -171915327 -340294900 -21938 -519766032 + -772751172 -73096060 -585322623 + + -0.6420643329620361 0.3624351918697357 + + <_> + + 0 -1 117 -33554953 -475332625 -1423463824 -2077230421 + -4849669 -2080505925 -219032928 -1071915349 + + -0.4820112884044647 0.4632140696048737 + + <_> + + 0 -1 65 -834130468 -134217476 -1349314083 -1073803559 + -619913764 -1449131844 -1386890321 -1979118423 + + -0.4465552568435669 0.5061788558959961 + + <_> + + 0 -1 56 -285249779 1912569855 -16530 -1731022870 -1161904146 + -1342177297 -268439634 -1464078708 + + -0.5190586447715759 0.4441480338573456 + + <_> + 7 + -0.7161560654640198 + + + <_> + + 0 -1 20 1246232575 1078001186 -10027057 60102 -277348353 + -43646987 -1210581153 1195769615 + + -0.4323809444904327 0.5663768053054810 + + <_> + + 0 -1 15 -778583572 -612921106 -578775890 -4036478 + -1946580497 -1164766570 -1986687009 -12103599 + + -0.4588732719421387 0.4547033011913300 + + <_> + + 0 -1 129 -1073759445 2013231743 -1363169553 -1082459201 + -1414286549 868185983 -1356133589 -1077936257 + + -0.5218553543090820 0.4111092388629913 + + <_> + + 0 -1 102 -84148365 -2093417722 -1204850272 564290299 + -67121221 -1342177350 -1309195902 -776734797 + + -0.4920000731945038 0.4326725304126740 + + <_> + + 0 -1 88 -25694458 67104495 -290216278 -168563037 2083877442 + 1702788383 -144191964 -234882162 + + -0.4494568109512329 0.4448510706424713 + + <_> + + 0 -1 59 -857980836 904682741 -1612267521 232279415 + 1550862252 -574825221 -357380888 -4579409 + + -0.5180826783180237 0.3888972699642181 + + <_> + + 0 -1 27 -98549440 -137838400 494928389 -246013630 939541351 + -1196072350 -620603549 2137216273 + + -0.6081240773200989 0.3333222270011902 + + <_> + 8 + -0.6743940711021423 + + + <_> + + 0 -1 29 -150995201 2071191945 -1302151626 536934335 + -1059008937 914128709 1147328110 -268369925 + + -0.1790193915367127 0.6605972051620483 + + <_> + + 0 -1 128 -134509479 1610575703 -1342177289 1861484541 + -1107833788 1577058173 -333558568 -136319041 + + -0.3681024610996246 0.5139749646186829 + + <_> + + 0 -1 70 -1 1060154476 -1090984524 -630918524 -539492875 + 779616255 -839568424 -321 + + -0.3217232525348663 0.6171553134918213 + + <_> + + 0 -1 4 -269562385 -285029906 -791084350 -17923776 235286671 + 1275504943 1344390399 -966276889 + + -0.4373284578323364 0.4358185231685638 + + <_> + + 0 -1 76 17825984 -747628419 595427229 1474759671 575672208 + -1684005538 872217086 -1155858277 + + -0.4404836893081665 0.4601220190525055 + + <_> + + 0 -1 124 -336593039 1873735591 -822231622 -355795238 + -470820869 -1997537409 -1057132384 -1015285005 + + -0.4294152259826660 0.4452161788940430 + + <_> + + 0 -1 54 -834212130 -593694721 -322142257 -364892500 + -951029539 -302125121 -1615106053 -79249765 + + -0.3973052501678467 0.4854526817798615 + + <_> + + 0 -1 95 1342144479 2147431935 -33554561 -47873 -855685912 -1 + 1988052447 536827383 + + -0.7054683566093445 0.2697997391223908 + + <_> + 9 + -1.2042298316955566 + + + <_> + + 0 -1 39 1431368960 -183437936 -537002499 -137497097 + 1560590321 -84611081 -2097193 -513 + + -0.5905947685241699 0.5101932883262634 + + <_> + + 0 -1 120 -1645259691 2105491231 2130706431 1458995007 + -8567536 -42483883 -33780003 -21004417 + + -0.4449204802513123 0.4490709304809570 + + <_> + + 0 -1 89 -612381022 -505806938 -362027516 -452985106 + 275854917 1920431639 -12600561 -134221825 + + -0.4693818688392639 0.4061094820499420 + + <_> + + 0 -1 14 -805573153 -161 -554172679 -530519488 -16779441 + 2000682871 -33604275 -150997129 + + -0.3600351214408875 0.5056326985359192 + + <_> + + 0 -1 67 6192 435166195 1467449341 2046691505 -1608493775 + -4755729 -1083162625 -71365637 + + -0.4459891915321350 0.4132415652275085 + + <_> + + 0 -1 86 -41689215 -3281034 1853357967 -420712635 -415924289 + -270209208 -1088293113 -825311232 + + -0.4466069042682648 0.4135067760944367 + + <_> + + 0 -1 80 -117391116 -42203396 2080374461 -188709 -542008165 + -356831940 -1091125345 -1073796897 + + -0.3394956290721893 0.5658645033836365 + + <_> + + 0 -1 75 -276830049 1378714472 -1342181951 757272098 + 1073740607 -282199241 -415761549 170896931 + + -0.5346512198448181 0.3584479391574860 + + <_> + + 0 -1 55 -796075825 -123166849 2113667055 -217530421 + -1107432194 -16385 -806359809 -391188771 + + -0.4379335641860962 0.4123645126819611 + + <_> + 10 + -0.8402050137519836 + + + <_> + + 0 -1 71 -890246622 15525883 -487690486 47116238 -1212319899 + -1291847681 -68159890 -469829921 + + -0.2670986354351044 0.6014143228530884 + + <_> + + 0 -1 31 -1361180685 -1898008841 -1090588811 -285410071 + -1074016265 -840443905 2147221487 -262145 + + -0.4149844348430634 0.4670888185501099 + + <_> + + 0 -1 40 1426190596 1899364271 2142731795 -142607505 + -508232452 -21563393 -41960001 -65 + + -0.4985891580581665 0.3719584941864014 + + <_> + + 0 -1 109 -201337965 10543906 -236498096 -746195597 + 1974565825 -15204415 921907633 -190058309 + + -0.4568729996681213 0.3965812027454376 + + <_> + + 0 -1 130 -595026732 -656401928 -268649235 -571490699 + -440600392 -133131 -358810952 -2004088646 + + -0.4770836830139160 0.3862601518630981 + + <_> + + 0 -1 66 941674740 -1107882114 1332789109 -67691015 + -1360463693 -1556612430 -609108546 733546933 + + -0.4877715110778809 0.3778986334800720 + + <_> + + 0 -1 49 -17114945 -240061474 1552871558 -82775604 -932393844 + -1308544889 -532635478 -99042357 + + -0.3721654713153839 0.4994400143623352 + + <_> + + 0 -1 133 -655906006 1405502603 -939205164 1884929228 + -498859222 559417357 -1928559445 -286264385 + + -0.3934195041656494 0.4769641458988190 + + <_> + + 0 -1 0 -335837777 1860677295 -90 -1946186226 931096183 + 251612987 2013265917 -671232197 + + -0.4323300719261169 0.4342164099216461 + + <_> + + 0 -1 103 37769424 -137772680 374692301 2002666345 -536176194 + -1644484728 807009019 1069089930 + + -0.4993278682231903 0.3665378093719482 + + <_> + 9 + -1.1974394321441650 + + + <_> + + 0 -1 43 -5505 2147462911 2143265466 -4511070 -16450 -257 + -201348440 -71333206 + + -0.3310225307941437 0.5624626278877258 + + <_> + + 0 -1 90 -136842268 -499330741 2015250980 -87107126 + -641665744 -788524639 -1147864792 -134892563 + + -0.5266560912132263 0.3704403042793274 + + <_> + + 0 -1 104 -146800880 -1780368555 2111170033 -140904684 + -16777551 -1946681885 -1646463595 -839131947 + + -0.4171888828277588 0.4540435671806335 + + <_> + + 0 -1 85 -832054034 -981663763 -301990281 -578814081 + -932319000 -1997406723 -33555201 -69206017 + + -0.4556705355644226 0.3704262077808380 + + <_> + + 0 -1 24 -118492417 -1209026825 1119023838 -1334313353 + 1112948738 -297319313 1378887291 -139469193 + + -0.4182529747486115 0.4267231225967407 + + <_> + + 0 -1 78 -1714382628 -2353704 -112094959 -549613092 + -1567058760 -1718550464 -342315012 -1074972227 + + -0.3625369668006897 0.4684656262397766 + + <_> + + 0 -1 5 -85219702 316836394 -33279 1904970288 2117267315 + -260901769 -621461759 -88607770 + + -0.4742925167083740 0.3689507246017456 + + <_> + + 0 -1 11 -294654041 -353603585 -1641159686 -50331921 + -2080899877 1145569279 -143132713 -152044037 + + -0.3666271567344666 0.4580127298831940 + + <_> + + 0 -1 32 1887453658 -638545712 -1877976819 -34320972 + -1071067983 -661345416 -583338277 1060190561 + + -0.4567637443542481 0.3894708156585693 + + <_> + 9 + -0.5733128190040588 + + + <_> + + 0 -1 122 -994063296 1088745462 -318837116 -319881377 + 1102566613 1165490103 -121679694 -134744129 + + -0.4055117964744568 0.5487945079803467 + + <_> + + 0 -1 68 -285233233 -538992907 1811935199 -369234005 -529 + -20593 -20505 -1561401854 + + -0.3787897229194641 0.4532003402709961 + + <_> + + 0 -1 58 -1335245632 1968917183 1940861695 536816369 + -1226071367 -570908176 457026619 1000020667 + + -0.4258328974246979 0.4202791750431061 + + <_> + + 0 -1 94 -1360318719 -1979797897 -50435249 -18646473 + -608879292 -805306691 -269304244 -17840167 + + -0.4561023116111755 0.4002747833728790 + + <_> + + 0 -1 87 2062765935 -16449 -1275080721 -16406 45764335 + -1090552065 -772846337 -570464322 + + -0.4314672648906708 0.4086346626281738 + + <_> + + 0 -1 127 -536896021 1080817663 -738234288 -965478709 + -2082767969 1290855887 1993822934 -990381609 + + -0.4174543321132660 0.4249868988990784 + + <_> + + 0 -1 3 -818943025 168730891 -293610428 -79249354 669224671 + 621166734 1086506807 1473768907 + + -0.4321364760398865 0.4090838730335236 + + <_> + + 0 -1 79 -68895696 -67107736 -1414315879 -841676168 + -619843344 -1180610531 -1081990469 1043203389 + + -0.5018386244773865 0.3702533841133118 + + <_> + + 0 -1 116 -54002134 -543485719 -2124882422 -1437445858 + -115617074 -1195787391 -1096024366 -2140472445 + + -0.5037505626678467 0.3564981222152710 + + <_> + 9 + -0.4892596900463104 + + + <_> + + 0 -1 132 -67113211 2003808111 1862135111 846461923 -2752 + 2002237273 -273154752 1937223539 + + -0.2448196411132813 0.5689709186553955 + + <_> + + 0 -1 62 1179423888 -78064940 -611839555 -539167899 + -1289358360 -1650810108 -892540499 -1432827684 + + -0.4633283913135529 0.3587929606437683 + + <_> + + 0 -1 23 -285212705 -78450761 -656212031 -264050110 -27787425 + -1334349961 -547662981 -135796924 + + -0.3731099069118500 0.4290455579757690 + + <_> + + 0 -1 77 341863476 403702016 -550588417 1600194541 + -1080690735 951127993 -1388580949 -1153717473 + + -0.3658909499645233 0.4556473195552826 + + <_> + + 0 -1 22 -586880702 -204831512 -100644596 -39319550 + -1191150794 705692513 457203315 -75806957 + + -0.5214384198188782 0.3221037387847900 + + <_> + + 0 -1 72 -416546870 545911370 -673716192 -775559454 + -264113598 139424 -183369982 -204474641 + + -0.4289036989212036 0.4004956185817719 + + <_> + + 0 -1 50 -1026505020 -589692154 -1740499937 -1563770497 + 1348491006 -60710713 -1109853489 -633909413 + + -0.4621542394161224 0.3832748532295227 + + <_> + + 0 -1 108 -1448872304 -477895040 -1778390608 -772418127 + -1789923416 -1612057181 -805306693 -1415842113 + + -0.3711548447608948 0.4612701535224915 + + <_> + + 0 -1 92 407905424 -582449988 52654751 -1294472 -285103725 + -74633006 1871559083 1057955850 + + -0.5180652141571045 0.3205870389938355 + + <_> + 10 + -0.5911940932273865 + + + <_> + + 0 -1 81 4112 -1259563825 -846671428 -100902460 1838164148 + -74153752 -90653988 -1074263896 + + -0.2592592537403107 0.5873016119003296 + + <_> + + 0 -1 1 -285216785 -823206977 -1085589 -1081346 1207959293 + 1157103471 2097133565 -2097169 + + -0.3801195919513702 0.4718827307224274 + + <_> + + 0 -1 121 -12465 -536875169 2147478367 2130706303 -37765492 + -866124467 -318782328 -1392509185 + + -0.3509117066860199 0.5094807147979736 + + <_> + + 0 -1 38 2147449663 -20741 -16794757 1945873146 -16710 -1 + -8406341 -67663041 + + -0.4068757295608521 0.4130136370658875 + + <_> + + 0 -1 17 -155191713 866117231 1651407483 548272812 -479201468 + -447742449 1354229504 -261884429 + + -0.4557141065597534 0.3539792001247406 + + <_> + + 0 -1 100 -225319378 -251682065 -492783986 -792341777 + -1287261695 1393643841 -11274182 -213909521 + + -0.4117803275585175 0.4118592441082001 + + <_> + + 0 -1 63 -382220122 -2002072729 -51404800 -371201558 + -923011069 -2135301457 -2066104743 -1042557441 + + -0.4008397758007050 0.4034757018089294 + + <_> + + 0 -1 101 -627353764 -48295149 1581203952 -436258614 + -105268268 -1435893445 -638126888 -1061107126 + + -0.5694189667701721 0.2964762747287750 + + <_> + + 0 -1 118 -8399181 1058107691 -621022752 -251003468 -12582915 + -574619739 -994397789 -1648362021 + + -0.3195341229438782 0.5294018983840942 + + <_> + + 0 -1 92 -348343812 -1078389516 1717960437 364735981 + -1783841602 -4883137 -457572354 -1076950384 + + -0.3365339040756226 0.5067458748817444 + + <_> + 10 + -0.7612916231155396 + + + <_> + + 0 -1 10 -1976661318 -287957604 -1659497122 -782068 43591089 + -453637880 1435470000 -1077438561 + + -0.4204545319080353 0.5165745615959168 + + <_> + + 0 -1 131 -67110925 14874979 -142633168 -1338923040 + 2046713291 -2067933195 1473503712 -789579837 + + -0.3762553930282593 0.4075302779674530 + + <_> + + 0 -1 83 -272814301 -1577073 -1118685 -305156120 -1052289 + -1073813756 -538971154 -355523038 + + -0.4253497421741486 0.3728055357933044 + + <_> + + 0 -1 135 -2233 -214486242 -538514758 573747007 -159390971 + 1994225489 -973738098 -203424005 + + -0.3601998090744019 0.4563256204128265 + + <_> + + 0 -1 115 -261031688 -1330369299 -641860609 1029570301 + -1306461192 -1196149518 -1529767778 683139823 + + -0.4034293889999390 0.4160816967487335 + + <_> + + 0 -1 64 -572993608 -34042628 -417865 -111109 -1433365268 + -19869715 -1920939864 -1279457063 + + -0.3620899617671967 0.4594142735004425 + + <_> + + 0 -1 36 -626275097 -615256993 1651946018 805366393 + 2016559730 -430780849 -799868165 -16580645 + + -0.3903816640377045 0.4381459355354309 + + <_> + + 0 -1 93 1354797300 -1090957603 1976418270 -1342502178 + -1851873892 -1194637077 -1153521668 -1108399474 + + -0.3591445386409760 0.4624078869819641 + + <_> + + 0 -1 91 68157712 1211368313 -304759523 1063017136 798797750 + -275513546 648167355 -1145357350 + + -0.4297670423984528 0.4023293554782867 + + <_> + + 0 -1 107 -546318240 -1628569602 -163577944 -537002306 + -545456389 -1325465645 -380446736 -1058473386 + + -0.5727006793022156 0.2995934784412384 + + <_> + + 0 0 3 5 + <_> + + 0 0 4 2 + <_> + + 0 0 6 3 + <_> + + 0 1 2 3 + <_> + + 0 1 3 3 + <_> + + 0 1 3 7 + <_> + + 0 4 3 3 + <_> + + 0 11 3 4 + <_> + + 0 12 8 4 + <_> + + 0 14 4 3 + <_> + + 1 0 5 3 + <_> + + 1 1 2 2 + <_> + + 1 3 3 1 + <_> + + 1 7 4 4 + <_> + + 1 12 2 2 + <_> + + 1 13 4 1 + <_> + + 1 14 4 3 + <_> + + 1 17 3 2 + <_> + + 2 0 2 3 + <_> + + 2 1 2 2 + <_> + + 2 2 4 6 + <_> + + 2 3 4 4 + <_> + + 2 7 2 1 + <_> + + 2 11 2 3 + <_> + + 2 17 3 2 + <_> + + 3 0 2 2 + <_> + + 3 1 7 3 + <_> + + 3 7 2 1 + <_> + + 3 7 2 4 + <_> + + 3 18 2 2 + <_> + + 4 0 2 3 + <_> + + 4 3 2 1 + <_> + + 4 6 2 1 + <_> + + 4 6 2 5 + <_> + + 4 7 5 2 + <_> + + 4 8 4 3 + <_> + + 4 18 2 2 + <_> + + 5 0 2 2 + <_> + + 5 3 4 4 + <_> + + 5 6 2 5 + <_> + + 5 9 2 2 + <_> + + 5 10 2 2 + <_> + + 6 3 4 4 + <_> + + 6 4 4 3 + <_> + + 6 5 2 3 + <_> + + 6 5 2 5 + <_> + + 6 5 4 3 + <_> + + 6 6 4 2 + <_> + + 6 6 4 4 + <_> + + 6 18 1 2 + <_> + + 6 21 2 1 + <_> + + 7 0 3 7 + <_> + + 7 4 2 3 + <_> + + 7 9 5 1 + <_> + + 7 21 2 1 + <_> + + 8 0 1 4 + <_> + + 8 5 2 2 + <_> + + 8 5 3 2 + <_> + + 8 17 3 1 + <_> + + 8 18 1 2 + <_> + + 9 0 5 3 + <_> + + 9 2 2 6 + <_> + + 9 5 1 1 + <_> + + 9 11 1 1 + <_> + + 9 16 1 1 + <_> + + 9 16 2 1 + <_> + + 9 17 1 1 + <_> + + 9 18 1 1 + <_> + + 10 5 1 2 + <_> + + 10 5 3 3 + <_> + + 10 7 1 5 + <_> + + 10 8 1 1 + <_> + + 10 9 1 1 + <_> + + 10 10 1 1 + <_> + + 10 10 1 2 + <_> + + 10 14 3 3 + <_> + + 10 15 1 1 + <_> + + 10 15 2 1 + <_> + + 10 16 1 1 + <_> + + 10 16 2 1 + <_> + + 10 17 1 1 + <_> + + 10 21 1 1 + <_> + + 11 3 2 2 + <_> + + 11 5 1 2 + <_> + + 11 5 3 3 + <_> + + 11 5 4 6 + <_> + + 11 6 1 1 + <_> + + 11 7 2 2 + <_> + + 11 8 1 2 + <_> + + 11 10 1 1 + <_> + + 11 10 1 2 + <_> + + 11 15 1 1 + <_> + + 11 17 1 1 + <_> + + 11 18 1 1 + <_> + + 12 0 2 2 + <_> + + 12 1 2 5 + <_> + + 12 2 4 1 + <_> + + 12 3 1 3 + <_> + + 12 7 3 4 + <_> + + 12 10 3 2 + <_> + + 12 11 1 1 + <_> + + 12 12 3 2 + <_> + + 12 14 4 3 + <_> + + 12 17 1 1 + <_> + + 12 21 2 1 + <_> + + 13 6 2 5 + <_> + + 13 7 3 5 + <_> + + 13 11 3 2 + <_> + + 13 17 2 2 + <_> + + 13 17 3 2 + <_> + + 13 18 1 2 + <_> + + 13 18 2 2 + <_> + + 14 0 2 2 + <_> + + 14 1 1 3 + <_> + + 14 2 3 2 + <_> + + 14 7 2 1 + <_> + + 14 13 2 1 + <_> + + 14 13 3 3 + <_> + + 14 17 2 2 + <_> + + 15 0 2 2 + <_> + + 15 0 2 3 + <_> + + 15 4 3 2 + <_> + + 15 4 3 6 + <_> + + 15 6 3 2 + <_> + + 15 11 3 4 + <_> + + 15 13 3 2 + <_> + + 15 17 2 2 + <_> + + 15 17 3 2 + <_> + + 16 1 2 3 + <_> + + 16 3 2 4 + <_> + + 16 6 1 1 + <_> + + 16 16 2 2 + <_> + + 17 1 2 2 + <_> + + 17 1 2 5 + <_> + + 17 12 2 2 + <_> + + 18 0 2 2 + diff --git a/envs/kitoverlay/skimage/data/multipage.tif b/envs/kitoverlay/skimage/data/multipage.tif new file mode 100644 index 0000000000000000000000000000000000000000..77fa220a89fb74837c5c18f7b0698b8e50873a91 Binary files /dev/null and b/envs/kitoverlay/skimage/data/multipage.tif differ diff --git a/envs/kitoverlay/skimage/data/multipage_rgb.tif b/envs/kitoverlay/skimage/data/multipage_rgb.tif new file mode 100644 index 0000000000000000000000000000000000000000..6832c368f417fb4f96c27aada57e9290618a12ee Binary files /dev/null and b/envs/kitoverlay/skimage/data/multipage_rgb.tif differ diff --git a/envs/kitoverlay/skimage/feature/__init__.py b/envs/kitoverlay/skimage/feature/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5a30fa68b4859a9b3b1aefe20e9185c00eaa6c --- /dev/null +++ b/envs/kitoverlay/skimage/feature/__init__.py @@ -0,0 +1,5 @@ +"""Feature detection and extraction, e.g., texture analysis, corners, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/feature/__init__.pyi b/envs/kitoverlay/skimage/feature/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..40c54fb43ca313da733b6c0577037d06f1c3b566 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/__init__.pyi @@ -0,0 +1,88 @@ +# 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__ = [ + 'canny', + 'Cascade', + 'daisy', + 'hog', + 'graycomatrix', + 'graycoprops', + 'local_binary_pattern', + 'multiblock_lbp', + 'draw_multiblock_lbp', + 'peak_local_max', + 'structure_tensor', + 'structure_tensor_eigenvalues', + 'hessian_matrix', + 'hessian_matrix_det', + 'hessian_matrix_eigvals', + 'shape_index', + 'corner_kitchen_rosenfeld', + 'corner_harris', + 'corner_shi_tomasi', + 'corner_foerstner', + 'corner_subpix', + 'corner_peaks', + 'corner_moravec', + 'corner_fast', + 'corner_orientations', + 'match_template', + 'BRIEF', + 'CENSURE', + 'ORB', + 'SIFT', + 'match_descriptors', + 'plot_matched_features', + 'blob_dog', + 'blob_doh', + 'blob_log', + 'haar_like_feature', + 'haar_like_feature_coord', + 'draw_haar_like_feature', + 'multiscale_basic_features', + 'learn_gmm', + 'fisher_vector', +] + +from ._canny import canny +from ._cascade import Cascade +from ._daisy import daisy +from ._hog import hog +from .texture import ( + graycomatrix, + graycoprops, + local_binary_pattern, + multiblock_lbp, + draw_multiblock_lbp, +) +from .peak import peak_local_max +from .corner import ( + corner_kitchen_rosenfeld, + corner_harris, + corner_shi_tomasi, + corner_foerstner, + corner_subpix, + corner_peaks, + corner_fast, + structure_tensor, + structure_tensor_eigenvalues, + hessian_matrix, + hessian_matrix_eigvals, + hessian_matrix_det, + corner_moravec, + corner_orientations, + shape_index, +) +from .template import match_template +from .brief import BRIEF +from .censure import CENSURE +from .orb import ORB +from .sift import SIFT +from .match import match_descriptors +from .util import plot_matched_features +from .blob import blob_dog, blob_log, blob_doh +from .haar import haar_like_feature, haar_like_feature_coord, draw_haar_like_feature +from ._basic_features import multiscale_basic_features +from ._fisher_vector import learn_gmm, fisher_vector diff --git a/envs/kitoverlay/skimage/feature/__pycache__/_hog.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/_hog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0117a62a49d564a3f18efcc7d2592cd7eb9b8bd Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/_hog.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/censure.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/censure.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79dac7a14c226d563aabdb45351f58df3ff2a73e Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/censure.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/orb.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/orb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b00b55774d9878466aecf4f9217cad97eb1d131 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/orb.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/__pycache__/peak.cpython-311.pyc b/envs/kitoverlay/skimage/feature/__pycache__/peak.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edab0ec2757e7a292919e1fd8f173735f6570eb5 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/__pycache__/peak.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/feature/_basic_features.py b/envs/kitoverlay/skimage/feature/_basic_features.py new file mode 100644 index 0000000000000000000000000000000000000000..393a1af496c84afa652543fa1450e4a86f9580d6 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_basic_features.py @@ -0,0 +1,198 @@ +from itertools import combinations_with_replacement +import itertools +import numpy as np +from skimage import filters, feature +from skimage.util.dtype import img_as_float32 +from .._shared._dependency_checks import is_wasm + +if not is_wasm: + from concurrent.futures import ThreadPoolExecutor as PoolExecutor +else: + from contextlib import AbstractContextManager + + # Threading isn't supported on WASM, mock ThreadPoolExecutor as a fallback + class PoolExecutor(AbstractContextManager): + def __init__(self, *_, **__): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + def map(self, fn, iterables): + return map(fn, iterables) + + +def _texture_filter(gaussian_filtered): + H_elems = [ + np.gradient(np.gradient(gaussian_filtered)[ax0], axis=ax1) + for ax0, ax1 in combinations_with_replacement(range(gaussian_filtered.ndim), 2) + ] + eigvals = feature.hessian_matrix_eigvals(H_elems) + return eigvals + + +def _singlescale_basic_features_singlechannel( + img, sigma, intensity=True, edges=True, texture=True +): + results = () + gaussian_filtered = filters.gaussian(img, sigma=sigma, preserve_range=False) + if intensity: + results += (gaussian_filtered,) + if edges: + results += (filters.sobel(gaussian_filtered),) + if texture: + results += (*_texture_filter(gaussian_filtered),) + return results + + +def _mutiscale_basic_features_singlechannel( + img, + intensity=True, + edges=True, + texture=True, + sigma_min=0.5, + sigma_max=16, + num_sigma=None, + workers=None, +): + """Features for a single channel nd image. + + Parameters + ---------- + img : ndarray + Input image, which can be grayscale or multichannel. + intensity : bool, default True + If True, pixel intensities averaged over the different scales + are added to the feature set. + edges : bool, default True + If True, intensities of local gradients averaged over the different + scales are added to the feature set. + texture : bool, default True + If True, eigenvalues of the Hessian matrix after Gaussian blurring + at different scales are added to the feature set. + sigma_min : float, optional + Smallest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + sigma_max : float, optional + Largest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + num_sigma : int, optional + Number of values of the Gaussian kernel between sigma_min and sigma_max. + If None, sigma_min multiplied by powers of 2 are used. + workers : int or None, optional + The number of parallel threads to use. If set to ``None``, the full + set of available cores are used. + + Returns + ------- + features : list + List of features, each element of the list is an array of shape as img. + """ + # computations are faster as float32 + img = np.ascontiguousarray(img_as_float32(img)) + if num_sigma is None: + num_sigma = int(np.log2(sigma_max) - np.log2(sigma_min) + 1) + sigmas = np.logspace( + np.log2(sigma_min), + np.log2(sigma_max), + num=num_sigma, + base=2, + endpoint=True, + ) + with PoolExecutor(max_workers=workers) as ex: + out_sigmas = list( + ex.map( + lambda s: _singlescale_basic_features_singlechannel( + img, s, intensity=intensity, edges=edges, texture=texture + ), + sigmas, + ) + ) + features = itertools.chain.from_iterable(out_sigmas) + return features + + +def multiscale_basic_features( + image, + intensity=True, + edges=True, + texture=True, + sigma_min=0.5, + sigma_max=16, + num_sigma=None, + workers=None, + *, + channel_axis=None, +): + """Local features for a single- or multi-channel nd image. + + Intensity, gradient intensity and local structure are computed at + different scales thanks to Gaussian blurring. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel. + intensity : bool, default True + If True, pixel intensities averaged over the different scales + are added to the feature set. + edges : bool, default True + If True, intensities of local gradients averaged over the different + scales are added to the feature set. + texture : bool, default True + If True, eigenvalues of the Hessian matrix after Gaussian blurring + at different scales are added to the feature set. + sigma_min : float, optional + Smallest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + sigma_max : float, optional + Largest value of the Gaussian kernel used to average local + neighborhoods before extracting features. + num_sigma : int, optional + Number of values of the Gaussian kernel between sigma_min and sigma_max. + If None, sigma_min multiplied by powers of 2 are used. + workers : int or None, optional + The number of parallel threads to use. If set to ``None``, the full + set of available cores are used. + 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 + ------- + features : np.ndarray + Array of shape ``image.shape + (n_features,)``. When `channel_axis` is + not None, all channels are concatenated along the features dimension. + (i.e. ``n_features == n_features_singlechannel * n_channels``) + """ + if not any([intensity, edges, texture]): + raise ValueError( + "At least one of `intensity`, `edges` or `textures`" + "must be True for features to be computed." + ) + if channel_axis is None: + image = image[..., np.newaxis] + channel_axis = -1 + elif channel_axis != -1: + image = np.moveaxis(image, channel_axis, -1) + + all_results = ( + _mutiscale_basic_features_singlechannel( + image[..., dim], + intensity=intensity, + edges=edges, + texture=texture, + sigma_min=sigma_min, + sigma_max=sigma_max, + num_sigma=num_sigma, + workers=workers, + ) + for dim in range(image.shape[-1]) + ) + features = list(itertools.chain.from_iterable(all_results)) + out = np.stack(features, axis=-1) + return out diff --git a/envs/kitoverlay/skimage/feature/_canny.py b/envs/kitoverlay/skimage/feature/_canny.py new file mode 100644 index 0000000000000000000000000000000000000000..a0fe8275148d155949dda8bc0229760d408d5d89 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_canny.py @@ -0,0 +1,262 @@ +""" +canny.py - Canny Edge detector + +Reference: Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 +""" + +import numpy as np +import scipy.ndimage as ndi + +from ..util.dtype import dtype_limits +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_nD +from ._canny_cy import _nonmaximum_suppression_bilinear + + +def _preprocess(image, mask, sigma, mode, cval): + """Generate a smoothed image and an eroded mask. + + The image is smoothed using a gaussian filter ignoring masked + pixels and the mask is eroded. + + Parameters + ---------- + image : array + Image to be smoothed. + mask : array + Mask with 1's for significant pixels, 0's for masked pixels. + sigma : scalar or sequence of scalars + Standard deviation for Gaussian kernel. The standard + deviations of the Gaussian filter are given for each axis as a + sequence, or as a single number, in which case it is equal for + all axes. + mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'} + The ``mode`` parameter determines how the array borders are + handled, where ``cval`` is the value when mode is equal to + 'constant'. + cval : float, optional + Value to fill past edges of input if `mode` is 'constant'. + + Returns + ------- + smoothed_image : ndarray + The smoothed array + eroded_mask : ndarray + The eroded mask. + + Notes + ----- + This function calculates the fractional contribution of masked pixels + by applying the function to the mask (which gets you the fraction of + the pixel data that's due to significant points). We then mask the image + and apply the function. The resulting values will be lower by the + bleed-over fraction, so you can recalibrate by dividing by the function + on the mask to recover the effect of smoothing from just the significant + pixels. + """ + gaussian_kwargs = dict(sigma=sigma, mode=mode, cval=cval, preserve_range=False) + compute_bleedover = mode == 'constant' or mask is not None + float_type = _supported_float_type(image.dtype) + if mask is None: + if compute_bleedover: + mask = np.ones(image.shape, dtype=float_type) + masked_image = image + + eroded_mask = np.ones(image.shape, dtype=bool) + eroded_mask[:1, :] = 0 + eroded_mask[-1:, :] = 0 + eroded_mask[:, :1] = 0 + eroded_mask[:, -1:] = 0 + + else: + mask = mask.astype(bool, copy=False) + masked_image = np.zeros_like(image) + masked_image[mask] = image[mask] + + # Make the eroded mask. Setting the border value to zero will wipe + # out the image edges for us. + s = ndi.generate_binary_structure(2, 2) + eroded_mask = ndi.binary_erosion(mask, s, border_value=0) + + if compute_bleedover: + # Compute the fractional contribution of masked pixels by applying + # the function to the mask (which gets you the fraction of the + # pixel data that's due to significant points) + bleed_over = ( + gaussian(mask.astype(float_type, copy=False), **gaussian_kwargs) + + np.finfo(float_type).eps + ) + + # Smooth the masked image + smoothed_image = gaussian(masked_image, **gaussian_kwargs) + + # Lower the result by the bleed-over fraction, so you can + # recalibrate by dividing by the function on the mask to recover + # the effect of smoothing from just the significant pixels. + if compute_bleedover: + smoothed_image /= bleed_over + + return smoothed_image, eroded_mask + + +def canny( + image, + sigma=1.0, + low_threshold=None, + high_threshold=None, + mask=None, + use_quantiles=False, + *, + mode='constant', + cval=0.0, +): + """Edge filter an image using the Canny algorithm. + + Parameters + ---------- + image : 2D array + Grayscale input image to detect edges on; can be of any dtype. + sigma : float, optional + Standard deviation of the Gaussian filter. + low_threshold : float, optional + Lower bound for hysteresis thresholding (linking edges). + If None, low_threshold is set to 10% of dtype's max. + high_threshold : float, optional + Upper bound for hysteresis thresholding (linking edges). + If None, high_threshold is set to 20% of dtype's max. + mask : array, dtype=bool, optional + Mask to limit the application of Canny to a certain area. + use_quantiles : bool, optional + If ``True`` then treat low_threshold and high_threshold as + quantiles of the edge magnitude image, rather than absolute + edge magnitude values. If ``True`` then the thresholds must be + in the range [0, 1]. + mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'} + The ``mode`` parameter determines how the array borders are + handled during Gaussian filtering, where ``cval`` is the value when + mode is equal to 'constant'. + cval : float, optional + Value to fill past edges of input if `mode` is 'constant'. + + Returns + ------- + output : 2D array (image) + The binary edge map. + + See also + -------- + skimage.filters.sobel + + Notes + ----- + The steps of the algorithm are as follows: + + * Smooth the image using a Gaussian with ``sigma`` width. + + * Apply the horizontal and vertical Sobel operators to get the gradients + within the image. The edge strength is the norm of the gradient. + + * Thin potential edges to 1-pixel wide curves. First, find the normal + to the edge at each point. This is done by looking at the + signs and the relative magnitude of the X-Sobel and Y-Sobel + to sort the points into 4 categories: horizontal, vertical, + diagonal and antidiagonal. Then look in the normal and reverse + directions to see if the values in either of those directions are + greater than the point in question. Use interpolation to get a mix of + points instead of picking the one that's the closest to the normal. + + * Perform a hysteresis thresholding: first label all points above the + high threshold as edges. Then recursively label any point above the + low threshold that is 8-connected to a labeled point as an edge. + + References + ---------- + .. [1] Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 + :DOI:`10.1109/TPAMI.1986.4767851` + .. [2] William Green's Canny tutorial + https://en.wikipedia.org/wiki/Canny_edge_detector + + Examples + -------- + >>> from skimage import feature + >>> rng = np.random.default_rng() + >>> # Generate noisy image of a square + >>> im = np.zeros((256, 256)) + >>> im[64:-64, 64:-64] = 1 + >>> im += 0.2 * rng.random(im.shape) + >>> # First trial with the Canny filter, with the default smoothing + >>> edges1 = feature.canny(im) + >>> # Increase the smoothing for better results + >>> edges2 = feature.canny(im, sigma=3) + + """ + + # Regarding masks, any point touching a masked point will have a gradient + # that is "infected" by the masked point, so it's enough to erode the + # mask by one and then mask the output. We also mask out the border points + # because who knows what lies beyond the edge of the image? + + if np.issubdtype(image.dtype, np.int64) or np.issubdtype(image.dtype, np.uint64): + raise ValueError("64-bit integer images are not supported") + + check_nD(image, 2) + dtype_max = dtype_limits(image, clip_negative=False)[1] + + if low_threshold is None: + low_threshold = 0.1 + elif use_quantiles: + if not (0.0 <= low_threshold <= 1.0): + raise ValueError("Quantile thresholds must be between 0 and 1.") + else: + low_threshold /= dtype_max + + if high_threshold is None: + high_threshold = 0.2 + elif use_quantiles: + if not (0.0 <= high_threshold <= 1.0): + raise ValueError("Quantile thresholds must be between 0 and 1.") + else: + high_threshold /= dtype_max + + if high_threshold < low_threshold: + raise ValueError("low_threshold should be lower then high_threshold") + + # Image filtering + smoothed, eroded_mask = _preprocess(image, mask, sigma, mode, cval) + + # Gradient magnitude estimation + jsobel = ndi.sobel(smoothed, axis=1) + isobel = ndi.sobel(smoothed, axis=0) + magnitude = isobel * isobel + magnitude += jsobel * jsobel + np.sqrt(magnitude, out=magnitude) + + if use_quantiles: + low_threshold, high_threshold = np.percentile( + magnitude, [100.0 * low_threshold, 100.0 * high_threshold] + ) + + # Non-maximum suppression + low_masked = _nonmaximum_suppression_bilinear( + isobel, jsobel, magnitude, eroded_mask, low_threshold + ) + + # Double thresholding and edge tracking + # + # Segment the low-mask, then only keep low-segments that have + # some high_mask component in them + # + low_mask = low_masked > 0 + strel = np.ones((3, 3), bool) + labels, count = ndi.label(low_mask, strel) + if count == 0: + return low_mask + + high_mask = low_mask & (low_masked >= high_threshold) + nonzero_sums = np.unique(labels[high_mask]) + good_label = np.zeros((count + 1,), bool) + good_label[nonzero_sums] = True + output_mask = good_label[labels] + return output_mask diff --git a/envs/kitoverlay/skimage/feature/_daisy.py b/envs/kitoverlay/skimage/feature/_daisy.py new file mode 100644 index 0000000000000000000000000000000000000000..74f0e122ca1c626132587a28e574e9c10955b115 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_daisy.py @@ -0,0 +1,249 @@ +import math + +import numpy as np +from numpy import arctan2, exp, pi, sqrt + +from .. import draw +from ..util.dtype import img_as_float +from .._shared.filters import gaussian +from .._shared.utils import check_nD +from ..color import gray2rgb + + +def daisy( + image, + step=4, + radius=15, + rings=3, + histograms=8, + orientations=8, + normalization='l1', + sigmas=None, + ring_radii=None, + visualize=False, +): + '''Extract DAISY feature descriptors densely for the given image. + + DAISY is a feature descriptor similar to SIFT formulated in a way that + allows for fast dense extraction. Typically, this is practical for + bag-of-features image representations. + + The implementation follows Tola et al. [1]_ but deviate on the following + points: + + * Histogram bin contribution are smoothed with a circular Gaussian + window over the tonal range (the angular range). + * The sigma values of the spatial Gaussian smoothing in this code do not + match the sigma values in the original code by Tola et al. [2]_. In + their code, spatial smoothing is applied to both the input image and + the center histogram. However, this smoothing is not documented in [1]_ + and, therefore, it is omitted. + + Parameters + ---------- + image : (M, N) array + Input image (grayscale). + step : int, optional + Distance between descriptor sampling points. + radius : int, optional + Radius (in pixels) of the outermost ring. + rings : int, optional + Number of rings. + histograms : int, optional + Number of histograms sampled per ring. + orientations : int, optional + Number of orientations (bins) per histogram. + normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional + How to normalize the descriptors + + * 'l1': L1-normalization of each descriptor. + * 'l2': L2-normalization of each descriptor. + * 'daisy': L2-normalization of individual histograms. + * 'off': Disable normalization. + + sigmas : 1D array of float, optional + Standard deviation of spatial Gaussian smoothing for the center + histogram and for each ring of histograms. The array of sigmas should + be sorted from the center and out. I.e. the first sigma value defines + the spatial smoothing of the center histogram and the last sigma value + defines the spatial smoothing of the outermost ring. Specifying sigmas + overrides the following parameter. + + ``rings = len(sigmas) - 1`` + + ring_radii : 1D array of int, optional + Radius (in pixels) for each ring. Specifying ring_radii overrides the + following two parameters. + + ``rings = len(ring_radii)`` + ``radius = ring_radii[-1]`` + + If both sigmas and ring_radii are given, they must satisfy the + following predicate since no radius is needed for the center + histogram. + + ``len(ring_radii) == len(sigmas) + 1`` + + visualize : bool, optional + Generate a visualization of the DAISY descriptors + + Returns + ------- + descs : array + Grid of DAISY descriptors for the given image as an array + dimensionality (P, Q, R) where + + ``P = ceil((M - radius*2) / step)`` + ``Q = ceil((N - radius*2) / step)`` + ``R = (rings * histograms + 1) * orientations`` + + descs_img : (M, N, 3) array (only if visualize==True) + Visualization of the DAISY descriptors. + + References + ---------- + .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide- + baseline stereo." Pattern Analysis and Machine Intelligence, IEEE + Transactions on 32.5 (2010): 815-830. + .. [2] http://cvlab.epfl.ch/software/daisy + ''' + + check_nD(image, 2, 'img') + + image = img_as_float(image) + float_dtype = image.dtype + + # Validate parameters. + if ( + sigmas is not None + and ring_radii is not None + and len(sigmas) - 1 != len(ring_radii) + ): + raise ValueError('`len(sigmas)-1 != len(ring_radii)`') + if ring_radii is not None: + rings = len(ring_radii) + radius = ring_radii[-1] + if sigmas is not None: + rings = len(sigmas) - 1 + if sigmas is None: + sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)] + if ring_radii is None: + ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)] + if normalization not in ['l1', 'l2', 'daisy', 'off']: + raise ValueError('Invalid normalization method.') + + # Compute image derivatives. + dx = np.zeros(image.shape, dtype=float_dtype) + dy = np.zeros(image.shape, dtype=float_dtype) + dx[:, :-1] = np.diff(image, n=1, axis=1) + dy[:-1, :] = np.diff(image, n=1, axis=0) + + # Compute gradient orientation and magnitude and their contribution + # to the histograms. + grad_mag = sqrt(dx**2 + dy**2) + grad_ori = arctan2(dy, dx) + orientation_kappa = orientations / pi + orientation_angles = [2 * o * pi / orientations - pi for o in range(orientations)] + hist = np.empty((orientations,) + image.shape, dtype=float_dtype) + for i, o in enumerate(orientation_angles): + # Weigh bin contribution by the circular normal distribution + hist[i, :, :] = exp(orientation_kappa * np.cos(grad_ori - o)) + # Weigh bin contribution by the gradient magnitude + hist[i, :, :] = np.multiply(hist[i, :, :], grad_mag) + + # Smooth orientation histograms for the center and all rings. + sigmas = [sigmas[0]] + sigmas + hist_smooth = np.empty((rings + 1,) + hist.shape, dtype=float_dtype) + for i in range(rings + 1): + for j in range(orientations): + hist_smooth[i, j, :, :] = gaussian( + hist[j, :, :], sigma=sigmas[i], mode='reflect' + ) + + # Assemble descriptor grid. + theta = [2 * pi * j / histograms for j in range(histograms)] + desc_dims = (rings * histograms + 1) * orientations + descs = np.empty( + (desc_dims, image.shape[0] - 2 * radius, image.shape[1] - 2 * radius), + dtype=float_dtype, + ) + descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius, radius:-radius] + idx = orientations + for i in range(rings): + for j in range(histograms): + y_min = radius + int(round(ring_radii[i] * math.sin(theta[j]))) + y_max = descs.shape[1] + y_min + x_min = radius + int(round(ring_radii[i] * math.cos(theta[j]))) + x_max = descs.shape[2] + x_min + descs[idx : idx + orientations, :, :] = hist_smooth[ + i + 1, :, y_min:y_max, x_min:x_max + ] + idx += orientations + descs = descs[:, ::step, ::step] + descs = descs.swapaxes(0, 1).swapaxes(1, 2) + + # Normalize descriptors. + if normalization != 'off': + descs += 1e-10 + if normalization == 'l1': + descs /= np.sum(descs, axis=2)[:, :, np.newaxis] + elif normalization == 'l2': + descs /= sqrt(np.sum(descs**2, axis=2))[:, :, np.newaxis] + elif normalization == 'daisy': + for i in range(0, desc_dims, orientations): + norms = sqrt(np.sum(descs[:, :, i : i + orientations] ** 2, axis=2)) + descs[:, :, i : i + orientations] /= norms[:, :, np.newaxis] + + if visualize: + descs_img = gray2rgb(image) + for i in range(descs.shape[0]): + for j in range(descs.shape[1]): + # Draw center histogram sigma + color = [1, 0, 0] + desc_y = i * step + radius + desc_x = j * step + radius + rows, cols, val = draw.circle_perimeter_aa( + desc_y, desc_x, int(sigmas[0]) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + max_bin = np.max(descs[i, j, :]) + for o_num, o in enumerate(orientation_angles): + # Draw center histogram bins + bin_size = descs[i, j, o_num] / max_bin + dy = sigmas[0] * bin_size * math.sin(o) + dx = sigmas[0] * bin_size * math.cos(o) + rows, cols, val = draw.line_aa( + desc_y, desc_x, int(desc_y + dy), int(desc_x + dx) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + for r_num, r in enumerate(ring_radii): + color_offset = float(1 + r_num) / rings + color = (1 - color_offset, 1, color_offset) + for t_num, t in enumerate(theta): + # Draw ring histogram sigmas + hist_y = desc_y + int(round(r * math.sin(t))) + hist_x = desc_x + int(round(r * math.cos(t))) + rows, cols, val = draw.circle_perimeter_aa( + hist_y, hist_x, int(sigmas[r_num + 1]) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + for o_num, o in enumerate(orientation_angles): + # Draw histogram bins + bin_size = descs[ + i, + j, + orientations + + r_num * histograms * orientations + + t_num * orientations + + o_num, + ] + bin_size /= max_bin + dy = sigmas[r_num + 1] * bin_size * math.sin(o) + dx = sigmas[r_num + 1] * bin_size * math.cos(o) + rows, cols, val = draw.line_aa( + hist_y, hist_x, int(hist_y + dy), int(hist_x + dx) + ) + draw.set_color(descs_img, (rows, cols), color, alpha=val) + return descs, descs_img + else: + return descs diff --git a/envs/kitoverlay/skimage/feature/_fisher_vector.py b/envs/kitoverlay/skimage/feature/_fisher_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..bae434e24f035ed8fe21d3aa772b3eae53f73738 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_fisher_vector.py @@ -0,0 +1,262 @@ +""" +fisher_vector.py - Implementation of the Fisher vector encoding algorithm + +This module contains the source code for Fisher vector computation. The +computation is separated into two distinct steps, which are called separately +by the user, namely: + +learn_gmm: Used to estimate the GMM for all vectors/descriptors computed for + all examples in the dataset (e.g. estimated using all the SIFT + vectors computed for all images in the dataset, or at least a subset + of this). + +fisher_vector: Used to compute the Fisher vector representation for a + single set of descriptors/vector (e.g. the SIFT + descriptors for a single image in your dataset, or + perhaps a test image). + +Reference: Perronnin, F. and Dance, C. Fisher kernels on Visual Vocabularies + for Image Categorization, IEEE Conference on Computer Vision and + Pattern Recognition, 2007 + +Origin Author: Dan Oneata (Author of the original implementation for the Fisher +vector computation using scikit-learn and NumPy. Subsequently ported to +scikit-image (here) by other authors.) +""" + +import numpy as np + + +__doctest_requires__ = {("learn_gmm", "fisher_vector"): ["sklearn"]} + + +class FisherVectorException(Exception): + pass + + +class DescriptorException(FisherVectorException): + pass + + +def learn_gmm(descriptors, *, n_modes=32, gm_args=None): + """Estimate a Gaussian mixture model (GMM) given a set of descriptors and + number of modes (i.e. Gaussians). This function is essentially a wrapper + around the scikit-learn implementation of GMM, namely the + :class:`sklearn.mixture.GaussianMixture` class. + + Due to the nature of the Fisher vector, the only enforced parameter of the + underlying scikit-learn class is the covariance_type, which must be 'diag'. + + There is no simple way to know what value to use for `n_modes` a-priori. + Typically, the value is usually one of ``{16, 32, 64, 128}``. One may train + a few GMMs and choose the one that maximises the log probability of the + GMM, or choose `n_modes` such that the downstream classifier trained on + the resultant Fisher vectors has maximal performance. + + Parameters + ---------- + descriptors : np.ndarray (N, M) or list [(N1, M), (N2, M), ...] + List of NumPy arrays, or a single NumPy array, of the descriptors + used to estimate the GMM. The reason a list of NumPy arrays is + permissible is because often when using a Fisher vector encoding, + descriptors/vectors are computed separately for each sample/image in + the dataset, such as SIFT vectors for each image. If a list if passed + in, then each element must be a NumPy array in which the number of + rows may differ (e.g. different number of SIFT vector for each image), + but the number of columns for each must be the same (i.e. the + dimensionality must be the same). + n_modes : int + The number of modes/Gaussians to estimate during the GMM estimate. + gm_args : dict + Keyword arguments that can be passed into the underlying scikit-learn + :class:`sklearn.mixture.GaussianMixture` class. + + Returns + ------- + gmm : :class:`sklearn.mixture.GaussianMixture` + The estimated GMM object, which contains the necessary parameters + needed to compute the Fisher vector. + + References + ---------- + .. [1] https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html + + Examples + -------- + >>> from skimage.feature import fisher_vector + >>> rng = np.random.Generator(np.random.PCG64()) + >>> sift_for_images = [rng.standard_normal((10, 128)) for _ in range(10)] + >>> num_modes = 16 + >>> # Estimate 16-mode GMM with these synthetic SIFT vectors + >>> gmm = learn_gmm(sift_for_images, n_modes=num_modes) + """ + + try: + from sklearn.mixture import GaussianMixture + except ImportError: + raise ImportError( + 'scikit-learn is not installed. Please ensure it is installed in ' + 'order to use the Fisher vector functionality.' + ) + + if not isinstance(descriptors, (list, np.ndarray)): + raise DescriptorException( + 'Please ensure descriptors are either a NumPy array, ' + 'or a list of NumPy arrays.' + ) + + d_mat_1 = descriptors[0] + if isinstance(descriptors, list) and not isinstance(d_mat_1, np.ndarray): + raise DescriptorException( + 'Please ensure descriptors are a list of NumPy arrays.' + ) + + if isinstance(descriptors, list): + expected_shape = descriptors[0].shape + ranks = [len(e.shape) == len(expected_shape) for e in descriptors] + if not all(ranks): + raise DescriptorException( + 'Please ensure all elements of your descriptor list ' 'are of rank 2.' + ) + dims = [e.shape[1] == descriptors[0].shape[1] for e in descriptors] + if not all(dims): + raise DescriptorException( + 'Please ensure all descriptors are of the same dimensionality.' + ) + + if not isinstance(n_modes, int) or n_modes <= 0: + raise FisherVectorException('Please ensure n_modes is a positive integer.') + + if gm_args: + has_cov_type = 'covariance_type' in gm_args + cov_type_not_diag = gm_args['covariance_type'] != 'diag' + if has_cov_type and cov_type_not_diag: + raise FisherVectorException('Covariance type must be "diag".') + + if isinstance(descriptors, list): + descriptors = np.vstack(descriptors) + + if gm_args: + has_cov_type = 'covariance_type' in gm_args + if has_cov_type: + gmm = GaussianMixture(n_components=n_modes, **gm_args) + else: + gmm = GaussianMixture( + n_components=n_modes, covariance_type='diag', **gm_args + ) + else: + gmm = GaussianMixture(n_components=n_modes, covariance_type='diag') + + gmm.fit(descriptors) + + return gmm + + +def fisher_vector(descriptors, gmm, *, improved=False, alpha=0.5): + """Compute the Fisher vector given some descriptors/vectors, + and an associated estimated GMM. + + Parameters + ---------- + descriptors : np.ndarray, shape=(n_descriptors, descriptor_length) + NumPy array of the descriptors for which the Fisher vector + representation is to be computed. + gmm : :class:`sklearn.mixture.GaussianMixture` + An estimated GMM object, which contains the necessary parameters needed + to compute the Fisher vector. + improved : bool, default=False + Flag denoting whether to compute improved Fisher vectors or not. + Improved Fisher vectors are L2 and power normalized. Power + normalization is simply f(z) = sign(z) pow(abs(z), alpha) for some + 0 <= alpha <= 1. + alpha : float, default=0.5 + The parameter for the power normalization step. Ignored if + improved=False. + + Returns + ------- + fisher_vector : np.ndarray + The computation Fisher vector, which is given by a concatenation of the + gradients of a GMM with respect to its parameters (mixture weights, + means, and covariance matrices). For D-dimensional input descriptors or + vectors, and a K-mode GMM, the Fisher vector dimensionality will be + 2KD + K. Thus, its dimensionality is invariant to the number of + descriptors/vectors. + + References + ---------- + .. [1] Perronnin, F. and Dance, C. Fisher kernels on Visual Vocabularies + for Image Categorization, IEEE Conference on Computer Vision and + Pattern Recognition, 2007 + .. [2] Perronnin, F. and Sanchez, J. and Mensink T. Improving the Fisher + Kernel for Large-Scale Image Classification, ECCV, 2010 + + Examples + -------- + >>> from skimage.feature import fisher_vector, learn_gmm + >>> sift_for_images = [np.random.random((10, 128)) for _ in range(10)] + >>> num_modes = 16 + >>> # Estimate 16-mode GMM with these synthetic SIFT vectors + >>> gmm = learn_gmm(sift_for_images, n_modes=num_modes) + >>> test_image_descriptors = np.random.random((25, 128)) + >>> # Compute the Fisher vector + >>> fv = fisher_vector(test_image_descriptors, gmm) + """ + try: + from sklearn.mixture import GaussianMixture + except ImportError: + raise ImportError( + 'scikit-learn is not installed. Please ensure it is installed in ' + 'order to use the Fisher vector functionality.' + ) + + if not isinstance(descriptors, np.ndarray): + raise DescriptorException('Please ensure descriptors is a NumPy array.') + + if not isinstance(gmm, GaussianMixture): + raise FisherVectorException( + 'Please ensure gmm is a sklearn.mixture.GaussianMixture object.' + ) + + if improved and not isinstance(alpha, float): + raise FisherVectorException( + 'Please ensure that the alpha parameter is a float.' + ) + + num_descriptors = len(descriptors) + + mixture_weights = gmm.weights_ + means = gmm.means_ + covariances = gmm.covariances_ + + posterior_probabilities = gmm.predict_proba(descriptors) + + # Statistics necessary to compute GMM gradients wrt its parameters + pp_sum = posterior_probabilities.mean(axis=0, keepdims=True).T + pp_x = posterior_probabilities.T.dot(descriptors) / num_descriptors + pp_x_2 = posterior_probabilities.T.dot(np.power(descriptors, 2)) / num_descriptors + + # Compute GMM gradients wrt its parameters + d_pi = pp_sum.squeeze() - mixture_weights + + d_mu = pp_x - pp_sum * means + + d_sigma_t1 = pp_sum * np.power(means, 2) + d_sigma_t2 = pp_sum * covariances + d_sigma_t3 = 2 * pp_x * means + d_sigma = -pp_x_2 - d_sigma_t1 + d_sigma_t2 + d_sigma_t3 + + # Apply analytical diagonal normalization + sqrt_mixture_weights = np.sqrt(mixture_weights) + d_pi /= sqrt_mixture_weights + d_mu /= sqrt_mixture_weights[:, np.newaxis] * np.sqrt(covariances) + d_sigma /= np.sqrt(2) * sqrt_mixture_weights[:, np.newaxis] * covariances + + # Concatenate GMM gradients to form Fisher vector representation + fisher_vector = np.hstack((d_pi, d_mu.ravel(), d_sigma.ravel())) + + if improved: + fisher_vector = np.sign(fisher_vector) * np.power(np.abs(fisher_vector), alpha) + fisher_vector = fisher_vector / np.linalg.norm(fisher_vector) + + return fisher_vector diff --git a/envs/kitoverlay/skimage/feature/_hessian_det_appx.cpython-311-x86_64-linux-gnu.so b/envs/kitoverlay/skimage/feature/_hessian_det_appx.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..df01630f5eb9eb0793e6a4e850c9bba78bc42013 Binary files /dev/null and b/envs/kitoverlay/skimage/feature/_hessian_det_appx.cpython-311-x86_64-linux-gnu.so differ diff --git a/envs/kitoverlay/skimage/feature/_hog.py b/envs/kitoverlay/skimage/feature/_hog.py new file mode 100644 index 0000000000000000000000000000000000000000..206361a3d4684361f0de401afa4b9c211cff5e94 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_hog.py @@ -0,0 +1,341 @@ +import numpy as np + +from . import _hoghistogram +from .._shared import utils + + +def _hog_normalize_block(block, method, eps=1e-5): + if method == 'L1': + out = block / (np.sum(np.abs(block)) + eps) + elif method == 'L1-sqrt': + out = np.sqrt(block / (np.sum(np.abs(block)) + eps)) + elif method == 'L2': + out = block / np.sqrt(np.sum(block**2) + eps**2) + elif method == 'L2-Hys': + out = block / np.sqrt(np.sum(block**2) + eps**2) + out = np.minimum(out, 0.2) + out = out / np.sqrt(np.sum(out**2) + eps**2) + else: + raise ValueError('Selected block normalization method is invalid.') + + return out + + +def _hog_channel_gradient(channel): + """Compute unnormalized gradient image along `row` and `col` axes. + + Parameters + ---------- + channel : (M, N) ndarray + Grayscale image or one of image channel. + + Returns + ------- + g_row, g_col : channel gradient along `row` and `col` axes correspondingly. + """ + g_row = np.empty(channel.shape, dtype=channel.dtype) + g_row[0, :] = 0 + g_row[-1, :] = 0 + g_row[1:-1, :] = channel[2:, :] - channel[:-2, :] + g_col = np.empty(channel.shape, dtype=channel.dtype) + g_col[:, 0] = 0 + g_col[:, -1] = 0 + g_col[:, 1:-1] = channel[:, 2:] - channel[:, :-2] + + return g_row, g_col + + +@utils.channel_as_last_axis(multichannel_output=False) +def hog( + image, + orientations=9, + pixels_per_cell=(8, 8), + cells_per_block=(3, 3), + block_norm='L2-Hys', + visualize=False, + transform_sqrt=False, + feature_vector=True, + *, + channel_axis=None, +): + """Extract Histogram of Oriented Gradients (HOG) for a given image. + + Compute a Histogram of Oriented Gradients (HOG) by + + 1. (optional) global image normalization + 2. computing the gradient image in `row` and `col` + 3. computing gradient histograms + 4. normalizing across blocks + 5. flattening into a feature vector + + Parameters + ---------- + image : (M, N[, C]) ndarray + Input image. + orientations : int, optional + Number of orientation bins. + pixels_per_cell : 2-tuple (int, int), optional + Size (in pixels) of a cell. + cells_per_block : 2-tuple (int, int), optional + Number of cells in each block. + block_norm : str {'L1', 'L1-sqrt', 'L2', 'L2-Hys'}, optional + Block normalization method: + + ``L1`` + Normalization using L1-norm. + ``L1-sqrt`` + Normalization using L1-norm, followed by square root. + ``L2`` + Normalization using L2-norm. + ``L2-Hys`` + Normalization using L2-norm, followed by limiting the + maximum values to 0.2 (`Hys` stands for `hysteresis`) and + renormalization using L2-norm. (default) + For details, see [3]_, [4]_. + + visualize : bool, optional + Also return an image of the HOG. For each cell and orientation bin, + the image contains a line segment that is centered at the cell center, + is perpendicular to the midpoint of the range of angles spanned by the + orientation bin, and has intensity proportional to the corresponding + histogram value. + transform_sqrt : bool, optional + Apply power law compression to normalize the image before + processing. DO NOT use this if the image contains negative + values. Also see `notes` section below. + feature_vector : bool, optional + Return the data as a feature vector by calling .ravel() on the result + just before returning. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + `channel_axis` was added in 0.19. + + Returns + ------- + out : (n_blocks_row, n_blocks_col, n_cells_row, n_cells_col, n_orient) ndarray + HOG descriptor for the image. If `feature_vector` is True, a 1D + (flattened) array is returned. + hog_image : (M, N) ndarray, optional + A visualisation of the HOG image. Only provided if `visualize` is True. + + Raises + ------ + ValueError + If the image is too small given the values of pixels_per_cell and + cells_per_block. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients + + .. [2] Dalal, N and Triggs, B, Histograms of Oriented Gradients for + Human Detection, IEEE Computer Society Conference on Computer + Vision and Pattern Recognition 2005 San Diego, CA, USA, + https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf, + :DOI:`10.1109/CVPR.2005.177` + + .. [3] Lowe, D.G., Distinctive image features from scale-invatiant + keypoints, International Journal of Computer Vision (2004) 60: 91, + http://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf, + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + .. [4] Dalal, N, Finding People in Images and Videos, + Human-Computer Interaction [cs.HC], Institut National Polytechnique + de Grenoble - INPG, 2006, + https://tel.archives-ouvertes.fr/tel-00390303/file/NavneetDalalThesis.pdf + + Notes + ----- + The presented code implements the HOG extraction method from [2]_ with + the following changes: (I) blocks of (3, 3) cells are used ((2, 2) in the + paper); (II) no smoothing within cells (Gaussian spatial window with sigma=8pix + in the paper); (III) L1 block normalization is used (L2-Hys in the paper). + + Power law compression, also known as Gamma correction, is used to reduce + the effects of shadowing and illumination variations. The compression makes + the dark regions lighter. When the kwarg `transform_sqrt` is set to + ``True``, the function computes the square root of each color channel + and then applies the hog algorithm to the image. + """ + image = np.atleast_2d(image) + float_dtype = utils._supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + multichannel = channel_axis is not None + ndim_spatial = image.ndim - 1 if multichannel else image.ndim + if ndim_spatial != 2: + raise ValueError( + 'Only images with two spatial dimensions are ' + 'supported. If using with color/multichannel ' + 'images, specify `channel_axis`.' + ) + + """ + The first stage applies an optional global image normalization + equalisation that is designed to reduce the influence of illumination + effects. In practice we use gamma (power law) compression, either + computing the square root or the log of each color channel. + Image texture strength is typically proportional to the local surface + illumination so this compression helps to reduce the effects of local + shadowing and illumination variations. + """ + + if transform_sqrt: + image = np.sqrt(image) + + """ + The second stage computes first order image gradients. These capture + contour, silhouette and some texture information, while providing + further resistance to illumination variations. The locally dominant + color channel is used, which provides color invariance to a large + extent. Variant methods may also include second order image derivatives, + which act as primitive bar detectors - a useful feature for capturing, + e.g. bar like structures in bicycles and limbs in humans. + """ + + if multichannel: + g_row_by_ch = np.empty_like(image, dtype=float_dtype) + g_col_by_ch = np.empty_like(image, dtype=float_dtype) + g_magn = np.empty_like(image, dtype=float_dtype) + + for idx_ch in range(image.shape[2]): + ( + g_row_by_ch[:, :, idx_ch], + g_col_by_ch[:, :, idx_ch], + ) = _hog_channel_gradient(image[:, :, idx_ch]) + g_magn[:, :, idx_ch] = np.hypot( + g_row_by_ch[:, :, idx_ch], g_col_by_ch[:, :, idx_ch] + ) + + # For each pixel select the channel with the highest gradient magnitude + idcs_max = g_magn.argmax(axis=2) + rr, cc = np.meshgrid( + np.arange(image.shape[0]), + np.arange(image.shape[1]), + indexing='ij', + sparse=True, + ) + g_row = g_row_by_ch[rr, cc, idcs_max] + g_col = g_col_by_ch[rr, cc, idcs_max] + else: + g_row, g_col = _hog_channel_gradient(image) + + """ + The third stage aims to produce an encoding that is sensitive to + local image content while remaining resistant to small changes in + pose or appearance. The adopted method pools gradient orientation + information locally in the same way as the SIFT [Lowe 2004] + feature. The image window is divided into small spatial regions, + called "cells". For each cell we accumulate a local 1-D histogram + of gradient or edge orientations over all the pixels in the + cell. This combined cell-level 1-D histogram forms the basic + "orientation histogram" representation. Each orientation histogram + divides the gradient angle range into a fixed number of + predetermined bins. The gradient magnitudes of the pixels in the + cell are used to vote into the orientation histogram. + """ + + s_row, s_col = image.shape[:2] + c_row, c_col = pixels_per_cell + b_row, b_col = cells_per_block + + n_cells_row = int(s_row // c_row) # number of cells along row-axis + n_cells_col = int(s_col // c_col) # number of cells along col-axis + + # compute orientations integral images + orientation_histogram = np.zeros( + (n_cells_row, n_cells_col, orientations), dtype=float + ) + g_row = g_row.astype(float, copy=False) + g_col = g_col.astype(float, copy=False) + + _hoghistogram.hog_histograms( + g_col, + g_row, + c_col, + c_row, + s_col, + s_row, + n_cells_col, + n_cells_row, + orientations, + orientation_histogram, + ) + + # now compute the histogram for each cell + hog_image = None + + if visualize: + from .. import draw + + radius = min(c_row, c_col) // 2 - 1 + orientations_arr = np.arange(orientations) + # set dr_arr, dc_arr to correspond to midpoints of orientation bins + orientation_bin_midpoints = np.pi * (orientations_arr + 0.5) / orientations + dr_arr = radius * np.sin(orientation_bin_midpoints) + dc_arr = radius * np.cos(orientation_bin_midpoints) + hog_image = np.zeros((s_row, s_col), dtype=float_dtype) + for r in range(n_cells_row): + for c in range(n_cells_col): + for o, dr, dc in zip(orientations_arr, dr_arr, dc_arr): + centre = tuple([r * c_row + c_row // 2, c * c_col + c_col // 2]) + rr, cc = draw.line( + int(centre[0] - dc), + int(centre[1] + dr), + int(centre[0] + dc), + int(centre[1] - dr), + ) + hog_image[rr, cc] += orientation_histogram[r, c, o] + + """ + The fourth stage computes normalization, which takes local groups of + cells and contrast normalizes their overall responses before passing + to next stage. Normalization introduces better invariance to illumination, + shadowing, and edge contrast. It is performed by accumulating a measure + of local histogram "energy" over local groups of cells that we call + "blocks". The result is used to normalize each cell in the block. + Typically each individual cell is shared between several blocks, but + its normalizations are block dependent and thus different. The cell + thus appears several times in the final output vector with different + normalizations. This may seem redundant but it improves the performance. + We refer to the normalized block descriptors as Histogram of Oriented + Gradient (HOG) descriptors. + """ + + n_blocks_row = (n_cells_row - b_row) + 1 + n_blocks_col = (n_cells_col - b_col) + 1 + if n_blocks_col <= 0 or n_blocks_row <= 0: + min_row = b_row * c_row + min_col = b_col * c_col + raise ValueError( + 'The input image is too small given the values of ' + 'pixels_per_cell and cells_per_block. ' + 'It should have at least: ' + f'{min_row} rows and {min_col} cols.' + ) + normalized_blocks = np.zeros( + (n_blocks_row, n_blocks_col, b_row, b_col, orientations), dtype=float_dtype + ) + + for r in range(n_blocks_row): + for c in range(n_blocks_col): + block = orientation_histogram[r : r + b_row, c : c + b_col, :] + normalized_blocks[r, c, :] = _hog_normalize_block(block, method=block_norm) + + """ + The final step collects the HOG descriptors from all blocks of a dense + overlapping grid of blocks covering the detection window into a combined + feature vector for use in the window classifier. + """ + + if feature_vector: + normalized_blocks = normalized_blocks.ravel() + + if visualize: + return normalized_blocks, hog_image + else: + return normalized_blocks diff --git a/envs/kitoverlay/skimage/feature/_orb_descriptor_positions.py b/envs/kitoverlay/skimage/feature/_orb_descriptor_positions.py new file mode 100644 index 0000000000000000000000000000000000000000..74e05058c6d71d8459f41dcc26521f2a4af86e5a --- /dev/null +++ b/envs/kitoverlay/skimage/feature/_orb_descriptor_positions.py @@ -0,0 +1,10 @@ +import os +import numpy as np + +# Putting this in cython was giving strange bugs for different versions +# of cython which seemed to indicate troubles with the __file__ variable +# not being defined. Keeping it in pure python makes it more reliable +this_dir = os.path.dirname(__file__) +POS = np.loadtxt(os.path.join(this_dir, "orb_descriptor_positions.txt"), dtype=np.int8) +POS0 = np.ascontiguousarray(POS[:, :2]) +POS1 = np.ascontiguousarray(POS[:, 2:]) diff --git a/envs/kitoverlay/skimage/feature/blob.py b/envs/kitoverlay/skimage/feature/blob.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e073d6759ef27c6ab640c4790283ff950292e9 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/blob.py @@ -0,0 +1,723 @@ +import math + +import numpy as np +import scipy.ndimage as ndi +from scipy import spatial + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_nD +from ..transform import integral_image +from ..util import img_as_float +from ._hessian_det_appx import _hessian_matrix_det +from .peak import peak_local_max + +# This basic blob detection algorithm is based on: +# http://www.cs.utah.edu/~jfishbau/advimproc/project1/ (04.04.2013) +# Theory behind: https://en.wikipedia.org/wiki/Blob_detection (04.04.2013) + + +def _compute_disk_overlap(d, r1, r2): + """ + Compute fraction of surface overlap between two disks of radii + ``r1`` and ``r2``, with centers separated by a distance ``d``. + + Parameters + ---------- + d : float + Distance between centers. + r1 : float + Radius of the first disk. + r2 : float + Radius of the second disk. + + Returns + ------- + fraction: float + Fraction of area of the overlap between the two disks. + """ + + ratio1 = (d**2 + r1**2 - r2**2) / (2 * d * r1) + ratio1 = np.clip(ratio1, -1, 1) + acos1 = math.acos(ratio1) + + ratio2 = (d**2 + r2**2 - r1**2) / (2 * d * r2) + ratio2 = np.clip(ratio2, -1, 1) + acos2 = math.acos(ratio2) + + a = -d + r2 + r1 + b = d - r2 + r1 + c = d + r2 - r1 + d = d + r2 + r1 + area = r1**2 * acos1 + r2**2 * acos2 - 0.5 * math.sqrt(abs(a * b * c * d)) + return area / (math.pi * (min(r1, r2) ** 2)) + + +def _compute_sphere_overlap(d, r1, r2): + """ + Compute volume overlap fraction between two spheres of radii + ``r1`` and ``r2``, with centers separated by a distance ``d``. + + Parameters + ---------- + d : float + Distance between centers. + r1 : float + Radius of the first sphere. + r2 : float + Radius of the second sphere. + + Returns + ------- + fraction: float + Fraction of volume of the overlap between the two spheres. + + Notes + ----- + See for example http://mathworld.wolfram.com/Sphere-SphereIntersection.html + for more details. + """ + vol = ( + math.pi + / (12 * d) + * (r1 + r2 - d) ** 2 + * (d**2 + 2 * d * (r1 + r2) - 3 * (r1**2 + r2**2) + 6 * r1 * r2) + ) + return vol / (4.0 / 3 * math.pi * min(r1, r2) ** 3) + + +def _blob_overlap(blob1, blob2, *, sigma_dim=1): + """Finds the overlapping area fraction between two blobs. + + Returns a float representing fraction of overlapped area. Note that 0.0 + is *always* returned for dimension greater than 3. + + Parameters + ---------- + blob1 : sequence of arrays + A sequence of ``(row, col, sigma)`` or ``(pln, row, col, sigma)``, + where ``row, col`` (or ``(pln, row, col)``) are coordinates + of blob and ``sigma`` is the standard deviation of the Gaussian kernel + which detected the blob. + blob2 : sequence of arrays + A sequence of ``(row, col, sigma)`` or ``(pln, row, col, sigma)``, + where ``row, col`` (or ``(pln, row, col)``) are coordinates + of blob and ``sigma`` is the standard deviation of the Gaussian kernel + which detected the blob. + sigma_dim : int, optional + The dimensionality of the sigma value. Can be 1 or the same as the + dimensionality of the blob space (2 or 3). + + Returns + ------- + f : float + Fraction of overlapped area (or volume in 3D). + """ + ndim = len(blob1) - sigma_dim + if ndim > 3: + return 0.0 + root_ndim = math.sqrt(ndim) + + # we divide coordinates by sigma * sqrt(ndim) to rescale space to isotropy, + # giving spheres of radius = 1 or < 1. + if blob1[-1] == blob2[-1] == 0: + return 0.0 + elif blob1[-1] > blob2[-1]: + max_sigma = blob1[-sigma_dim:] + r1 = 1 + r2 = blob2[-1] / blob1[-1] + else: + max_sigma = blob2[-sigma_dim:] + r2 = 1 + r1 = blob1[-1] / blob2[-1] + pos1 = blob1[:ndim] / (max_sigma * root_ndim) + pos2 = blob2[:ndim] / (max_sigma * root_ndim) + + d = np.sqrt(np.sum((pos2 - pos1) ** 2)) + if d > r1 + r2: # centers farther than sum of radii, so no overlap + return 0.0 + + # one blob is inside the other + if d <= abs(r1 - r2): + return 1.0 + + if ndim == 2: + return _compute_disk_overlap(d, r1, r2) + + else: # ndim=3 http://mathworld.wolfram.com/Sphere-SphereIntersection.html + return _compute_sphere_overlap(d, r1, r2) + + +def _prune_blobs(blobs_array, overlap, *, sigma_dim=1): + """Eliminated blobs with area overlap. + + Parameters + ---------- + blobs_array : ndarray + A 2d array with each row representing 3 (or 4) values, + ``(row, col, sigma)`` or ``(pln, row, col, sigma)`` in 3D, + where ``(row, col)`` (``(pln, row, col)``) are coordinates of the blob + and ``sigma`` is the standard deviation of the Gaussian kernel which + detected the blob. + This array must not have a dimension of size 0. + overlap : float + A value between 0 and 1. If the fraction of area overlapping for 2 + blobs is greater than `overlap` the smaller blob is eliminated. + sigma_dim : int, optional + The number of columns in ``blobs_array`` corresponding to sigmas rather + than positions. + + Returns + ------- + A : ndarray + `array` with overlapping blobs removed. + """ + sigma = blobs_array[:, -sigma_dim:].max() + distance = 2 * sigma * math.sqrt(blobs_array.shape[1] - sigma_dim) + tree = spatial.cKDTree(blobs_array[:, :-sigma_dim]) + pairs = np.array(list(tree.query_pairs(distance))) + if len(pairs) == 0: + return blobs_array + else: + for i, j in pairs: + blob1, blob2 = blobs_array[i], blobs_array[j] + if _blob_overlap(blob1, blob2, sigma_dim=sigma_dim) > overlap: + # note: this test works even in the anisotropic case because + # all sigmas increase together. + if blob1[-1] > blob2[-1]: + blob2[-1] = 0 + else: + blob1[-1] = 0 + + return np.stack([b for b in blobs_array if b[-1] > 0]) + + +def _format_exclude_border(img_ndim, exclude_border): + """Format an ``exclude_border`` argument as a tuple of ints for calling + ``peak_local_max``. + """ + if isinstance(exclude_border, tuple): + if len(exclude_border) != img_ndim: + raise ValueError( + "`exclude_border` should have the same length as the " + "dimensionality of the image." + ) + for exclude in exclude_border: + if not isinstance(exclude, int): + raise ValueError( + "exclude border, when expressed as a tuple, must only " + "contain ints." + ) + return exclude_border + (0,) + elif isinstance(exclude_border, int): + return (exclude_border,) * img_ndim + (0,) + elif exclude_border is True: + raise ValueError("exclude_border cannot be True") + elif exclude_border is False: + return (0,) * (img_ndim + 1) + else: + raise ValueError(f'Unsupported value ({exclude_border}) for exclude_border') + + +def blob_dog( + image, + min_sigma=1, + max_sigma=50, + sigma_ratio=1.6, + threshold=0.5, + overlap=0.5, + *, + threshold_rel=None, + exclude_border=False, +): + r"""Finds blobs in the given grayscale image. + + Blobs are found using the Difference of Gaussian (DoG) method [1]_, [2]_. + For each blob found, the method returns its coordinates and the standard + deviation of the Gaussian kernel that detected the blob. + + Parameters + ---------- + image : ndarray + Input grayscale image, blobs are assumed to be light on dark + background (white on black). + min_sigma : scalar or sequence of scalars, optional + Minimum standard deviation for Gaussian kernel. Keep this value low to + detect smaller blobs. The standard deviation of the Gaussian kernel + is given either as a sequence for each axis, or as a single number, in + which case it is equal for all axes. + max_sigma : scalar or sequence of scalars, optional + The maximum standard deviation for Gaussian kernel. Keep this high to + detect larger blobs. The standard deviation of the Gaussian kernel + is given either as a sequence for each axis, or as a single number, in + which case it is equal for all axes. + sigma_ratio : float, optional + The ratio between the standard deviation of Gaussian Kernels used for + computing the Difference of Gaussians + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(dog_space) * threshold_rel``, where ``dog_space`` refers to the + stack of Difference-of-Gaussian (DoG) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + exclude_border : tuple of ints, int, or False, optional + If tuple of ints, the length of the tuple must match the input array's + dimensionality. Each element of the tuple will exclude peaks from + within `exclude_border`-pixels of the border of the image along that + dimension. + If nonzero int, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If zero or False, peaks are identified regardless of their + distance from the border. + + Returns + ------- + A : (n, image.ndim + sigma) ndarray + A 2d array with each row representing 2 coordinate values for a 2D + image, or 3 coordinate values for a 3D image, plus the sigma(s) used. + When a single sigma is passed, outputs are: + ``(r, c, sigma)`` or ``(p, r, c, sigma)`` where ``(r, c)`` or + ``(p, r, c)`` are coordinates of the blob and ``sigma`` is the standard + deviation of the Gaussian kernel which detected the blob. When an + anisotropic gaussian is used (sigmas per dimension), the detected sigma + is returned for each dimension. + + See also + -------- + skimage.filters.difference_of_gaussians + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach + .. [2] Lowe, D. G. "Distinctive Image Features from Scale-Invariant + Keypoints." International Journal of Computer Vision 60, 91–110 (2004). + https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + Examples + -------- + >>> from skimage import data, feature + >>> coins = data.coins() + >>> feature.blob_dog(coins, threshold=.05, min_sigma=10, max_sigma=40) + array([[128., 155., 10.], + [198., 155., 10.], + [124., 338., 10.], + [127., 102., 10.], + [193., 281., 10.], + [126., 208., 10.], + [267., 115., 10.], + [197., 102., 10.], + [198., 215., 10.], + [123., 279., 10.], + [126., 46., 10.], + [259., 247., 10.], + [196., 43., 10.], + [ 54., 276., 10.], + [267., 358., 10.], + [ 58., 100., 10.], + [259., 305., 10.], + [185., 347., 16.], + [261., 174., 16.], + [ 46., 336., 16.], + [ 54., 217., 10.], + [ 55., 157., 10.], + [ 57., 41., 10.], + [260., 47., 16.]]) + + Notes + ----- + The radius of each blob is approximately :math:`\sqrt{2}\sigma` for + a 2-D image and :math:`\sqrt{3}\sigma` for a 3-D image. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + # if both min and max sigma are scalar, function returns only one sigma + scalar_sigma = np.isscalar(max_sigma) and np.isscalar(min_sigma) + + # Gaussian filter requires that sequence-type sigmas have same + # dimensionality as image. This broadcasts scalar kernels + if np.isscalar(max_sigma): + max_sigma = np.full(image.ndim, max_sigma, dtype=float_dtype) + if np.isscalar(min_sigma): + min_sigma = np.full(image.ndim, min_sigma, dtype=float_dtype) + + # Convert sequence types to array + min_sigma = np.asarray(min_sigma, dtype=float_dtype) + max_sigma = np.asarray(max_sigma, dtype=float_dtype) + + if sigma_ratio <= 1.0: + raise ValueError('sigma_ratio must be > 1.0') + + # k such that min_sigma*(sigma_ratio**k) > max_sigma + k = int(np.mean(np.log(max_sigma / min_sigma) / np.log(sigma_ratio) + 1)) + + # a geometric progression of standard deviations for gaussian kernels + sigma_list = np.array([min_sigma * (sigma_ratio**i) for i in range(k + 1)]) + + # computing difference between two successive Gaussian blurred images + # to obtain an approximation of the scale invariant Laplacian of the + # Gaussian operator + dog_image_cube = np.empty(image.shape + (k,), dtype=float_dtype) + gaussian_previous = gaussian(image, sigma=sigma_list[0], mode='reflect') + for i, s in enumerate(sigma_list[1:]): + gaussian_current = gaussian(image, sigma=s, mode='reflect') + dog_image_cube[..., i] = gaussian_previous - gaussian_current + gaussian_previous = gaussian_current + + # normalization factor for consistency in DoG magnitude + sf = 1 / (sigma_ratio - 1) + dog_image_cube *= sf + + exclude_border = _format_exclude_border(image.ndim, exclude_border) + local_maxima = peak_local_max( + dog_image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + footprint=np.ones((3,) * (image.ndim + 1)), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, image.ndim + (1 if scalar_sigma else image.ndim))) + + # Convert local_maxima to float64 + lm = local_maxima.astype(float_dtype) + + # translate final column of lm, which contains the index of the + # sigma that produced the maximum intensity value, into the sigma + sigmas_of_peaks = sigma_list[local_maxima[:, -1]] + + if scalar_sigma: + # select one sigma column, keeping dimension + sigmas_of_peaks = sigmas_of_peaks[:, 0:1] + + # Remove sigma index and replace with sigmas + lm = np.hstack([lm[:, :-1], sigmas_of_peaks]) + + sigma_dim = sigmas_of_peaks.shape[1] + + return _prune_blobs(lm, overlap, sigma_dim=sigma_dim) + + +def blob_log( + image, + min_sigma=1, + max_sigma=50, + num_sigma=10, + threshold=0.2, + overlap=0.5, + log_scale=False, + *, + threshold_rel=None, + exclude_border=False, +): + r"""Finds blobs in the given grayscale image. + + Blobs are found using the Laplacian of Gaussian (LoG) method [1]_. + For each blob found, the method returns its coordinates and the standard + deviation of the Gaussian kernel that detected the blob. + + Parameters + ---------- + image : ndarray + Input grayscale image, blobs are assumed to be light on dark + background (white on black). + min_sigma : scalar or sequence of scalars, optional + Minimum standard deviation for Gaussian kernel. Keep this value low to + detect smaller blobs. The standard deviation of the Gaussian kernel + is given either as a sequence for each axis, or as a single number, in + which case it is equal for all axes. + max_sigma : scalar or sequence of scalars, optional + The maximum standard deviation for Gaussian kernel. Keep this high to + detect larger blobs. The standard deviation of the Gaussian kernel + is given either as a sequence for each axis, or as a single number, in + which case it is equal for all axes. + num_sigma : int, optional + The number of evenly spaced values for standard deviation of the + Gaussian kernel to consider on the closed interval + ``[min_sigma, max_sigma]``. + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + log_scale : bool, optional + If set intermediate values of standard deviations are interpolated + using a logarithmic scale to the base `10`. If not, linear + interpolation is used. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(log_space) * threshold_rel``, where ``log_space`` refers to the + stack of Laplacian-of-Gaussian (LoG) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + exclude_border : tuple of ints, int, or False, optional + If tuple of ints, the length of the tuple must match the input array's + dimensionality. Each element of the tuple will exclude peaks from + within `exclude_border`-pixels of the border of the image along that + dimension. + If nonzero int, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If zero or False, peaks are identified regardless of their + distance from the border. + + Returns + ------- + A : (n, image.ndim + sigma) ndarray + A 2d array with each row representing 2 coordinate values for a 2D + image, or 3 coordinate values for a 3D image, plus the sigma(s) used. + When a single sigma is passed, outputs are: + ``(r, c, sigma)`` or ``(p, r, c, sigma)`` where ``(r, c)`` or + ``(p, r, c)`` are coordinates of the blob and ``sigma`` is the standard + deviation of the Gaussian kernel which detected the blob. When an + anisotropic gaussian is used (sigmas per dimension), the detected sigma + is returned for each dimension. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian + + Examples + -------- + >>> from skimage import data, feature, exposure + >>> img = data.coins() + >>> img = exposure.equalize_hist(img) # improves detection + >>> feature.blob_log(img, threshold = .3) + array([[124. , 336. , 11.88888889], + [198. , 155. , 11.88888889], + [194. , 213. , 17.33333333], + [121. , 272. , 17.33333333], + [263. , 244. , 17.33333333], + [194. , 276. , 17.33333333], + [266. , 115. , 11.88888889], + [128. , 154. , 11.88888889], + [260. , 174. , 17.33333333], + [198. , 103. , 11.88888889], + [126. , 208. , 11.88888889], + [127. , 102. , 11.88888889], + [263. , 302. , 17.33333333], + [197. , 44. , 11.88888889], + [185. , 344. , 17.33333333], + [126. , 46. , 11.88888889], + [113. , 323. , 1. ]]) + + Notes + ----- + The radius of each blob is approximately :math:`\sqrt{2}\sigma` for + a 2-D image and :math:`\sqrt{3}\sigma` for a 3-D image. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + # if both min and max sigma are scalar, function returns only one sigma + scalar_sigma = True if np.isscalar(max_sigma) and np.isscalar(min_sigma) else False + + # Gaussian filter requires that sequence-type sigmas have same + # dimensionality as image. This broadcasts scalar kernels + if np.isscalar(max_sigma): + max_sigma = np.full(image.ndim, max_sigma, dtype=float_dtype) + if np.isscalar(min_sigma): + min_sigma = np.full(image.ndim, min_sigma, dtype=float_dtype) + + # Convert sequence types to array + min_sigma = np.asarray(min_sigma, dtype=float_dtype) + max_sigma = np.asarray(max_sigma, dtype=float_dtype) + + if log_scale: + start = np.log10(min_sigma) + stop = np.log10(max_sigma) + sigma_list = np.logspace(start, stop, num_sigma) + else: + sigma_list = np.linspace(min_sigma, max_sigma, num_sigma) + + # computing gaussian laplace + image_cube = np.empty(image.shape + (len(sigma_list),), dtype=float_dtype) + for i, s in enumerate(sigma_list): + # average s**2 provides scale invariance + image_cube[..., i] = -ndi.gaussian_laplace(image, s) * np.mean(s) ** 2 + + exclude_border = _format_exclude_border(image.ndim, exclude_border) + local_maxima = peak_local_max( + image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + footprint=np.ones((3,) * (image.ndim + 1)), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, image.ndim + (1 if scalar_sigma else image.ndim))) + + # Convert local_maxima to float64 + lm = local_maxima.astype(float_dtype) + + # translate final column of lm, which contains the index of the + # sigma that produced the maximum intensity value, into the sigma + sigmas_of_peaks = sigma_list[local_maxima[:, -1]] + + if scalar_sigma: + # select one sigma column, keeping dimension + sigmas_of_peaks = sigmas_of_peaks[:, 0:1] + + # Remove sigma index and replace with sigmas + lm = np.hstack([lm[:, :-1], sigmas_of_peaks]) + + sigma_dim = sigmas_of_peaks.shape[1] + + return _prune_blobs(lm, overlap, sigma_dim=sigma_dim) + + +def blob_doh( + image, + min_sigma=1, + max_sigma=30, + num_sigma=10, + threshold=0.01, + overlap=0.5, + log_scale=False, + *, + threshold_rel=None, +): + """Finds blobs in the given grayscale image. + + Blobs are found using the Determinant of Hessian method [1]_. For each blob + found, the method returns its coordinates and the standard deviation + of the Gaussian Kernel used for the Hessian matrix whose determinant + detected the blob. Determinant of Hessians is approximated using [2]_. + + Parameters + ---------- + image : 2D ndarray + Input grayscale image. Blobs can either be light on dark or vice versa. + min_sigma : float, optional + The minimum standard deviation for Gaussian Kernel used to compute + Hessian matrix. Keep this value low to detect smaller blobs. + The standard deviation of the Gaussian kernel is given either as a + sequence for each axis, or as a single number, in which case it is + equal for all axes. + max_sigma : float, optional + The maximum standard deviation for Gaussian Kernel used to compute + Hessian matrix. Keep this value high to detect larger blobs. + The standard deviation of the Gaussian kernel is given either as a + sequence for each axis, or as a single number, in which case it is + equal for all axes. + num_sigma : int, optional + The number of evenly spaced values for standard deviation of the + Gaussian kernel to consider on the closed interval + ``[min_sigma, max_sigma]``. + threshold : float or None, optional + The absolute lower bound for scale space maxima. Local maxima smaller + than `threshold` are ignored. Reduce this to detect blobs with lower + intensities. If `threshold_rel` is also specified, whichever threshold + is larger will be used. If None, `threshold_rel` is used instead. + overlap : float, optional + A value between 0 and 1. If the area of two blobs overlaps by a + fraction greater than `threshold`, the smaller blob is eliminated. + log_scale : bool, optional + If set intermediate values of standard deviations are interpolated + using a logarithmic scale to the base `10`. If not, linear + interpolation is used. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(doh_space) * threshold_rel``, where ``doh_space`` refers to the + stack of Determinant-of-Hessian (DoH) images computed internally. This + should have a value between 0 and 1. If None, `threshold` is used + instead. + + Returns + ------- + A : (n, 3) ndarray + A 2d array with each row representing 3 values, ``(y,x,sigma)`` + where ``(y,x)`` are coordinates of the blob and ``sigma`` is the + standard deviation of the Gaussian kernel of the Hessian Matrix whose + determinant detected the blob. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Blob_detection#The_determinant_of_the_Hessian + .. [2] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, + "SURF: Speeded Up Robust Features" + ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf + + Examples + -------- + >>> from skimage import data, feature + >>> img = data.coins() + >>> feature.blob_doh(img) + array([[197. , 153. , 20.33333333], + [124. , 336. , 20.33333333], + [126. , 153. , 20.33333333], + [195. , 100. , 23.55555556], + [192. , 212. , 23.55555556], + [121. , 271. , 30. ], + [126. , 101. , 20.33333333], + [193. , 275. , 23.55555556], + [123. , 205. , 20.33333333], + [270. , 363. , 30. ], + [265. , 113. , 23.55555556], + [262. , 243. , 23.55555556], + [185. , 348. , 30. ], + [156. , 302. , 30. ], + [123. , 44. , 23.55555556], + [260. , 173. , 30. ], + [197. , 44. , 20.33333333]]) + + Notes + ----- + The radius of each blob is approximately `sigma`. + Computation of Determinant of Hessians is independent of the standard + deviation. Therefore detecting larger blobs won't take more time. In + methods line :py:meth:`blob_dog` and :py:meth:`blob_log` the computation + of Gaussians for larger `sigma` takes more time. The downside is that + this method can't be used for detecting blobs of radius less than `3px` + due to the box filters used in the approximation of Hessian Determinant. + """ + check_nD(image, 2) + + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + image = integral_image(image) + + if log_scale: + start, stop = math.log(min_sigma, 10), math.log(max_sigma, 10) + sigma_list = np.logspace(start, stop, num_sigma) + else: + sigma_list = np.linspace(min_sigma, max_sigma, num_sigma) + + image_cube = np.empty(shape=image.shape + (len(sigma_list),), dtype=float_dtype) + for j, s in enumerate(sigma_list): + image_cube[..., j] = _hessian_matrix_det(image, s) + + local_maxima = peak_local_max( + image_cube, + threshold_abs=threshold, + threshold_rel=threshold_rel, + exclude_border=False, + footprint=np.ones((3,) * image_cube.ndim), + ) + + # Catch no peaks + if local_maxima.size == 0: + return np.empty((0, 3)) + # Convert local_maxima to float64 + lm = local_maxima.astype(np.float64) + # Convert the last index to its corresponding scale value + lm[:, -1] = sigma_list[local_maxima[:, -1]] + return _prune_blobs(lm, overlap) diff --git a/envs/kitoverlay/skimage/feature/brief.py b/envs/kitoverlay/skimage/feature/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..634efb2c892842f0925dec470670d1f2090b5da8 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/brief.py @@ -0,0 +1,216 @@ +import copy + +import numpy as np +from packaging.version import Version + +from .._shared.filters import gaussian +from .._shared.utils import check_nD +from .brief_cy import _brief_loop +from .util import ( + DescriptorExtractor, + _mask_border_keypoints, + _prepare_grayscale_input_2D, +) + + +np2 = Version(np.__version__) >= Version('2') + + +class BRIEF(DescriptorExtractor): + """BRIEF binary descriptor extractor. + + BRIEF (Binary Robust Independent Elementary Features) is an efficient + feature point descriptor. It is highly discriminative even when using + relatively few bits and is computed using simple intensity difference + tests. + + For each keypoint, intensity comparisons are carried out for a specifically + distributed number N of pixel-pairs resulting in a binary descriptor of + length N. For binary descriptors the Hamming distance can be used for + feature matching, which leads to lower computational cost in comparison to + the L2 norm. + + Parameters + ---------- + descriptor_size : int, optional + Size of BRIEF descriptor for each keypoint. Sizes 128, 256 and 512 + recommended by the authors. Default is 256. + patch_size : int, optional + Length of the two dimensional square patch sampling region around + the keypoints. Default is 49. + mode : {'normal', 'uniform'}, optional + Probability distribution for sampling location of decision pixel-pairs + around keypoints. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator (RNG). + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG is used for the random sampling of the decision + pixel-pairs. From a square window with length `patch_size`, + pixel pairs are sampled using the `mode` parameter to build + the descriptors using intensity comparison. + + For matching across images, the same `rng` should be used to construct + descriptors. To facilitate this: + + (a) `rng` defaults to 1 + (b) Subsequent calls of the ``extract`` method will use the same rng/seed. + sigma : float, optional + Standard deviation of the Gaussian low-pass filter applied to the image + to alleviate noise sensitivity, which is strongly recommended to obtain + discriminative and good descriptors. + + Attributes + ---------- + descriptors : (Q, `descriptor_size`) array of dtype bool + 2D ndarray of binary descriptors of size `descriptor_size` for Q + keypoints after filtering out border keypoints with value at an + index ``(i, j)`` either being ``True`` or ``False`` representing + the outcome of the intensity comparison for i-th keypoint on j-th + decision pixel-pair. It is ``Q == np.sum(mask)``. + mask : (N,) array of dtype bool + Mask indicating whether a keypoint has been filtered out + (``False``) or is described in the `descriptors` array (``True``). + + Examples + -------- + >>> from skimage.feature import (corner_harris, corner_peaks, BRIEF, + ... match_descriptors) + >>> import numpy as np + >>> square1 = np.zeros((8, 8), dtype=np.int32) + >>> square1[2:6, 2:6] = 1 + >>> square1 + array([[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, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 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, 0]], dtype=int32) + >>> square2 = np.zeros((9, 9), dtype=np.int32) + >>> square2[2:7, 2:7] = 1 + >>> square2 + array([[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, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 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, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) + >>> keypoints1 = corner_peaks(corner_harris(square1), min_distance=1) + >>> keypoints2 = corner_peaks(corner_harris(square2), min_distance=1) + >>> extractor = BRIEF(patch_size=5) + >>> extractor.extract(square1, keypoints1) + >>> descriptors1 = extractor.descriptors + >>> extractor.extract(square2, keypoints2) + >>> descriptors2 = extractor.descriptors + >>> matches = match_descriptors(descriptors1, descriptors2) + >>> matches + array([[0, 0], + [1, 1], + [2, 2], + [3, 3]]) + >>> keypoints1[matches[:, 0]] + array([[2, 2], + [2, 5], + [5, 2], + [5, 5]]) + >>> keypoints2[matches[:, 1]] + array([[2, 2], + [2, 6], + [6, 2], + [6, 6]]) + + """ + + def __init__( + self, descriptor_size=256, patch_size=49, mode='normal', sigma=1, rng=1 + ): + mode = mode.lower() + if mode not in ('normal', 'uniform'): + raise ValueError("`mode` must be 'normal' or 'uniform'.") + + self.descriptor_size = descriptor_size + self.patch_size = patch_size + self.mode = mode + self.sigma = sigma + + if isinstance(rng, np.random.Generator): + # Spawn an independent RNG from parent RNG provided by the user. + # This is necessary so that we can safely deepcopy the RNG. + # See https://github.com/scikit-learn/scikit-learn/issues/16988#issuecomment-1518037853 + bg = rng._bit_generator + ss = bg._seed_seq + (child_ss,) = ss.spawn(1) + self.rng = np.random.Generator(type(bg)(child_ss)) + elif rng is None: + self.rng = np.random.default_rng(np.random.SeedSequence()) + else: + self.rng = np.random.default_rng(rng) + + self.descriptors = None + self.mask = None + + def extract(self, image, keypoints): + """Extract BRIEF binary descriptors for given keypoints in image. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + + """ + check_nD(image, 2) + + # Copy RNG so we can repeatedly call extract with the same random values + rng = copy.deepcopy(self.rng) + + image = _prepare_grayscale_input_2D(image) + + # Gaussian low-pass filtering to alleviate noise sensitivity + image = np.ascontiguousarray(gaussian(image, sigma=self.sigma, mode='reflect')) + + # Sampling pairs of decision pixels in patch_size x patch_size window + desc_size = self.descriptor_size + patch_size = self.patch_size + if self.mode == 'normal': + samples = (patch_size / 5.0) * rng.standard_normal(desc_size * 8) + samples = np.array(samples, dtype=np.int32) + samples = samples[ + (samples < (patch_size // 2)) & (samples > -(patch_size - 2) // 2) + ] + + pos1 = samples[: desc_size * 2].reshape(desc_size, 2) + pos2 = samples[desc_size * 2 : desc_size * 4].reshape(desc_size, 2) + elif self.mode == 'uniform': + samples = rng.integers( + -(patch_size - 2) // 2, (patch_size // 2) + 1, (desc_size * 2, 2) + ) + samples = np.array(samples, dtype=np.int32) + pos1, pos2 = np.split(samples, 2) + + pos1 = np.ascontiguousarray(pos1) + pos2 = np.ascontiguousarray(pos2) + + # Removing keypoints that are within (patch_size / 2) distance from the + # image border + self.mask = _mask_border_keypoints(image.shape, keypoints, patch_size // 2) + + keypoints = np.array( + keypoints[self.mask, :], + dtype=np.int64, + order='C', + copy=None if np2 else False, + ) + + self.descriptors = np.zeros( + (keypoints.shape[0], desc_size), dtype=bool, order='C' + ) + + _brief_loop(image, self.descriptors.view(np.uint8), keypoints, pos1, pos2) diff --git a/envs/kitoverlay/skimage/feature/censure.py b/envs/kitoverlay/skimage/feature/censure.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5e9564d8524d4649909bb42ac814516fc0a5e5 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/censure.py @@ -0,0 +1,346 @@ +import numpy as np +from scipy.ndimage import maximum_filter, minimum_filter, convolve + +from ..transform import integral_image +from .corner import structure_tensor +from ..morphology import octagon, star +from .censure_cy import _censure_dob_loop +from ..feature.util import ( + FeatureDetector, + _prepare_grayscale_input_2D, + _mask_border_keypoints, +) +from .._shared.utils import check_nD + +# The paper(Reference [1]) mentions the sizes of the Octagon shaped filter +# kernel for the first seven scales only. The sizes of the later scales +# have been extrapolated based on the following statement in the paper. +# "These octagons scale linearly and were experimentally chosen to correspond +# to the seven DOBs described in the previous section." +OCTAGON_OUTER_SHAPE = [ + (5, 2), + (5, 3), + (7, 3), + (9, 4), + (9, 7), + (13, 7), + (15, 10), + (15, 11), + (15, 12), + (17, 13), + (17, 14), +] +OCTAGON_INNER_SHAPE = [ + (3, 0), + (3, 1), + (3, 2), + (5, 2), + (5, 3), + (5, 4), + (5, 5), + (7, 5), + (7, 6), + (9, 6), + (9, 7), +] + +# The sizes for the STAR shaped filter kernel for different scales have been +# taken from the OpenCV implementation. +STAR_SHAPE = [1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 23, 32, 45, 46, 64, 90, 128] +STAR_FILTER_SHAPE = [ + (1, 0), + (3, 1), + (4, 2), + (5, 3), + (7, 4), + (8, 5), + (9, 6), + (11, 8), + (13, 10), + (14, 11), + (15, 12), + (16, 14), +] + + +def _filter_image(image, min_scale, max_scale, mode): + response = np.zeros( + (image.shape[0], image.shape[1], max_scale - min_scale + 1), dtype=np.float64 + ) + + if mode == 'dob': + # make response[:, :, i] contiguous memory block + item_size = response.itemsize + response = np.lib.stride_tricks.as_strided( + response, + strides=( + item_size * response.shape[1], + item_size, + item_size * response.shape[0] * response.shape[1], + ), + ) + + integral_img = integral_image(image) + + for i in range(max_scale - min_scale + 1): + n = min_scale + i + + # Constant multipliers for the outer region and the inner region + # of the bi-level filters with the constraint of keeping the + # DC bias 0. + inner_weight = 1.0 / (2 * n + 1) ** 2 + outer_weight = 1.0 / (12 * n**2 + 4 * n) + + _censure_dob_loop( + n, integral_img, response[:, :, i], inner_weight, outer_weight + ) + + # NOTE : For the Octagon shaped filter, we implemented and evaluated the + # slanted integral image based image filtering but the performance was + # more or less equal to image filtering using + # scipy.ndimage.filters.convolve(). Hence we have decided to use the + # later for a much cleaner implementation. + elif mode == 'octagon': + # TODO : Decide the shapes of Octagon filters for scales > 7 + + for i in range(max_scale - min_scale + 1): + mo, no = OCTAGON_OUTER_SHAPE[min_scale + i - 1] + mi, ni = OCTAGON_INNER_SHAPE[min_scale + i - 1] + response[:, :, i] = convolve(image, _octagon_kernel(mo, no, mi, ni)) + + elif mode == 'star': + for i in range(max_scale - min_scale + 1): + m = STAR_SHAPE[STAR_FILTER_SHAPE[min_scale + i - 1][0]] + n = STAR_SHAPE[STAR_FILTER_SHAPE[min_scale + i - 1][1]] + response[:, :, i] = convolve(image, _star_kernel(m, n)) + + return response + + +def _octagon_kernel(mo, no, mi, ni): + outer = (mo + 2 * no) ** 2 - 2 * no * (no + 1) + inner = (mi + 2 * ni) ** 2 - 2 * ni * (ni + 1) + outer_weight = 1.0 / (outer - inner) + inner_weight = 1.0 / inner + c = ((mo + 2 * no) - (mi + 2 * ni)) // 2 + outer_oct = octagon(mo, no) + inner_oct = np.zeros((mo + 2 * no, mo + 2 * no)) + inner_oct[c:-c, c:-c] = octagon(mi, ni) + bfilter = outer_weight * outer_oct - (outer_weight + inner_weight) * inner_oct + return bfilter + + +def _star_kernel(m, n): + c = m + m // 2 - n - n // 2 + outer_star = star(m) + inner_star = np.zeros_like(outer_star) + inner_star[c:-c, c:-c] = star(n) + outer_weight = 1.0 / (np.sum(outer_star - inner_star)) + inner_weight = 1.0 / np.sum(inner_star) + bfilter = outer_weight * outer_star - (outer_weight + inner_weight) * inner_star + return bfilter + + +def _suppress_lines(feature_mask, image, sigma, line_threshold): + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + feature_mask[(Arr + Acc) ** 2 > line_threshold * (Arr * Acc - Arc**2)] = False + + +class CENSURE(FeatureDetector): + """CENSURE keypoint detector. + + min_scale : int, optional + Minimum scale to extract keypoints from. + max_scale : int, optional + Maximum scale to extract keypoints from. The keypoints will be + extracted from all the scales except the first and the last i.e. + from the scales in the range [min_scale + 1, max_scale - 1]. The filter + sizes for different scales is such that the two adjacent scales + comprise of an octave. + mode : {'DoB', 'Octagon', 'STAR'}, optional + Type of bi-level filter used to get the scales of the input image. + Possible values are 'DoB', 'Octagon' and 'STAR'. The three modes + represent the shape of the bi-level filters i.e. box(square), octagon + and star respectively. For instance, a bi-level octagon filter consists + of a smaller inner octagon and a larger outer octagon with the filter + weights being uniformly negative in both the inner octagon while + uniformly positive in the difference region. Use STAR and Octagon for + better features and DoB for better performance. + non_max_threshold : float, optional + Threshold value used to suppress maximas and minimas with a weak + magnitude response obtained after Non-Maximal Suppression. + line_threshold : float, optional + Threshold for rejecting interest points which have ratio of principal + curvatures greater than this value. + + Attributes + ---------- + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + + References + ---------- + .. [1] Motilal Agrawal, Kurt Konolige and Morten Rufus Blas + "CENSURE: Center Surround Extremas for Realtime Feature + Detection and Matching", + https://link.springer.com/chapter/10.1007/978-3-540-88693-8_8 + :DOI:`10.1007/978-3-540-88693-8_8` + + .. [2] Adam Schmidt, Marek Kraft, Michal Fularz and Zuzanna Domagala + "Comparative Assessment of Point Feature Detectors and + Descriptors in the Context of Robot Navigation" + http://yadda.icm.edu.pl/yadda/element/bwmeta1.element.baztech-268aaf28-0faf-4872-a4df-7e2e61cb364c/c/Schmidt_comparative.pdf + :DOI:`10.1.1.465.1117` + + Examples + -------- + >>> from skimage.data import astronaut + >>> from skimage.color import rgb2gray + >>> from skimage.feature import CENSURE + >>> img = rgb2gray(astronaut()[100:300, 100:300]) + >>> censure = CENSURE() + >>> censure.detect(img) + >>> censure.keypoints + array([[ 4, 148], + [ 12, 73], + [ 21, 176], + [ 91, 22], + [ 93, 56], + [ 94, 22], + [ 95, 54], + [100, 51], + [103, 51], + [106, 67], + [108, 15], + [117, 20], + [122, 60], + [125, 37], + [129, 37], + [133, 76], + [145, 44], + [146, 94], + [150, 114], + [153, 33], + [154, 156], + [155, 151], + [184, 63]]) + >>> censure.scales + array([2, 6, 6, 2, 4, 3, 2, 3, 2, 6, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 4, 2, + 2]) + + """ + + def __init__( + self, + min_scale=1, + max_scale=7, + mode='DoB', + non_max_threshold=0.15, + line_threshold=10, + ): + mode = mode.lower() + if mode not in ('dob', 'octagon', 'star'): + raise ValueError("`mode` must be one of 'DoB', 'Octagon', 'STAR'.") + + if min_scale < 1 or max_scale < 1 or max_scale - min_scale < 2: + raise ValueError( + 'The scales must be >= 1 and the number of ' 'scales should be >= 3.' + ) + + self.min_scale = min_scale + self.max_scale = max_scale + self.mode = mode + self.non_max_threshold = non_max_threshold + self.line_threshold = line_threshold + + self.keypoints = None + self.scales = None + + def detect(self, image): + """Detect CENSURE keypoints along with the corresponding scale. + + Parameters + ---------- + image : 2D ndarray + Input image. + + """ + + # (1) First we generate the required scales on the input grayscale + # image using a bi-level filter and stack them up in `filter_response`. + + # (2) We then perform Non-Maximal suppression in 3 x 3 x 3 window on + # the filter_response to suppress points that are neither minima or + # maxima in 3 x 3 x 3 neighborhood. We obtain a boolean ndarray + # `feature_mask` containing all the minimas and maximas in + # `filter_response` as True. + # (3) Then we suppress all the points in the `feature_mask` for which + # the corresponding point in the image at a particular scale has the + # ratio of principal curvatures greater than `line_threshold`. + # (4) Finally, we remove the border keypoints and return the keypoints + # along with its corresponding scale. + + check_nD(image, 2) + + num_scales = self.max_scale - self.min_scale + + image = np.ascontiguousarray(_prepare_grayscale_input_2D(image)) + + # Generating all the scales + filter_response = _filter_image( + image, self.min_scale, self.max_scale, self.mode + ) + + # Suppressing points that are neither minima or maxima in their + # 3 x 3 x 3 neighborhood to zero + minimas = minimum_filter(filter_response, (3, 3, 3)) == filter_response + maximas = maximum_filter(filter_response, (3, 3, 3)) == filter_response + + feature_mask = minimas | maximas + feature_mask[filter_response < self.non_max_threshold] = False + + for i in range(1, num_scales): + # sigma = (window_size - 1) / 6.0, so the window covers > 99% of + # the kernel's distribution + # window_size = 7 + 2 * (min_scale - 1 + i) + # Hence sigma = 1 + (min_scale - 1 + i)/ 3.0 + _suppress_lines( + feature_mask[:, :, i], + image, + (1 + (self.min_scale + i - 1) / 3.0), + self.line_threshold, + ) + + rows, cols, scales = np.nonzero(feature_mask[..., 1:num_scales]) + keypoints = np.column_stack([rows, cols]) + scales = scales + self.min_scale + 1 + + if self.mode == 'dob': + self.keypoints = keypoints + self.scales = scales + return + + cumulative_mask = np.zeros(keypoints.shape[0], dtype=bool) + + if self.mode == 'octagon': + for i in range(self.min_scale + 1, self.max_scale): + c = (OCTAGON_OUTER_SHAPE[i - 1][0] - 1) // 2 + OCTAGON_OUTER_SHAPE[ + i - 1 + ][1] + cumulative_mask |= _mask_border_keypoints(image.shape, keypoints, c) & ( + scales == i + ) + elif self.mode == 'star': + for i in range(self.min_scale + 1, self.max_scale): + c = ( + STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] + + STAR_SHAPE[STAR_FILTER_SHAPE[i - 1][0]] // 2 + ) + cumulative_mask |= _mask_border_keypoints(image.shape, keypoints, c) & ( + scales == i + ) + + self.keypoints = keypoints[cumulative_mask] + self.scales = scales[cumulative_mask] diff --git a/envs/kitoverlay/skimage/feature/corner.py b/envs/kitoverlay/skimage/feature/corner.py new file mode 100644 index 0000000000000000000000000000000000000000..66926e316ee8cf74cf6436b185fd5b037c5632ea --- /dev/null +++ b/envs/kitoverlay/skimage/feature/corner.py @@ -0,0 +1,1355 @@ +import functools +import math +from itertools import combinations_with_replacement + +import numpy as np +from scipy import ndimage as ndi +from scipy import spatial, stats + +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, safe_as_int, warn +from ..transform import integral_image +from ..util import img_as_float +from ._hessian_det_appx import _hessian_matrix_det +from .corner_cy import _corner_fast, _corner_moravec, _corner_orientations +from .peak import peak_local_max +from .util import _prepare_grayscale_input_2D, _prepare_grayscale_input_nD + + +def _compute_derivatives(image, mode='constant', cval=0): + """Compute derivatives in axis directions using the Sobel operator. + + Parameters + ---------- + image : ndarray + Input image. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + derivatives : list of ndarray + Derivatives in each axis direction. + + """ + + derivatives = [ + ndi.sobel(image, axis=i, mode=mode, cval=cval) for i in range(image.ndim) + ] + + return derivatives + + +def structure_tensor(image, sigma=1, mode='constant', cval=0, order='rc'): + """Compute structure tensor using sum of squared differences. + + The (2-dimensional) structure tensor A is defined as:: + + A = [Arr Arc] + [Arc Acc] + + which is approximated by the weighted sum of squared differences in a local + window around each pixel in the image. This formula can be extended to a + larger number of dimensions (see [1]_). + + Parameters + ---------- + image : ndarray + Input image. + sigma : float or array-like of float, optional + Standard deviation used for the Gaussian kernel, which is used as a + weighting function for the local summation of squared differences. + If sigma is an iterable, its length must be equal to `image.ndim` and + each element is used for the Gaussian kernel applied along its + respective axis. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + NOTE: 'xy' is only an option for 2D images, higher dimensions must + always use 'rc' order. This parameter allows for the use of reverse or + forward order of the image axes in gradient computation. 'rc' indicates + the use of the first axis initially (Arr, Arc, Acc), whilst 'xy' + indicates the usage of the last axis initially (Axx, Axy, Ayy). + + Returns + ------- + A_elems : list of ndarray + Upper-diagonal elements of the structure tensor for each pixel in the + input image. + + Examples + -------- + >>> from skimage.feature import structure_tensor + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 1 + >>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc') + >>> Acc + array([[0., 0., 0., 0., 0.], + [0., 1., 0., 1., 0.], + [0., 4., 0., 4., 0.], + [0., 1., 0., 1., 0.], + [0., 0., 0., 0., 0.]]) + + See also + -------- + structure_tensor_eigenvalues + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Structure_tensor + """ + if order == 'xy' and image.ndim > 2: + raise ValueError('Only "rc" order is supported for dim > 2.') + + if order not in ['rc', 'xy']: + raise ValueError(f'order {order} is invalid. Must be either "rc" or "xy"') + + if not np.isscalar(sigma): + sigma = tuple(sigma) + if len(sigma) != image.ndim: + raise ValueError('sigma must have as many elements as image ' 'has axes') + + image = _prepare_grayscale_input_nD(image) + + derivatives = _compute_derivatives(image, mode=mode, cval=cval) + + if order == 'xy': + derivatives = reversed(derivatives) + + # structure tensor + A_elems = [ + gaussian(der0 * der1, sigma=sigma, mode=mode, cval=cval) + for der0, der1 in combinations_with_replacement(derivatives, 2) + ] + + return A_elems + + +def _hessian_matrix_with_gaussian(image, sigma=1, mode='reflect', cval=0, order='rc'): + """Compute the Hessian via convolutions with Gaussian derivatives. + + In 2D, the Hessian matrix is defined as: + H = [Hrr Hrc] + [Hrc Hcc] + + which is computed by convolving the image with the second derivatives + of the Gaussian kernel in the respective r- and c-directions. + + The implementation here also supports n-dimensional data. + + Parameters + ---------- + image : ndarray + Input image. + sigma : float or sequence of float, optional + Standard deviation used for the Gaussian kernel, which sets the + amount of smoothing in terms of pixel-distances. It is + advised to not choose a sigma much less than 1.0, otherwise + aliasing artifacts may occur. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + This parameter allows for the use of reverse or forward order of + the image axes in gradient computation. 'rc' indicates the use of + the first axis initially (Hrr, Hrc, Hcc), whilst 'xy' indicates the + usage of the last axis initially (Hxx, Hxy, Hyy) + + Returns + ------- + H_elems : list of ndarray + Upper-diagonal elements of the hessian matrix for each pixel in the + input image. In 2D, this will be a three element list containing [Hrr, + Hrc, Hcc]. In nD, the list will contain ``(n**2 + n) / 2`` arrays. + + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim > 2 and order == "xy": + raise ValueError("order='xy' is only supported for 2D images.") + if order not in ["rc", "xy"]: + raise ValueError(f"unrecognized order: {order}") + + if np.isscalar(sigma): + sigma = (sigma,) * image.ndim + + # This function uses `scipy.ndimage.gaussian_filter` with the order + # argument to compute convolutions. For example, specifying + # ``order=[1, 0]`` would apply convolution with a first-order derivative of + # the Gaussian along the first axis and simple Gaussian smoothing along the + # second. + + # For small sigma, the SciPy Gaussian filter suffers from aliasing and edge + # artifacts, given that the filter will approximate a sinc or sinc + # derivative which only goes to 0 very slowly (order 1/n**2). Thus, we use + # a much larger truncate value to reduce any edge artifacts. + truncate = 8 if all(s > 1 for s in sigma) else 100 + sq1_2 = 1 / math.sqrt(2) + sigma_scaled = tuple(sq1_2 * s for s in sigma) + common_kwargs = dict(sigma=sigma_scaled, mode=mode, cval=cval, truncate=truncate) + gaussian_ = functools.partial(ndi.gaussian_filter, **common_kwargs) + + # Apply two successive first order Gaussian derivative operations, as + # detailed in: + # https://dsp.stackexchange.com/questions/78280/are-scipy-second-order-gaussian-derivatives-correct + + # 1.) First order along one axis while smoothing (order=0) along the other + ndim = image.ndim + + # orders in 2D = ([1, 0], [0, 1]) + # in 3D = ([1, 0, 0], [0, 1, 0], [0, 0, 1]) + # etc. + orders = tuple([0] * d + [1] + [0] * (ndim - d - 1) for d in range(ndim)) + gradients = [gaussian_(image, order=orders[d]) for d in range(ndim)] + + # 2.) apply the derivative along another axis as well + axes = range(ndim) + if order == 'xy': + axes = reversed(axes) + H_elems = [ + gaussian_(gradients[ax0], order=orders[ax1]) + for ax0, ax1 in combinations_with_replacement(axes, 2) + ] + return H_elems + + +def hessian_matrix( + image, sigma=1, mode='constant', cval=0, order='rc', use_gaussian_derivatives=None +): + r"""Compute the Hessian matrix. + + In 2D, the Hessian matrix is defined as:: + + H = [Hrr Hrc] + [Hrc Hcc] + + which is computed by convolving the image with the second derivatives + of the Gaussian kernel in the respective r- and c-directions. + + The implementation here also supports n-dimensional data. + + Parameters + ---------- + image : ndarray + Input image. + sigma : float + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + order : {'rc', 'xy'}, optional + For 2D images, this parameter allows for the use of reverse or forward + order of the image axes in gradient computation. 'rc' indicates the use + of the first axis initially (Hrr, Hrc, Hcc), whilst 'xy' indicates the + usage of the last axis initially (Hxx, Hxy, Hyy). Images with higher + dimension must always use 'rc' order. + use_gaussian_derivatives : bool, optional + Indicates whether the Hessian is computed by convolving with Gaussian + derivatives, or by a simple finite-difference operation. + + Returns + ------- + H_elems : list of ndarray + Upper-diagonal elements of the hessian matrix for each pixel in the + input image. In 2D, this will be a three element list containing [Hrr, + Hrc, Hcc]. In nD, the list will contain ``(n**2 + n) / 2`` arrays. + + + Notes + ----- + The distributive property of derivatives and convolutions allows us to + restate the derivative of an image, I, smoothed with a Gaussian kernel, G, + as the convolution of the image with the derivative of G. + + .. math:: + + \frac{\partial }{\partial x_i}(I * G) = + I * \left( \frac{\partial }{\partial x_i} G \right) + + When ``use_gaussian_derivatives`` is ``True``, this property is used to + compute the second order derivatives that make up the Hessian matrix. + + When ``use_gaussian_derivatives`` is ``False``, simple finite differences + on a Gaussian-smoothed image are used instead. + + Examples + -------- + >>> from skimage.feature import hessian_matrix + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> Hrr, Hrc, Hcc = hessian_matrix(square, sigma=0.1, order='rc', + ... use_gaussian_derivatives=False) + >>> Hrc + array([[ 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.]]) + + """ + + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim > 2 and order == "xy": + raise ValueError("order='xy' is only supported for 2D images.") + if order not in ["rc", "xy"]: + raise ValueError(f"unrecognized order: {order}") + + if use_gaussian_derivatives is None: + use_gaussian_derivatives = False + warn( + "use_gaussian_derivatives currently defaults to False, but will " + "change to True in a future version. Please specify this " + "argument explicitly to maintain the current behavior", + category=FutureWarning, + stacklevel=2, + ) + + if use_gaussian_derivatives: + return _hessian_matrix_with_gaussian( + image, sigma=sigma, mode=mode, cval=cval, order=order + ) + + gaussian_filtered = gaussian(image, sigma=sigma, mode=mode, cval=cval) + + gradients = np.gradient(gaussian_filtered) + axes = range(image.ndim) + + if order == 'xy': + axes = reversed(axes) + + H_elems = [ + np.gradient(gradients[ax0], axis=ax1) + for ax0, ax1 in combinations_with_replacement(axes, 2) + ] + return H_elems + + +def hessian_matrix_det(image, sigma=1, approximate=True): + """Compute the approximate Hessian Determinant over an image. + + The 2D approximate method uses box filters over integral images to + compute the approximate Hessian Determinant. + + Parameters + ---------- + image : ndarray + The image over which to compute the Hessian Determinant. + sigma : float, optional + Standard deviation of the Gaussian kernel used for the Hessian + matrix. + approximate : bool, optional + If ``True`` and the image is 2D, use a much faster approximate + computation. This argument has no effect on 3D and higher images. + + Returns + ------- + out : array + The array of the Determinant of Hessians. + + References + ---------- + .. [1] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, + "SURF: Speeded Up Robust Features" + ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf + + Notes + ----- + For 2D images when ``approximate=True``, the running time of this method + only depends on size of the image. It is independent of `sigma` as one + would expect. The downside is that the result for `sigma` less than `3` + is not accurate, i.e., not similar to the result obtained if someone + computed the Hessian and took its determinant. + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + if image.ndim == 2 and approximate: + integral = integral_image(image) + return np.array(_hessian_matrix_det(integral, sigma)) + else: # slower brute-force implementation for nD images + hessian_mat_array = _symmetric_image( + hessian_matrix(image, sigma, use_gaussian_derivatives=False) + ) + return np.linalg.det(hessian_mat_array) + + +def _symmetric_compute_eigenvalues(S_elems): + """Compute eigenvalues from the upper-diagonal entries of a symmetric + matrix. + + Parameters + ---------- + S_elems : list of ndarray + The upper-diagonal elements of the matrix, as returned by + `hessian_matrix` or `structure_tensor`. + + Returns + ------- + eigs : ndarray + The eigenvalues of the matrix, in decreasing order. The eigenvalues are + the leading dimension. That is, ``eigs[i, j, k]`` contains the + ith-largest eigenvalue at position (j, k). + """ + + if len(S_elems) == 3: # Fast explicit formulas for 2D. + M00, M01, M11 = S_elems + eigs = np.empty((2, *M00.shape), M00.dtype) + eigs[:] = (M00 + M11) / 2 + hsqrtdet = np.sqrt(M01**2 + ((M00 - M11) / 2) ** 2) + eigs[0] += hsqrtdet + eigs[1] -= hsqrtdet + return eigs + else: + matrices = _symmetric_image(S_elems) + # eigvalsh returns eigenvalues in increasing order. We want decreasing + eigs = np.linalg.eigvalsh(matrices)[..., ::-1] + leading_axes = tuple(range(eigs.ndim - 1)) + return np.transpose(eigs, (eigs.ndim - 1,) + leading_axes) + + +def _symmetric_image(S_elems): + """Convert the upper-diagonal elements of a matrix to the full + symmetric matrix. + + Parameters + ---------- + S_elems : list of array + The upper-diagonal elements of the matrix, as returned by + `hessian_matrix` or `structure_tensor`. + + Returns + ------- + image : array + An array of shape ``(M, N[, ...], image.ndim, image.ndim)``, + containing the matrix corresponding to each coordinate. + """ + image = S_elems[0] + symmetric_image = np.zeros( + image.shape + (image.ndim, image.ndim), dtype=S_elems[0].dtype + ) + for idx, (row, col) in enumerate( + combinations_with_replacement(range(image.ndim), 2) + ): + symmetric_image[..., row, col] = S_elems[idx] + symmetric_image[..., col, row] = S_elems[idx] + return symmetric_image + + +def structure_tensor_eigenvalues(A_elems): + """Compute eigenvalues of structure tensor. + + Parameters + ---------- + A_elems : list of ndarray + The upper-diagonal elements of the structure tensor, as returned + by `structure_tensor`. + + Returns + ------- + ndarray + The eigenvalues of the structure tensor, in decreasing order. The + eigenvalues are the leading dimension. That is, the coordinate + [i, j, k] corresponds to the ith-largest eigenvalue at position (j, k). + + Examples + -------- + >>> from skimage.feature import structure_tensor + >>> from skimage.feature import structure_tensor_eigenvalues + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 1 + >>> A_elems = structure_tensor(square, sigma=0.1, order='rc') + >>> structure_tensor_eigenvalues(A_elems)[0] + array([[0., 0., 0., 0., 0.], + [0., 2., 4., 2., 0.], + [0., 4., 0., 4., 0.], + [0., 2., 4., 2., 0.], + [0., 0., 0., 0., 0.]]) + + See also + -------- + structure_tensor + """ + return _symmetric_compute_eigenvalues(A_elems) + + +def hessian_matrix_eigvals(H_elems): + """Compute eigenvalues of Hessian matrix. + + Parameters + ---------- + H_elems : list of ndarray + The upper-diagonal elements of the Hessian matrix, as returned + by `hessian_matrix`. + + Returns + ------- + eigs : ndarray + The eigenvalues of the Hessian matrix, in decreasing order. The + eigenvalues are the leading dimension. That is, ``eigs[i, j, k]`` + contains the ith-largest eigenvalue at position (j, k). + + Examples + -------- + >>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> H_elems = hessian_matrix(square, sigma=0.1, order='rc', + ... use_gaussian_derivatives=False) + >>> hessian_matrix_eigvals(H_elems)[0] + array([[ 0., 0., 2., 0., 0.], + [ 0., 1., 0., 1., 0.], + [ 2., 0., -2., 0., 2.], + [ 0., 1., 0., 1., 0.], + [ 0., 0., 2., 0., 0.]]) + """ + return _symmetric_compute_eigenvalues(H_elems) + + +def shape_index(image, sigma=1, mode='constant', cval=0): + """Compute the shape index. + + The shape index, as defined by Koenderink & van Doorn [1]_, is a + single valued measure of local curvature, assuming the image as a 3D plane + with intensities representing heights. + + It is derived from the eigenvalues of the Hessian, and its + value ranges from -1 to 1 (and is undefined (=NaN) in *flat* regions), + with following ranges representing following shapes: + + .. table:: Ranges of the shape index and corresponding shapes. + + =================== ============= + Interval (s in ...) Shape + =================== ============= + [ -1, -7/8) Spherical cup + [-7/8, -5/8) Through + [-5/8, -3/8) Rut + [-3/8, -1/8) Saddle rut + [-1/8, +1/8) Saddle + [+1/8, +3/8) Saddle ridge + [+3/8, +5/8) Ridge + [+5/8, +7/8) Dome + [+7/8, +1] Spherical cap + =================== ============= + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used for + smoothing the input data before Hessian eigen value calculation. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + s : ndarray + Shape index + + References + ---------- + .. [1] Koenderink, J. J. & van Doorn, A. J., + "Surface shape and curvature scales", + Image and Vision Computing, 1992, 10, 557-564. + :DOI:`10.1016/0262-8856(92)90076-F` + + Examples + -------- + >>> from skimage.feature import shape_index + >>> square = np.zeros((5, 5)) + >>> square[2, 2] = 4 + >>> s = shape_index(square, sigma=0.1) + >>> s + array([[ nan, nan, -0.5, nan, nan], + [ nan, -0. , nan, -0. , nan], + [-0.5, nan, -1. , nan, -0.5], + [ nan, -0. , nan, -0. , nan], + [ nan, nan, -0.5, nan, nan]]) + """ + + H = hessian_matrix( + image, + sigma=sigma, + mode=mode, + cval=cval, + order='rc', + use_gaussian_derivatives=False, + ) + l1, l2 = hessian_matrix_eigvals(H) + + # don't warn on divide by 0 as occurs in the docstring example + with np.errstate(divide='ignore', invalid='ignore'): + return (2.0 / np.pi) * np.arctan((l2 + l1) / (l2 - l1)) + + +def corner_kitchen_rosenfeld(image, mode='constant', cval=0): + """Compute Kitchen and Rosenfeld corner measure response image. + + The corner measure is calculated as follows:: + + (imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy) + / (imx**2 + imy**2) + + Where imx and imy are the first and imxx, imxy, imyy the second + derivatives. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional + How to handle values outside the image borders. + cval : float, optional + Used in conjunction with mode 'constant', the value outside + the image boundaries. + + Returns + ------- + response : ndarray + Kitchen and Rosenfeld response image. + + References + ---------- + .. [1] Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection. + Pattern recognition letters, 1(2), 95-102. + :DOI:`10.1016/0167-8655(82)90020-4` + """ + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + imy, imx = _compute_derivatives(image, mode=mode, cval=cval) + imxy, imxx = _compute_derivatives(imx, mode=mode, cval=cval) + imyy, imyx = _compute_derivatives(imy, mode=mode, cval=cval) + + numerator = imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy + denominator = imx**2 + imy**2 + + response = np.zeros_like(image, dtype=float_dtype) + + mask = denominator != 0 + response[mask] = numerator[mask] / denominator[mask] + + return response + + +def corner_harris(image, method='k', k=0.05, eps=1e-6, sigma=1): + """Compute Harris corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as:: + + det(A) - k * trace(A)**2 + + or:: + + 2 * det(A) / (trace(A) + eps) + + Parameters + ---------- + image : (M, N) ndarray + Input image. + method : {'k', 'eps'}, optional + Method to compute the response image from the auto-correlation matrix. + k : float, optional + Sensitivity factor to separate corners from edges, typically in range + `[0, 0.2]`. Small values of k result in detection of sharp corners. + eps : float, optional + Normalisation factor (Noble's corner measure). + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + response : ndarray + Harris response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_harris, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.astype(int) + array([[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, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> corner_peaks(corner_harris(square), min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # determinant + detA = Arr * Acc - Arc**2 + # trace + traceA = Arr + Acc + + if method == 'k': + response = detA - k * traceA**2 + else: + response = 2 * detA / (traceA + eps) + + return response + + +def corner_shi_tomasi(image, sigma=1): + """Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as the smaller eigenvalue of A:: + + ((Axx + Ayy) - sqrt((Axx - Ayy)**2 + 4 * Axy**2)) / 2 + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + response : ndarray + Shi-Tomasi response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_shi_tomasi, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.astype(int) + array([[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, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> corner_peaks(corner_shi_tomasi(square), min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # minimum eigenvalue of A + response = ((Arr + Acc) - np.sqrt((Arr - Acc) ** 2 + 4 * Arc**2)) / 2 + + return response + + +def corner_foerstner(image, sigma=1): + """Compute Foerstner corner measure response image. + + This corner detector uses information from the auto-correlation matrix A:: + + A = [(imx**2) (imx*imy)] = [Axx Axy] + [(imx*imy) (imy**2)] [Axy Ayy] + + Where imx and imy are first derivatives, averaged with a gaussian filter. + The corner measure is then defined as:: + + w = det(A) / trace(A) (size of error ellipse) + q = 4 * det(A) / trace(A)**2 (roundness of error ellipse) + + Parameters + ---------- + image : (M, N) ndarray + Input image. + sigma : float, optional + Standard deviation used for the Gaussian kernel, which is used as + weighting function for the auto-correlation matrix. + + Returns + ------- + w : ndarray + Error ellipse sizes. + q : ndarray + Roundness of error ellipse. + + References + ---------- + .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for + detection and precise location of distinct points, corners and + centres of circular features. In Proc. ISPRS intercommission + conference on fast processing of photogrammetric data (pp. 281-305). + https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf + .. [2] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_foerstner, corner_peaks + >>> square = np.zeros([10, 10]) + >>> square[2:8, 2:8] = 1 + >>> square.astype(int) + array([[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, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 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]]) + >>> w, q = corner_foerstner(square) + >>> accuracy_thresh = 0.5 + >>> roundness_thresh = 0.3 + >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w + >>> corner_peaks(foerstner, min_distance=1) + array([[2, 2], + [2, 7], + [7, 2], + [7, 7]]) + + """ + + Arr, Arc, Acc = structure_tensor(image, sigma, order='rc') + + # determinant + detA = Arr * Acc - Arc**2 + # trace + traceA = Arr + Acc + + w = np.zeros_like(image, dtype=detA.dtype) + q = np.zeros_like(w) + + mask = traceA != 0 + + w[mask] = detA[mask] / traceA[mask] + q[mask] = 4 * detA[mask] / traceA[mask] ** 2 + + return w, q + + +def corner_fast(image, n=12, threshold=0.15): + """Extract FAST corners for a given image. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + n : int, optional + Minimum number of consecutive pixels out of 16 pixels on the circle + that should all be either brighter or darker w.r.t testpixel. + A point c on the circle is darker w.r.t test pixel p if + `Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also + stands for the n in `FAST-n` corner detector. + threshold : float, optional + Threshold used in deciding whether the pixels on the circle are + brighter, darker or similar w.r.t. the test pixel. Decrease the + threshold when more corners are desired and vice-versa. + + Returns + ------- + response : ndarray + FAST corner response image. + + References + ---------- + .. [1] Rosten, E., & Drummond, T. (2006, May). Machine learning for + high-speed corner detection. In European conference on computer + vision (pp. 430-443). Springer, Berlin, Heidelberg. + :DOI:`10.1007/11744023_34` + http://www.edwardrosten.com/work/rosten_2006_machine.pdf + .. [2] Wikipedia, "Features from accelerated segment test", + https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test + + Examples + -------- + >>> from skimage.feature import corner_fast, corner_peaks + >>> square = np.zeros((12, 12)) + >>> square[3:9, 3:9] = 1 + >>> square.astype(int) + 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, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 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, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> corner_peaks(corner_fast(square, 9), min_distance=1) + array([[3, 3], + [3, 8], + [8, 3], + [8, 8]]) + + """ + image = _prepare_grayscale_input_2D(image) + + image = np.ascontiguousarray(image) + response = _corner_fast(image, n, threshold) + return response + + +def corner_subpix(image, corners, window_size=11, alpha=0.99): + """Determine subpixel position of corners. + + A statistical test decides whether the corner is defined as the + intersection of two edges or a single peak. Depending on the classification + result, the subpixel corner location is determined based on the local + covariance of the grey-values. If the significance level for either + statistical test is not sufficient, the corner cannot be classified, and + the output subpixel position is set to NaN. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + corners : (K, 2) ndarray + Corner coordinates `(row, col)`. + window_size : int, optional + Search window size for subpixel estimation. + alpha : float, optional + Significance level for corner classification. + + Returns + ------- + positions : (K, 2) ndarray + Subpixel corner positions. NaN for "not classified" corners. + + References + ---------- + .. [1] Förstner, W., & Gülch, E. (1987, June). A fast operator for + detection and precise location of distinct points, corners and + centres of circular features. In Proc. ISPRS intercommission + conference on fast processing of photogrammetric data (pp. 281-305). + https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf + .. [2] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_harris, corner_peaks, corner_subpix + >>> img = np.zeros((10, 10)) + >>> img[:5, :5] = 1 + >>> img[5:, 5:] = 1 + >>> img.astype(int) + array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]) + >>> coords = corner_peaks(corner_harris(img), min_distance=2) + >>> coords_subpix = corner_subpix(img, coords, window_size=7) + >>> coords_subpix + array([[4.5, 4.5]]) + + """ + + # window extent in one direction + wext = (window_size - 1) // 2 + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + image = np.pad(image, pad_width=wext, mode='constant', constant_values=0) + + # add pad width, make sure to not modify the input values in-place + corners = safe_as_int(corners + wext) + + # normal equation arrays + N_dot = np.zeros((2, 2), dtype=float_dtype) + N_edge = np.zeros((2, 2), dtype=float_dtype) + b_dot = np.zeros((2,), dtype=float_dtype) + b_edge = np.zeros((2,), dtype=float_dtype) + + # critical statistical test values + redundancy = window_size**2 - 2 + t_crit_dot = stats.f.isf(1 - alpha, redundancy, redundancy) + t_crit_edge = stats.f.isf(alpha, redundancy, redundancy) + + # coordinates of pixels within window + y, x = np.mgrid[-wext : wext + 1, -wext : wext + 1] + + corners_subpix = np.zeros_like(corners, dtype=float_dtype) + + for i, (y0, x0) in enumerate(corners): + # crop window around corner + border for sobel operator + miny = y0 - wext - 1 + maxy = y0 + wext + 2 + minx = x0 - wext - 1 + maxx = x0 + wext + 2 + window = image[miny:maxy, minx:maxx] + + winy, winx = _compute_derivatives(window, mode='constant', cval=0) + + # compute gradient squares and remove border + winx_winx = (winx * winx)[1:-1, 1:-1] + winx_winy = (winx * winy)[1:-1, 1:-1] + winy_winy = (winy * winy)[1:-1, 1:-1] + + # sum of squared differences (mean instead of gaussian filter) + Axx = np.sum(winx_winx) + Axy = np.sum(winx_winy) + Ayy = np.sum(winy_winy) + + # sum of squared differences weighted with coordinates + # (mean instead of gaussian filter) + bxx_x = np.sum(winx_winx * x) + bxx_y = np.sum(winx_winx * y) + bxy_x = np.sum(winx_winy * x) + bxy_y = np.sum(winx_winy * y) + byy_x = np.sum(winy_winy * x) + byy_y = np.sum(winy_winy * y) + + # normal equations for subpixel position + N_dot[0, 0] = Axx + N_dot[0, 1] = N_dot[1, 0] = -Axy + N_dot[1, 1] = Ayy + + N_edge[0, 0] = Ayy + N_edge[0, 1] = N_edge[1, 0] = Axy + N_edge[1, 1] = Axx + + b_dot[:] = bxx_y - bxy_x, byy_x - bxy_y + b_edge[:] = byy_y + bxy_x, bxx_x + bxy_y + + # estimated positions + try: + est_dot = np.linalg.solve(N_dot, b_dot) + est_edge = np.linalg.solve(N_edge, b_edge) + except np.linalg.LinAlgError: + # if image is constant the system is singular + corners_subpix[i, :] = np.nan, np.nan + continue + + # residuals + ry_dot = y - est_dot[0] + rx_dot = x - est_dot[1] + ry_edge = y - est_edge[0] + rx_edge = x - est_edge[1] + # squared residuals + rxx_dot = rx_dot * rx_dot + rxy_dot = rx_dot * ry_dot + ryy_dot = ry_dot * ry_dot + rxx_edge = rx_edge * rx_edge + rxy_edge = rx_edge * ry_edge + ryy_edge = ry_edge * ry_edge + + # determine corner class (dot or edge) + # variance for different models + var_dot = np.sum( + winx_winx * ryy_dot - 2 * winx_winy * rxy_dot + winy_winy * rxx_dot + ) + var_edge = np.sum( + winy_winy * ryy_edge + 2 * winx_winy * rxy_edge + winx_winx * rxx_edge + ) + + # test value (F-distributed) + if var_dot < np.spacing(1) and var_edge < np.spacing(1): + t = np.nan + elif var_dot == 0: + t = np.inf + else: + t = var_edge / var_dot + + # 1 for edge, -1 for dot, 0 for "not classified" + corner_class = int(t < t_crit_edge) - int(t > t_crit_dot) + + if corner_class == -1: + corners_subpix[i, :] = y0 + est_dot[0], x0 + est_dot[1] + elif corner_class == 0: + corners_subpix[i, :] = np.nan, np.nan + elif corner_class == 1: + corners_subpix[i, :] = y0 + est_edge[0], x0 + est_edge[1] + + # subtract pad width + corners_subpix -= wext + + return corners_subpix + + +def corner_peaks( + image, + min_distance=1, + threshold_abs=None, + threshold_rel=None, + exclude_border=True, + indices=True, + num_peaks=np.inf, + footprint=None, + labels=None, + *, + num_peaks_per_label=np.inf, + p_norm=np.inf, +): + """Find peaks in corner measure response image. + + This differs from `skimage.feature.peak_local_max` in that it suppresses + multiple connected peaks with the same accumulator value. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + min_distance : int, optional + The minimal allowed distance separating peaks. + * : * + See :py:meth:`skimage.feature.peak_local_max`. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + + Returns + ------- + output : ndarray or ndarray of bools + + * If `indices = True` : (row, column, ...) coordinates of peaks. + * If `indices = False` : Boolean array shaped like `image`, with peaks + represented by True values. + + See also + -------- + skimage.feature.peak_local_max + + Notes + ----- + .. versionchanged:: 0.18 + The default value of `threshold_rel` has changed to None, which + corresponds to letting `skimage.feature.peak_local_max` decide on the + default. This is equivalent to `threshold_rel=0`. + + The `num_peaks` limit is applied before suppression of connected peaks. + To limit the number of peaks after suppression, set `num_peaks=np.inf` and + post-process the output of this function. + + Examples + -------- + >>> from skimage.feature import peak_local_max + >>> response = np.zeros((5, 5)) + >>> response[2:4, 2:4] = 1 + >>> response + array([[0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0.], + [0., 0., 1., 1., 0.], + [0., 0., 1., 1., 0.], + [0., 0., 0., 0., 0.]]) + >>> peak_local_max(response) + array([[2, 2], + [2, 3], + [3, 2], + [3, 3]]) + >>> corner_peaks(response) + array([[2, 2]]) + + """ + if np.isinf(num_peaks): + num_peaks = None + + # Get the coordinates of the detected peaks + coords = peak_local_max( + image, + min_distance=min_distance, + threshold_abs=threshold_abs, + threshold_rel=threshold_rel, + exclude_border=exclude_border, + num_peaks=np.inf, + footprint=footprint, + labels=labels, + num_peaks_per_label=num_peaks_per_label, + ) + + if len(coords): + # Use KDtree to find the peaks that are too close to each other + tree = spatial.cKDTree(coords) + + rejected_peaks_indices = set() + for idx, point in enumerate(coords): + if idx not in rejected_peaks_indices: + candidates = tree.query_ball_point(point, r=min_distance, p=p_norm) + candidates.remove(idx) + rejected_peaks_indices.update(candidates) + + # Remove the peaks that are too close to each other + coords = np.delete(coords, tuple(rejected_peaks_indices), axis=0)[:num_peaks] + + if indices: + return coords + + peaks = np.zeros_like(image, dtype=bool) + peaks[tuple(coords.T)] = True + + return peaks + + +def corner_moravec(image, window_size=1): + """Compute Moravec corner measure response image. + + This is one of the simplest corner detectors and is comparatively fast but + has several limitations (e.g. not rotation invariant). + + Parameters + ---------- + image : (M, N) ndarray + Input image. + window_size : int, optional + Window size. + + Returns + ------- + response : ndarray + Moravec response image. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Corner_detection + + Examples + -------- + >>> from skimage.feature import corner_moravec + >>> square = np.zeros([7, 7]) + >>> square[3, 3] = 1 + >>> square.astype(int) + 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, 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]]) + >>> corner_moravec(square).astype(int) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 2, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + """ + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + return _corner_moravec(np.ascontiguousarray(image), window_size) + + +def corner_orientations(image, corners, mask): + """Compute the orientation of corners. + + The orientation of corners is computed using the first order central moment + i.e. the center of mass approach. The corner orientation is the angle of + the vector from the corner coordinate to the intensity centroid in the + local neighborhood around the corner calculated using first order central + moment. + + Parameters + ---------- + image : (M, N) array + Input grayscale image. + corners : (K, 2) array + Corner coordinates as ``(row, col)``. + mask : 2D array + Mask defining the local neighborhood of the corner used for the + calculation of the central moment. + + Returns + ------- + orientations : (K, 1) array + Orientations of corners in the range [-pi, pi]. + + References + ---------- + .. [1] Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski + "ORB : An efficient alternative to SIFT and SURF" + http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf + .. [2] Paul L. Rosin, "Measuring Corner Properties" + http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf + + Examples + -------- + >>> from skimage.morphology import octagon + >>> from skimage.feature import (corner_fast, corner_peaks, + ... corner_orientations) + >>> square = np.zeros((12, 12)) + >>> square[3:9, 3:9] = 1 + >>> square.astype(int) + 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, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 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, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> corners = corner_peaks(corner_fast(square, 9), min_distance=1) + >>> corners + array([[3, 3], + [3, 8], + [8, 3], + [8, 8]]) + >>> orientations = corner_orientations(square, corners, octagon(3, 2)) + >>> np.rad2deg(orientations) + array([ 45., 135., -45., -135.]) + + """ + image = _prepare_grayscale_input_2D(image) + return _corner_orientations(image, corners, mask) diff --git a/envs/kitoverlay/skimage/feature/haar.py b/envs/kitoverlay/skimage/feature/haar.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdc4078da91e90c0e5a53b1233f3e2c5003d1ba --- /dev/null +++ b/envs/kitoverlay/skimage/feature/haar.py @@ -0,0 +1,339 @@ +from itertools import chain +from operator import add + +import numpy as np + +from ._haar import haar_like_feature_coord_wrapper +from ._haar import haar_like_feature_wrapper +from ..color import gray2rgb +from ..draw import rectangle +from ..util import img_as_float + +FEATURE_TYPE = ('type-2-x', 'type-2-y', 'type-3-x', 'type-3-y', 'type-4') + + +def _validate_feature_type(feature_type): + """Transform feature type to an iterable and check that it exists.""" + if feature_type is None: + feature_type_ = FEATURE_TYPE + else: + if isinstance(feature_type, str): + feature_type_ = [feature_type] + else: + feature_type_ = feature_type + for feat_t in feature_type_: + if feat_t not in FEATURE_TYPE: + raise ValueError( + f'The given feature type is unknown. Got {feat_t} instead of one ' + f'of {FEATURE_TYPE}.' + ) + return feature_type_ + + +def haar_like_feature_coord(width, height, feature_type=None): + """Compute the coordinates of Haar-like features. + + Parameters + ---------- + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_type : str or list of str or None, optional + The type of feature to consider: + + - 'type-2-x': 2 rectangles varying along the x axis; + - 'type-2-y': 2 rectangles varying along the y axis; + - 'type-3-x': 3 rectangles varying along the x axis; + - 'type-3-y': 3 rectangles varying along the y axis; + - 'type-4': 4 rectangles varying along x and y axis. + + By default all features are extracted. + + Returns + ------- + feature_coord : (n_features, n_rectangles, 2, 2), ndarray of list of \ +tuple coord + Coordinates of the rectangles for each feature. + feature_type : (n_features,), ndarray of str + The corresponding type for each feature. + + Examples + -------- + >>> import numpy as np + >>> from skimage.transform import integral_image + >>> from skimage.feature import haar_like_feature_coord + >>> feat_coord, feat_type = haar_like_feature_coord(2, 2, 'type-4') + >>> feat_coord # doctest: +SKIP + array([ list([[(0, 0), (0, 0)], [(0, 1), (0, 1)], + [(1, 1), (1, 1)], [(1, 0), (1, 0)]])], dtype=object) + >>> feat_type + array(['type-4'], dtype=object) + + """ + feature_type_ = _validate_feature_type(feature_type) + + feat_coord, feat_type = zip( + *[ + haar_like_feature_coord_wrapper(width, height, feat_t) + for feat_t in feature_type_ + ] + ) + + return np.concatenate(feat_coord), np.hstack(feat_type) + + +def haar_like_feature( + int_image, r, c, width, height, feature_type=None, feature_coord=None +): + """Compute the Haar-like features for a region of interest (ROI) of an + integral image. + + Haar-like features have been successfully used for image classification and + object detection [1]_. It has been used for real-time face detection + algorithm proposed in [2]_. + + Parameters + ---------- + int_image : (M, N) ndarray + Integral image for which the features need to be computed. + r : int + Row-coordinate of top left corner of the detection window. + c : int + Column-coordinate of top left corner of the detection window. + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_type : str or list of str or None, optional + The type of feature to consider: + + - 'type-2-x': 2 rectangles varying along the x axis; + - 'type-2-y': 2 rectangles varying along the y axis; + - 'type-3-x': 3 rectangles varying along the x axis; + - 'type-3-y': 3 rectangles varying along the y axis; + - 'type-4': 4 rectangles varying along x and y axis. + + By default all features are extracted. + + If using with `feature_coord`, it should correspond to the feature + type of each associated coordinate feature. + feature_coord : ndarray of list of tuples or None, optional + The array of coordinates to be extracted. This is useful when you want + to recompute only a subset of features. In this case `feature_type` + needs to be an array containing the type of each feature, as returned + by :func:`haar_like_feature_coord`. By default, all coordinates are + computed. + + Returns + ------- + haar_features : (n_features,) ndarray of int or float + Resulting Haar-like features. Each value is equal to the subtraction of + sums of the positive and negative rectangles. The data type depends of + the data type of `int_image`: `int` when the data type of `int_image` + is `uint` or `int` and `float` when the data type of `int_image` is + `float`. + + Notes + ----- + When extracting those features in parallel, be aware that the choice of the + backend (i.e. multiprocessing vs threading) will have an impact on the + performance. The rule of thumb is as follows: use multiprocessing when + extracting features for all possible ROI in an image; use threading when + extracting the feature at specific location for a limited number of ROIs. + Refer to the example + :ref:`sphx_glr_auto_examples_applications_plot_haar_extraction_selection_classification.py` + for more insights. + + Examples + -------- + >>> import numpy as np + >>> from skimage.transform import integral_image + >>> from skimage.feature import haar_like_feature + >>> img = np.ones((5, 5), dtype=np.uint8) + >>> img_ii = integral_image(img) + >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-x') + >>> feature + array([-1, -2, -3, -4, -5, -1, -2, -3, -4, -5, -1, -2, -3, -4, -5, -1, -2, + -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -1, -2, -3, -1, + -2, -3, -1, -2, -1, -2, -1, -2, -1, -1, -1]) + + You can compute the feature for some pre-computed coordinates. + + >>> from skimage.feature import haar_like_feature_coord + >>> feature_coord, feature_type = zip( + ... *[haar_like_feature_coord(5, 5, feat_t) + ... for feat_t in ('type-2-x', 'type-3-x')]) + >>> # only select one feature over two + >>> feature_coord = np.concatenate([x[::2] for x in feature_coord]) + >>> feature_type = np.concatenate([x[::2] for x in feature_type]) + >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, + ... feature_type=feature_type, + ... feature_coord=feature_coord) + >>> feature + 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, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -3, -5, -2, -4, -1, + -3, -5, -2, -4, -2, -4, -2, -4, -2, -1, -3, -2, -1, -1, -1, -1, -1]) + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Haar-like_feature + .. [2] Oren, M., Papageorgiou, C., Sinha, P., Osuna, E., & Poggio, T. + (1997, June). Pedestrian detection using wavelet templates. + In Computer Vision and Pattern Recognition, 1997. Proceedings., + 1997 IEEE Computer Society Conference on (pp. 193-199). IEEE. + http://tinyurl.com/y6ulxfta + :DOI:`10.1109/CVPR.1997.609319` + .. [3] Viola, Paul, and Michael J. Jones. "Robust real-time face + detection." International journal of computer vision 57.2 + (2004): 137-154. + https://www.merl.com/publications/docs/TR2004-043.pdf + :DOI:`10.1109/CVPR.2001.990517` + + """ + if feature_coord is None: + feature_type_ = _validate_feature_type(feature_type) + + return np.hstack( + list( + chain.from_iterable( + haar_like_feature_wrapper( + int_image, r, c, width, height, feat_t, feature_coord + ) + for feat_t in feature_type_ + ) + ) + ) + else: + if feature_coord.shape[0] != feature_type.shape[0]: + raise ValueError( + "Inconsistent size between feature coordinates" "and feature types." + ) + + mask_feature = [feature_type == feat_t for feat_t in FEATURE_TYPE] + haar_feature_idx, haar_feature = zip( + *[ + ( + np.flatnonzero(mask), + haar_like_feature_wrapper( + int_image, r, c, width, height, feat_t, feature_coord[mask] + ), + ) + for mask, feat_t in zip(mask_feature, FEATURE_TYPE) + if np.count_nonzero(mask) + ] + ) + + haar_feature_idx = np.concatenate(haar_feature_idx) + haar_feature = np.concatenate(haar_feature) + + haar_feature[haar_feature_idx] = haar_feature.copy() + return haar_feature + + +def draw_haar_like_feature( + image, + r, + c, + width, + height, + feature_coord, + color_positive_block=(1.0, 0.0, 0.0), + color_negative_block=(0.0, 1.0, 0.0), + alpha=0.5, + max_n_features=None, + rng=None, +): + """Visualization of Haar-like features. + + Parameters + ---------- + image : (M, N) ndarray + The region of an integral image for which the features need to be + computed. + r : int + Row-coordinate of top left corner of the detection window. + c : int + Column-coordinate of top left corner of the detection window. + width : int + Width of the detection window. + height : int + Height of the detection window. + feature_coord : ndarray of list of tuples or None, optional + The array of coordinates to be extracted. This is useful when you want + to recompute only a subset of features. In this case `feature_type` + needs to be an array containing the type of each feature, as returned + by :func:`haar_like_feature_coord`. By default, all coordinates are + computed. + color_positive_block : tuple of 3 floats + Floats specifying the color for the positive block. Corresponding + values define (R, G, B) values. Default value is red (1, 0, 0). + color_negative_block : tuple of 3 floats + Floats specifying the color for the negative block Corresponding values + define (R, G, B) values. Default value is blue (0, 1, 0). + alpha : float + Value in the range [0, 1] that specifies opacity of visualization. 1 - + fully transparent, 0 - opaque. + max_n_features : int, default=None + The maximum number of features to be returned. + By default, all features are returned. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The rng is used when generating a set of features smaller than + the total number of available features. + + Returns + ------- + features : (M, N), ndarray + An image in which the different features will be added. + + Examples + -------- + >>> import numpy as np + >>> from skimage.feature import haar_like_feature_coord + >>> from skimage.feature import draw_haar_like_feature + >>> feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4') + >>> image = draw_haar_like_feature(np.zeros((2, 2)), + ... 0, 0, 2, 2, + ... feature_coord, + ... max_n_features=1) + >>> image + array([[[0. , 0.5, 0. ], + [0.5, 0. , 0. ]], + + [[0.5, 0. , 0. ], + [0. , 0.5, 0. ]]]) + + """ + rng = np.random.default_rng(rng) + color_positive_block = np.asarray(color_positive_block, dtype=np.float64) + color_negative_block = np.asarray(color_negative_block, dtype=np.float64) + + if max_n_features is None: + feature_coord_ = feature_coord + else: + feature_coord_ = rng.choice(feature_coord, size=max_n_features, replace=False) + + output = np.copy(image) + if len(image.shape) < 3: + output = gray2rgb(image) + output = img_as_float(output) + + for coord in feature_coord_: + for idx_rect, rect in enumerate(coord): + coord_start, coord_end = rect + coord_start = tuple(map(add, coord_start, [r, c])) + coord_end = tuple(map(add, coord_end, [r, c])) + rr, cc = rectangle(coord_start, coord_end) + + if ((idx_rect + 1) % 2) == 0: + new_value = (1 - alpha) * output[rr, cc] + alpha * color_positive_block + else: + new_value = (1 - alpha) * output[rr, cc] + alpha * color_negative_block + output[rr, cc] = new_value + + return output diff --git a/envs/kitoverlay/skimage/feature/match.py b/envs/kitoverlay/skimage/feature/match.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c429170156e939e6ecd34e56c6ea6b2c0ee897 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/match.py @@ -0,0 +1,103 @@ +import numpy as np +from scipy.spatial.distance import cdist + + +def match_descriptors( + descriptors1, + descriptors2, + metric=None, + p=2, + max_distance=np.inf, + cross_check=True, + max_ratio=1.0, +): + """Brute-force matching of descriptors. + + For each descriptor in the first set this matcher finds the closest + descriptor in the second set (and vice-versa in the case of enabled + cross-checking). + + Parameters + ---------- + descriptors1 : (M, P) array + Descriptors of size P about M keypoints in the first image. + descriptors2 : (N, P) array + Descriptors of size P about N keypoints in the second image. + metric : {'euclidean', 'cityblock', 'minkowski', 'hamming', ...} , optional + The metric to compute the distance between two descriptors. See + `scipy.spatial.distance.cdist` for all possible types. The hamming + distance should be used for binary descriptors. By default the L2-norm + is used for all descriptors of dtype float or double and the Hamming + distance is used for binary descriptors automatically. + p : int, optional + The p-norm to apply for ``metric='minkowski'``. + max_distance : float, optional + Maximum allowed distance between descriptors of two keypoints + in separate images to be regarded as a match. + cross_check : bool, optional + If True, the matched keypoints are returned after cross checking i.e. a + matched pair (keypoint1, keypoint2) is returned if keypoint2 is the + best match for keypoint1 in second image and keypoint1 is the best + match for keypoint2 in first image. + max_ratio : float, optional + Maximum ratio of distances between first and second closest descriptor + in the second set of descriptors. This threshold is useful to filter + ambiguous matches between the two descriptor sets. The choice of this + value depends on the statistics of the chosen descriptor, e.g., + for SIFT descriptors a value of 0.8 is usually chosen, see + D.G. Lowe, "Distinctive Image Features from Scale-Invariant Keypoints", + International Journal of Computer Vision, 2004. + + Returns + ------- + matches : (Q, 2) array + Indices of corresponding matches in first and second set of + descriptors, where ``matches[:, 0]`` denote the indices in the first + and ``matches[:, 1]`` the indices in the second set of descriptors. + + """ + + if descriptors1.shape[1] != descriptors2.shape[1]: + raise ValueError("Descriptor length must equal.") + + if metric is None: + if np.issubdtype(descriptors1.dtype, bool): + metric = 'hamming' + else: + metric = 'euclidean' + + kwargs = {} + # Scipy raises an error if p is passed as an extra argument when it isn't + # necessary for the chosen metric. + if metric == 'minkowski': + kwargs['p'] = p + distances = cdist(descriptors1, descriptors2, metric=metric, **kwargs) + + indices1 = np.arange(descriptors1.shape[0]) + indices2 = np.argmin(distances, axis=1) + + if cross_check: + matches1 = np.argmin(distances, axis=0) + mask = indices1 == matches1[indices2] + indices1 = indices1[mask] + indices2 = indices2[mask] + + if max_distance < np.inf: + mask = distances[indices1, indices2] < max_distance + indices1 = indices1[mask] + indices2 = indices2[mask] + + if max_ratio < 1.0: + best_distances = distances[indices1, indices2] + distances[indices1, indices2] = np.inf + second_best_indices2 = np.argmin(distances[indices1], axis=1) + second_best_distances = distances[indices1, second_best_indices2] + second_best_distances[second_best_distances == 0] = np.finfo(np.float64).eps + ratio = best_distances / second_best_distances + mask = ratio < max_ratio + indices1 = indices1[mask] + indices2 = indices2[mask] + + matches = np.column_stack((indices1, indices2)) + + return matches diff --git a/envs/kitoverlay/skimage/feature/orb.py b/envs/kitoverlay/skimage/feature/orb.py new file mode 100644 index 0000000000000000000000000000000000000000..c9fa5f23bc222eb0da9d660134ded0b1b7a7695b --- /dev/null +++ b/envs/kitoverlay/skimage/feature/orb.py @@ -0,0 +1,366 @@ +import numpy as np + +from ..feature.util import ( + FeatureDetector, + DescriptorExtractor, + _mask_border_keypoints, + _prepare_grayscale_input_2D, +) + +from .corner import corner_fast, corner_orientations, corner_peaks, corner_harris +from ..transform import pyramid_gaussian +from .._shared.utils import check_nD +from .._shared.compat import NP_COPY_IF_NEEDED + +from .orb_cy import _orb_loop + + +OFAST_MASK = np.zeros((31, 31)) +OFAST_UMAX = [15, 15, 15, 15, 14, 14, 14, 13, 13, 12, 11, 10, 9, 8, 6, 3] +for i in range(-15, 16): + for j in range(-OFAST_UMAX[abs(i)], OFAST_UMAX[abs(i)] + 1): + OFAST_MASK[15 + j, 15 + i] = 1 + + +class ORB(FeatureDetector, DescriptorExtractor): + """Oriented FAST and rotated BRIEF feature detector and binary descriptor + extractor. + + Parameters + ---------- + n_keypoints : int, optional + Number of keypoints to be returned. The function will return the best + `n_keypoints` according to the Harris corner response if more than + `n_keypoints` are detected. If not, then all the detected keypoints + are returned. + fast_n : int, optional + The `n` parameter in `skimage.feature.corner_fast`. Minimum number of + consecutive pixels out of 16 pixels on the circle that should all be + either brighter or darker w.r.t test-pixel. A point c on the circle is + darker w.r.t test pixel p if ``Ic < Ip - threshold`` and brighter if + ``Ic > Ip + threshold``. Also stands for the n in ``FAST-n`` corner + detector. + fast_threshold : float, optional + The ``threshold`` parameter in ``feature.corner_fast``. Threshold used + to decide whether the pixels on the circle are brighter, darker or + similar w.r.t. the test pixel. Decrease the threshold when more + corners are desired and vice-versa. + harris_k : float, optional + The `k` parameter in `skimage.feature.corner_harris`. Sensitivity + factor to separate corners from edges, typically in range ``[0, 0.2]``. + Small values of `k` result in detection of sharp corners. + downscale : float, optional + Downscale factor for the image pyramid. Default value 1.2 is chosen so + that there are more dense scales which enable robust scale invariance + for a subsequent feature description. + n_scales : int, optional + Maximum number of scales from the bottom of the image pyramid to + extract the features from. + + Attributes + ---------- + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + orientations : (N,) array + Corresponding orientations in radians. + responses : (N,) array + Corresponding Harris corner responses. + descriptors : (Q, `descriptor_size`) array of dtype bool + 2D array of binary descriptors of size `descriptor_size` for Q + keypoints after filtering out border keypoints with value at an + index ``(i, j)`` either being ``True`` or ``False`` representing + the outcome of the intensity comparison for i-th keypoint on j-th + decision pixel-pair. It is ``Q == np.sum(mask)``. + + References + ---------- + .. [1] Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski + "ORB: An efficient alternative to SIFT and SURF" + http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf + + Examples + -------- + >>> from skimage.feature import ORB, match_descriptors + >>> img1 = np.zeros((100, 100)) + >>> img2 = np.zeros_like(img1) + >>> rng = np.random.default_rng(19481137) # do not copy this value + >>> square = rng.random((20, 20)) + >>> img1[40:60, 40:60] = square + >>> img2[53:73, 53:73] = square + >>> detector_extractor1 = ORB(n_keypoints=5) + >>> detector_extractor2 = ORB(n_keypoints=5) + >>> detector_extractor1.detect_and_extract(img1) + >>> detector_extractor2.detect_and_extract(img2) + >>> matches = match_descriptors(detector_extractor1.descriptors, + ... detector_extractor2.descriptors) + >>> matches + array([[0, 0], + [1, 1], + [2, 2], + [3, 4], + [4, 3]]) + >>> detector_extractor1.keypoints[matches[:, 0]] + array([[59. , 59. ], + [40. , 40. ], + [57. , 40. ], + [46. , 58. ], + [58.8, 58.8]]) + >>> detector_extractor2.keypoints[matches[:, 1]] + array([[72., 72.], + [53., 53.], + [70., 53.], + [59., 71.], + [72., 72.]]) + + """ + + def __init__( + self, + downscale=1.2, + n_scales=8, + n_keypoints=500, + fast_n=9, + fast_threshold=0.08, + harris_k=0.04, + ): + self.downscale = downscale + self.n_scales = n_scales + self.n_keypoints = n_keypoints + self.fast_n = fast_n + self.fast_threshold = fast_threshold + self.harris_k = harris_k + + self.keypoints = None + self.scales = None + self.responses = None + self.orientations = None + self.descriptors = None + + def _build_pyramid(self, image): + image = _prepare_grayscale_input_2D(image) + return list( + pyramid_gaussian( + image, self.n_scales - 1, self.downscale, channel_axis=None + ) + ) + + def _detect_octave(self, octave_image): + dtype = octave_image.dtype + # Extract keypoints for current octave + fast_response = corner_fast(octave_image, self.fast_n, self.fast_threshold) + keypoints = corner_peaks(fast_response, min_distance=1) + + if len(keypoints) == 0: + return ( + np.zeros((0, 2), dtype=dtype), + np.zeros((0,), dtype=dtype), + np.zeros((0,), dtype=dtype), + ) + + mask = _mask_border_keypoints(octave_image.shape, keypoints, distance=16) + keypoints = keypoints[mask] + + orientations = corner_orientations(octave_image, keypoints, OFAST_MASK) + + harris_response = corner_harris(octave_image, method='k', k=self.harris_k) + responses = harris_response[keypoints[:, 0], keypoints[:, 1]] + + return keypoints, orientations, responses + + def detect(self, image): + """Detect oriented FAST keypoints along with the corresponding scale. + + Parameters + ---------- + image : 2D array + Input image. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + keypoints_list = [] + orientations_list = [] + scales_list = [] + responses_list = [] + + for octave in range(len(pyramid)): + octave_image = np.ascontiguousarray(pyramid[octave]) + + if np.squeeze(octave_image).ndim < 2: + # No further keypoints can be detected if the image is not really 2d + break + + keypoints, orientations, responses = self._detect_octave(octave_image) + + keypoints_list.append(keypoints * self.downscale**octave) + orientations_list.append(orientations) + scales_list.append( + np.full( + keypoints.shape[0], + self.downscale**octave, + dtype=octave_image.dtype, + ) + ) + responses_list.append(responses) + + keypoints = np.vstack(keypoints_list) + orientations = np.hstack(orientations_list) + scales = np.hstack(scales_list) + responses = np.hstack(responses_list) + + if keypoints.shape[0] < self.n_keypoints: + self.keypoints = keypoints + self.scales = scales + self.orientations = orientations + self.responses = responses + else: + # Choose best n_keypoints according to Harris corner response + best_indices = responses.argsort()[::-1][: self.n_keypoints] + self.keypoints = keypoints[best_indices] + self.scales = scales[best_indices] + self.orientations = orientations[best_indices] + self.responses = responses[best_indices] + + def _extract_octave(self, octave_image, keypoints, orientations): + mask = _mask_border_keypoints(octave_image.shape, keypoints, distance=20) + keypoints = np.array( + keypoints[mask], dtype=np.intp, order='C', copy=NP_COPY_IF_NEEDED + ) + orientations = np.array(orientations[mask], order='C', copy=False) + + descriptors = _orb_loop(octave_image, keypoints, orientations) + + return descriptors, mask + + def extract(self, image, keypoints, scales, orientations): + """Extract rBRIEF binary descriptors for given keypoints in image. + + Note that the keypoints must be extracted using the same `downscale` + and `n_scales` parameters. Additionally, if you want to extract both + keypoints and descriptors you should use the faster + `detect_and_extract`. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + scales : (N,) array + Corresponding scales. + orientations : (N,) array + Corresponding orientations in radians. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + descriptors_list = [] + mask_list = [] + + # Determine octaves from scales + octaves = (np.log(scales) / np.log(self.downscale)).astype(np.intp) + + for octave in range(len(pyramid)): + # Mask for all keypoints in current octave + octave_mask = octaves == octave + + if np.sum(octave_mask) > 0: + octave_image = np.ascontiguousarray(pyramid[octave]) + + octave_keypoints = keypoints[octave_mask] + octave_keypoints /= self.downscale**octave + octave_orientations = orientations[octave_mask] + + descriptors, mask = self._extract_octave( + octave_image, octave_keypoints, octave_orientations + ) + + descriptors_list.append(descriptors) + mask_list.append(mask) + + self.descriptors = np.vstack(descriptors_list).view(bool) + self.mask_ = np.hstack(mask_list) + + def detect_and_extract(self, image): + """Detect oriented FAST keypoints and extract rBRIEF descriptors. + + Note that this is faster than first calling `detect` and then + `extract`. + + Parameters + ---------- + image : 2D array + Input image. + + """ + check_nD(image, 2) + + pyramid = self._build_pyramid(image) + + keypoints_list = [] + responses_list = [] + scales_list = [] + orientations_list = [] + descriptors_list = [] + + for octave in range(len(pyramid)): + octave_image = np.ascontiguousarray(pyramid[octave]) + + if np.squeeze(octave_image).ndim < 2: + # No further keypoints can be detected if the image is not really 2d + break + + keypoints, orientations, responses = self._detect_octave(octave_image) + + if len(keypoints) == 0: + keypoints_list.append(keypoints) + responses_list.append(responses) + descriptors_list.append(np.zeros((0, 256), dtype=bool)) + continue + + descriptors, mask = self._extract_octave( + octave_image, keypoints, orientations + ) + + scaled_keypoints = keypoints[mask] * self.downscale**octave + keypoints_list.append(scaled_keypoints) + responses_list.append(responses[mask]) + orientations_list.append(orientations[mask]) + scales_list.append( + self.downscale**octave + * np.ones(scaled_keypoints.shape[0], dtype=np.intp) + ) + descriptors_list.append(descriptors) + + if len(scales_list) == 0: + raise RuntimeError( + "ORB found no features. Try passing in an image containing " + "greater intensity contrasts between adjacent pixels." + ) + + keypoints = np.vstack(keypoints_list) + responses = np.hstack(responses_list) + scales = np.hstack(scales_list) + orientations = np.hstack(orientations_list) + descriptors = np.vstack(descriptors_list).view(bool) + + if keypoints.shape[0] < self.n_keypoints: + self.keypoints = keypoints + self.scales = scales + self.orientations = orientations + self.responses = responses + self.descriptors = descriptors + else: + # Choose best n_keypoints according to Harris corner response + best_indices = responses.argsort()[::-1][: self.n_keypoints] + self.keypoints = keypoints[best_indices] + self.scales = scales[best_indices] + self.orientations = orientations[best_indices] + self.responses = responses[best_indices] + self.descriptors = descriptors[best_indices] diff --git a/envs/kitoverlay/skimage/feature/orb_descriptor_positions.txt b/envs/kitoverlay/skimage/feature/orb_descriptor_positions.txt new file mode 100644 index 0000000000000000000000000000000000000000..a78b2eb421572adf2349fc0758e12ddef70f1b45 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/orb_descriptor_positions.txt @@ -0,0 +1,256 @@ +8 -3 9 5 +4 2 7 -12 +-11 9 -8 2 +7 -12 12 -13 +2 -13 2 12 +1 -7 1 6 +-2 -10 -2 -4 +-13 -13 -11 -8 +-13 -3 -12 -9 +10 4 11 9 +-13 -8 -8 -9 +-11 7 -9 12 +7 7 12 6 +-4 -5 -3 0 +-13 2 -12 -3 +-9 0 -7 5 +12 -6 12 -1 +-3 6 -2 12 +-6 -13 -4 -8 +11 -13 12 -8 +4 7 5 1 +5 -3 10 -3 +3 -7 6 12 +-8 -7 -6 -2 +-2 11 -1 -10 +-13 12 -8 10 +-7 3 -5 -3 +-4 2 -3 7 +-10 -12 -6 11 +5 -12 6 -7 +5 -6 7 -1 +1 0 4 -5 +9 11 11 -13 +4 7 4 12 +2 -1 4 4 +-4 -12 -2 7 +-8 -5 -7 -10 +4 11 9 12 +0 -8 1 -13 +-13 -2 -8 2 +-3 -2 -2 3 +-6 9 -4 -9 +8 12 10 7 +0 9 1 3 +7 -5 11 -10 +-13 -6 -11 0 +10 7 12 1 +-6 -3 -6 12 +10 -9 12 -4 +-13 8 -8 -12 +-13 0 -8 -4 +3 3 7 8 +5 7 10 -7 +-1 7 1 -12 +3 -10 5 6 +2 -4 3 -10 +-13 0 -13 5 +-13 -7 -12 12 +-13 3 -11 8 +-7 12 -4 7 +6 -10 12 8 +-9 -1 -7 -6 +-2 -5 0 12 +-12 5 -7 5 +3 -10 8 -13 +-7 -7 -4 5 +-3 -2 -1 -7 +2 9 5 -11 +-11 -13 -5 -13 +-1 6 0 -1 +5 -3 5 2 +-4 -13 -4 12 +-9 -6 -9 6 +-12 -10 -8 -4 +10 2 12 -3 +7 12 12 12 +-7 -13 -6 5 +-4 9 -3 4 +7 -1 12 2 +-7 6 -5 1 +-13 11 -12 5 +-3 7 -2 -6 +7 -8 12 -7 +-13 -7 -11 -12 +1 -3 12 12 +2 -6 3 0 +-4 3 -2 -13 +-1 -13 1 9 +7 1 8 -6 +1 -1 3 12 +9 1 12 6 +-1 -9 -1 3 +-13 -13 -10 5 +7 7 10 12 +12 -5 12 9 +6 3 7 11 +5 -13 6 10 +2 -12 2 3 +3 8 4 -6 +2 6 12 -13 +9 -12 10 3 +-8 4 -7 9 +-11 12 -4 -6 +1 12 2 -8 +6 -9 7 -4 +2 3 3 -2 +6 3 11 0 +3 -3 8 -8 +7 8 9 3 +-11 -5 -6 -4 +-10 11 -5 10 +-5 -8 -3 12 +-10 5 -9 0 +8 -1 12 -6 +4 -6 6 -11 +-10 12 -8 7 +4 -2 6 7 +-2 0 -2 12 +-5 -8 -5 2 +7 -6 10 12 +-9 -13 -8 -8 +-5 -13 -5 -2 +8 -8 9 -13 +-9 -11 -9 0 +1 -8 1 -2 +7 -4 9 1 +-2 1 -1 -4 +11 -6 12 -11 +-12 -9 -6 4 +3 7 7 12 +5 5 10 8 +0 -4 2 8 +-9 12 -5 -13 +0 7 2 12 +-1 2 1 7 +5 11 7 -9 +3 5 6 -8 +-13 -4 -8 9 +-5 9 -3 -3 +-4 -7 -3 -12 +6 5 8 0 +-7 6 -6 12 +-13 6 -5 -2 +1 -10 3 10 +4 1 8 -4 +-2 -2 2 -13 +2 -12 12 12 +-2 -13 0 -6 +4 1 9 3 +-6 -10 -3 -5 +-3 -13 -1 1 +7 5 12 -11 +4 -2 5 -7 +-13 9 -9 -5 +7 1 8 6 +7 -8 7 6 +-7 -4 -7 1 +-8 11 -7 -8 +-13 6 -12 -8 +2 4 3 9 +10 -5 12 3 +-6 -5 -6 7 +8 -3 9 -8 +2 -12 2 8 +-11 -2 -10 3 +-12 -13 -7 -9 +-11 0 -10 -5 +5 -3 11 8 +-2 -13 -1 12 +-1 -8 0 9 +-13 -11 -12 -5 +-10 -2 -10 11 +-3 9 -2 -13 +2 -3 3 2 +-9 -13 -4 0 +-4 6 -3 -10 +-4 12 -2 -7 +-6 -11 -4 9 +6 -3 6 11 +-13 11 -5 5 +11 11 12 6 +7 -5 12 -2 +-1 12 0 7 +-4 -8 -3 -2 +-7 1 -6 7 +-13 -12 -8 -13 +-7 -2 -6 -8 +-8 5 -6 -9 +-5 -1 -4 5 +-13 7 -8 10 +1 5 5 -13 +1 0 10 -13 +9 12 10 -1 +5 -8 10 -9 +-1 11 1 -13 +-9 -3 -6 2 +-1 -10 1 12 +-13 1 -8 -10 +8 -11 10 -6 +2 -13 3 -6 +7 -13 12 -9 +-10 -10 -5 -7 +-10 -8 -8 -13 +4 -6 8 5 +3 12 8 -13 +-4 2 -3 -3 +5 -13 10 -12 +4 -13 5 -1 +-9 9 -4 3 +0 3 3 -9 +-12 1 -6 1 +3 2 4 -8 +-10 -10 -10 9 +8 -13 12 12 +-8 -12 -6 -5 +2 2 3 7 +10 6 11 -8 +6 8 8 -12 +-7 10 -6 5 +-3 -9 -3 9 +-1 -13 -1 5 +-3 -7 -3 4 +-8 -2 -8 3 +4 2 12 12 +2 -5 3 11 +6 -9 11 -13 +3 -1 7 12 +11 -1 12 4 +-3 0 -3 6 +4 -11 4 12 +2 -4 2 1 +-10 -6 -8 1 +-13 7 -11 1 +-13 12 -11 -13 +6 0 11 -13 +0 -1 1 4 +-13 3 -9 -2 +-9 8 -6 -3 +-13 -6 -8 -2 +5 -9 8 10 +2 7 3 -9 +-1 -6 -1 -1 +9 5 11 -2 +11 -3 12 -8 +3 0 3 5 +-1 4 0 10 +3 -6 4 5 +-13 0 -10 5 +5 8 12 11 +8 9 9 -6 +7 -4 8 -12 +-10 4 -10 9 +7 3 12 4 +9 -7 10 -2 +7 0 12 -2 +-1 -6 0 -11 diff --git a/envs/kitoverlay/skimage/feature/peak.py b/envs/kitoverlay/skimage/feature/peak.py new file mode 100644 index 0000000000000000000000000000000000000000..6e8493174f11abac15e13876c323072e3ed6c744 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/peak.py @@ -0,0 +1,420 @@ +from warnings import warn + +import numpy as np +import scipy.ndimage as ndi + +from .. import measure +from .._shared.coord import ensure_spacing + + +def _get_high_intensity_peaks(image, mask, num_peaks, min_distance, p_norm): + """ + Return the highest intensity peak coordinates. + """ + # get coordinates of peaks + coord = np.nonzero(mask) + intensities = image[coord] + # Highest peak first + idx_maxsort = np.argsort(-intensities, kind="stable") + coord = np.transpose(coord)[idx_maxsort] + + if np.isfinite(num_peaks): + max_out = int(num_peaks) + else: + max_out = None + + if min_distance > 1: + coord = ensure_spacing( + coord, spacing=min_distance, p_norm=p_norm, max_out=max_out + ) + + if len(coord) > num_peaks: + coord = coord[:num_peaks] + + return coord + + +def _get_peak_mask(image, footprint, threshold, mask=None): + """ + Return the mask containing all peak candidates above thresholds. + """ + if footprint.size == 1 or image.size == 1: + return image > threshold + + image_max = ndi.maximum_filter(image, footprint=footprint, mode='nearest') + + out = image == image_max + + # no peak for a trivial image + image_is_trivial = np.all(out) if mask is None else np.all(out[mask]) + if image_is_trivial: + out[:] = False + if mask is not None: + # isolated pixels in masked area are returned as peaks + isolated_px = np.logical_xor(mask, ndi.binary_opening(mask)) + out[isolated_px] = True + + out &= image > threshold + return out + + +def _exclude_border(label, border_width): + """Set label border values to 0.""" + # zero out label borders + for i, width in enumerate(border_width): + if width == 0: + continue + label[(slice(None),) * i + (slice(None, width),)] = 0 + label[(slice(None),) * i + (slice(-width, None),)] = 0 + return label + + +def _get_threshold(image, threshold_abs, threshold_rel): + """Return the threshold value according to an absolute and a relative + value. + + """ + threshold = threshold_abs if threshold_abs is not None else image.min() + + if threshold_rel is not None: + threshold = max(threshold, threshold_rel * image.max()) + + return threshold + + +def _get_excluded_border_width(image, min_distance, exclude_border): + """Return border_width values relative to a min_distance if requested.""" + + if isinstance(exclude_border, bool): + border_width = (min_distance if exclude_border else 0,) * image.ndim + elif isinstance(exclude_border, int): + if exclude_border < 0: + raise ValueError("`exclude_border` cannot be a negative value") + border_width = (exclude_border,) * image.ndim + elif isinstance(exclude_border, tuple): + if len(exclude_border) != image.ndim: + raise ValueError( + "`exclude_border` should have the same length as the " + "dimensionality of the image." + ) + for exclude in exclude_border: + if not isinstance(exclude, int): + raise ValueError( + "`exclude_border`, when expressed as a tuple, must only " + "contain ints." + ) + if exclude < 0: + raise ValueError("`exclude_border` can not be a negative value") + border_width = exclude_border + else: + raise TypeError( + "`exclude_border` must be bool, int, or tuple with the same " + "length as the dimensionality of the image." + ) + + return border_width + + +def peak_local_max( + image, + min_distance=1, + threshold_abs=None, + threshold_rel=None, + exclude_border=True, + num_peaks=np.inf, + footprint=None, + labels=None, + num_peaks_per_label=np.inf, + p_norm=np.inf, +): + """Find peaks in an image as coordinate list. + + Peaks are the local maxima in a region of `2 * min_distance + 1` + (i.e. peaks are separated by at least `min_distance`). + + If both `threshold_abs` and `threshold_rel` are provided, the maximum + of the two is chosen as the minimum intensity threshold of peaks. + + .. versionchanged:: 0.18 + Prior to version 0.18, peaks of the same height within a radius of + `min_distance` were all returned, but this could cause unexpected + behaviour. From 0.18 onwards, an arbitrary peak within the region is + returned. See issue gh-2592. + + Parameters + ---------- + image : ndarray + Input image. + min_distance : int, optional + The minimal allowed distance separating peaks. To find the + maximum number of peaks, use `min_distance=1`. + threshold_abs : float or None, optional + Minimum intensity of peaks. By default, the absolute threshold is + the minimum intensity of the image. + threshold_rel : float or None, optional + Minimum intensity of peaks, calculated as + ``max(image) * threshold_rel``. + exclude_border : int, tuple of ints, or bool, optional + If positive integer, `exclude_border` excludes peaks from within + `exclude_border`-pixels of the border of the image. + If tuple of non-negative ints, the length of the tuple must match the + input array's dimensionality. Each element of the tuple will exclude + peaks from within `exclude_border`-pixels of the border of the image + along that dimension. + If True, takes the `min_distance` parameter as value. + If zero or False, peaks are identified regardless of their distance + from the border. + num_peaks : int, optional + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` peaks based on highest peak intensity. + footprint : ndarray of bools, optional + If provided, `footprint == 1` represents the local region within which + to search for peaks at every point in `image`. + labels : ndarray of ints, optional + If provided, each unique region `labels == value` represents a unique + region to search for peaks. Zero is reserved for background. + num_peaks_per_label : int, optional + Maximum number of peaks for each label. + p_norm : float + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + ``inf`` corresponds to the Chebyshev distance and 2 to the + Euclidean distance. + + Returns + ------- + output : ndarray + The coordinates of the peaks. + + Notes + ----- + The peak local maximum function returns the coordinates of local peaks + (maxima) in an image. Internally, a maximum filter is used for finding + local maxima. This operation dilates the original image. After comparison + of the dilated and original images, this function returns the coordinates + of the peaks where the dilated image equals the original image. + + See also + -------- + skimage.feature.corner_peaks + + Examples + -------- + >>> img1 = np.zeros((7, 7)) + >>> img1[3, 4] = 1 + >>> img1[3, 2] = 1.5 + >>> img1 + 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.5, 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. ]]) + + >>> peak_local_max(img1, min_distance=1) + array([[3, 2], + [3, 4]]) + + >>> peak_local_max(img1, min_distance=2) + array([[3, 2]]) + + >>> img2 = np.zeros((20, 20, 20)) + >>> img2[10, 10, 10] = 1 + >>> img2[15, 15, 15] = 1 + >>> peak_idx = peak_local_max(img2, exclude_border=0) + >>> peak_idx + array([[10, 10, 10], + [15, 15, 15]]) + + >>> peak_mask = np.zeros_like(img2, dtype=bool) + >>> peak_mask[tuple(peak_idx.T)] = True + >>> np.argwhere(peak_mask) + array([[10, 10, 10], + [15, 15, 15]]) + + """ + if (footprint is None or footprint.size == 1) and min_distance < 1: + warn( + "When min_distance < 1, peak_local_max acts as finding " + "image > max(threshold_abs, threshold_rel * max(image)).", + RuntimeWarning, + stacklevel=2, + ) + + border_width = _get_excluded_border_width(image, min_distance, exclude_border) + + threshold = _get_threshold(image, threshold_abs, threshold_rel) + + if footprint is None: + size = 2 * min_distance + 1 + footprint = np.ones((size,) * image.ndim, dtype=bool) + else: + footprint = np.asarray(footprint) + + if labels is None: + # Non maximum filter + mask = _get_peak_mask(image, footprint, threshold) + + mask = _exclude_border(mask, border_width) + + # Select highest intensities (num_peaks) + coordinates = _get_high_intensity_peaks( + image, mask, num_peaks, min_distance, p_norm + ) + + else: + _labels = _exclude_border(labels.astype(int, casting="safe"), border_width) + + if np.issubdtype(image.dtype, np.floating): + bg_val = np.finfo(image.dtype).min + else: + bg_val = np.iinfo(image.dtype).min + + # For each label, extract a smaller image enclosing the object of + # interest, identify num_peaks_per_label peaks + labels_peak_coord = [] + + for label_idx, roi in enumerate(ndi.find_objects(_labels)): + if roi is None: + continue + + # Get roi mask + label_mask = labels[roi] == label_idx + 1 + # Extract image roi + img_object = image[roi].copy() + # Ensure masked values don't affect roi's local peaks + img_object[np.logical_not(label_mask)] = bg_val + + mask = _get_peak_mask(img_object, footprint, threshold, label_mask) + + coordinates = _get_high_intensity_peaks( + img_object, mask, num_peaks_per_label, min_distance, p_norm + ) + + # transform coordinates in global image indices space + for idx, s in enumerate(roi): + coordinates[:, idx] += s.start + + labels_peak_coord.append(coordinates) + + if labels_peak_coord: + coordinates = np.vstack(labels_peak_coord) + else: + coordinates = np.empty((0, 2), dtype=int) + + if len(coordinates) > num_peaks: + out = np.zeros_like(image, dtype=bool) + out[tuple(coordinates.T)] = True + coordinates = _get_high_intensity_peaks( + image, out, num_peaks, min_distance, p_norm + ) + + return coordinates + + +def _prominent_peaks( + image, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=np.inf +): + """Return peaks with non-maximum suppression. + + Identifies most prominent features separated by certain distances. + Non-maximum suppression with different sizes is applied separately + in the first and second dimension of the image to identify peaks. + + Parameters + ---------- + image : (M, N) ndarray + Input image. + min_xdistance : int + Minimum distance separating features in the x dimension. + min_ydistance : int + Minimum distance separating features in the y dimension. + threshold : float + Minimum intensity of peaks. Default is `0.5 * max(image)`. + num_peaks : int + Maximum number of peaks. When the number of peaks exceeds `num_peaks`, + return `num_peaks` coordinates based on peak intensity. + + Returns + ------- + intensity, xcoords, ycoords : tuple of array + Peak intensity values, x and y indices. + """ + + img = image.copy() + rows, cols = img.shape + + if threshold is None: + threshold = 0.5 * np.max(img) + + ycoords_size = 2 * min_ydistance + 1 + xcoords_size = 2 * min_xdistance + 1 + img_max = ndi.maximum_filter1d( + img, size=ycoords_size, axis=0, mode='constant', cval=0 + ) + img_max = ndi.maximum_filter1d( + img_max, size=xcoords_size, axis=1, mode='constant', cval=0 + ) + mask = img == img_max + img *= mask + img_t = img > threshold + + label_img = measure.label(img_t) + props = measure.regionprops(label_img, img_max) + + # Sort the list of peaks by intensity, not left-right, so larger peaks + # in Hough space cannot be arbitrarily suppressed by smaller neighbors + props = sorted(props, key=lambda x: x.intensity_max)[::-1] + coords = np.array([np.round(p.centroid) for p in props], dtype=int) + + img_peaks = [] + ycoords_peaks = [] + xcoords_peaks = [] + + # relative coordinate grid for local neighborhood suppression + ycoords_ext, xcoords_ext = np.mgrid[ + -min_ydistance : min_ydistance + 1, -min_xdistance : min_xdistance + 1 + ] + + for ycoords_idx, xcoords_idx in coords: + accum = img_max[ycoords_idx, xcoords_idx] + if accum > threshold: + # absolute coordinate grid for local neighborhood suppression + ycoords_nh = ycoords_idx + ycoords_ext + xcoords_nh = xcoords_idx + xcoords_ext + + # no reflection for distance neighborhood + ycoords_in = np.logical_and(ycoords_nh > 0, ycoords_nh < rows) + ycoords_nh = ycoords_nh[ycoords_in] + xcoords_nh = xcoords_nh[ycoords_in] + + # reflect xcoords and assume xcoords are continuous, + # e.g. for angles: + # (..., 88, 89, -90, -89, ..., 89, -90, -89, ...) + xcoords_low = xcoords_nh < 0 + ycoords_nh[xcoords_low] = rows - ycoords_nh[xcoords_low] + xcoords_nh[xcoords_low] += cols + xcoords_high = xcoords_nh >= cols + ycoords_nh[xcoords_high] = rows - ycoords_nh[xcoords_high] + xcoords_nh[xcoords_high] -= cols + + # suppress neighborhood + img_max[ycoords_nh, xcoords_nh] = 0 + + # add current feature to peaks + img_peaks.append(accum) + ycoords_peaks.append(ycoords_idx) + xcoords_peaks.append(xcoords_idx) + + img_peaks = np.array(img_peaks) + ycoords_peaks = np.array(ycoords_peaks) + xcoords_peaks = np.array(xcoords_peaks) + + if num_peaks < len(img_peaks): + idx_maxsort = np.argsort(img_peaks)[::-1][:num_peaks] + img_peaks = img_peaks[idx_maxsort] + ycoords_peaks = ycoords_peaks[idx_maxsort] + xcoords_peaks = xcoords_peaks[idx_maxsort] + + return img_peaks, xcoords_peaks, ycoords_peaks diff --git a/envs/kitoverlay/skimage/feature/sift.py b/envs/kitoverlay/skimage/feature/sift.py new file mode 100644 index 0000000000000000000000000000000000000000..e5dab0f4523779ca9307015ba80506aa4f171914 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/sift.py @@ -0,0 +1,771 @@ +import math + +import numpy as np +import scipy.ndimage as ndi + +from .._shared.utils import check_nD, _supported_float_type +from ..feature.util import DescriptorExtractor, FeatureDetector +from .._shared.filters import gaussian +from ..transform import rescale +from ..util import img_as_float +from ._sift import _local_max, _ori_distances, _update_histogram + + +def _edgeness(hxx, hyy, hxy): + """Compute edgeness (eq. 18 of Otero et. al. IPOL paper)""" + trace = hxx + hyy + determinant = hxx * hyy - hxy * hxy + return (trace * trace) / determinant + + +def _sparse_gradient(vol, positions): + """Gradient of a 3D volume at the provided `positions`. + + For SIFT we only need the gradient at specific positions and do not need + the gradient at the edge positions, so can just use this simple + implementation instead of numpy.gradient. + """ + p0 = positions[..., 0] + p1 = positions[..., 1] + p2 = positions[..., 2] + g0 = vol[p0 + 1, p1, p2] - vol[p0 - 1, p1, p2] + g0 *= 0.5 + g1 = vol[p0, p1 + 1, p2] - vol[p0, p1 - 1, p2] + g1 *= 0.5 + g2 = vol[p0, p1, p2 + 1] - vol[p0, p1, p2 - 1] + g2 *= 0.5 + return g0, g1, g2 + + +def _hessian(d, positions): + """Compute the non-redundant 3D Hessian terms at the requested positions. + + Source: "Anatomy of the SIFT Method" p.380 (13) + """ + p0 = positions[..., 0] + p1 = positions[..., 1] + p2 = positions[..., 2] + two_d0 = 2 * d[p0, p1, p2] + # 0 = row, 1 = col, 2 = octave + h00 = d[p0 - 1, p1, p2] + d[p0 + 1, p1, p2] - two_d0 + h11 = d[p0, p1 - 1, p2] + d[p0, p1 + 1, p2] - two_d0 + h22 = d[p0, p1, p2 - 1] + d[p0, p1, p2 + 1] - two_d0 + h01 = 0.25 * ( + d[p0 + 1, p1 + 1, p2] + - d[p0 - 1, p1 + 1, p2] + - d[p0 + 1, p1 - 1, p2] + + d[p0 - 1, p1 - 1, p2] + ) + h02 = 0.25 * ( + d[p0 + 1, p1, p2 + 1] + - d[p0 + 1, p1, p2 - 1] + + d[p0 - 1, p1, p2 - 1] + - d[p0 - 1, p1, p2 + 1] + ) + h12 = 0.25 * ( + d[p0, p1 + 1, p2 + 1] + - d[p0, p1 + 1, p2 - 1] + + d[p0, p1 - 1, p2 - 1] + - d[p0, p1 - 1, p2 + 1] + ) + return (h00, h11, h22, h01, h02, h12) + + +def _offsets(grad, hess): + """Compute position refinement offsets from gradient and Hessian. + + This is equivalent to np.linalg.solve(-H, J) where H is the Hessian + matrix and J is the gradient (Jacobian). + + This analytical solution is adapted from (BSD-licensed) C code by + Otero et. al (see SIFT docstring References). + """ + h00, h11, h22, h01, h02, h12 = hess + g0, g1, g2 = grad + det = h00 * h11 * h22 + det -= h00 * h12 * h12 + det -= h01 * h01 * h22 + det += 2 * h01 * h02 * h12 + det -= h02 * h02 * h11 + aa = (h11 * h22 - h12 * h12) / det + ab = (h02 * h12 - h01 * h22) / det + ac = (h01 * h12 - h02 * h11) / det + bb = (h00 * h22 - h02 * h02) / det + bc = (h01 * h02 - h00 * h12) / det + cc = (h00 * h11 - h01 * h01) / det + offset0 = -aa * g0 - ab * g1 - ac * g2 + offset1 = -ab * g0 - bb * g1 - bc * g2 + offset2 = -ac * g0 - bc * g1 - cc * g2 + return np.stack((offset0, offset1, offset2), axis=-1) + + +class SIFT(FeatureDetector, DescriptorExtractor): + """SIFT feature detection and descriptor extraction. + + Parameters + ---------- + upsampling : int, optional + Prior to the feature detection the image is upscaled by a factor + of 1 (no upscaling), 2 or 4. Method: Bi-cubic interpolation. + n_octaves : int, optional + Maximum number of octaves. With every octave the image size is + halved and the sigma doubled. The number of octaves will be + reduced as needed to keep at least 12 pixels along each dimension + at the smallest scale. + n_scales : int, optional + Maximum number of scales in every octave. + sigma_min : float, optional + The blur level of the seed image. If upsampling is enabled + sigma_min is scaled by factor 1/upsampling + sigma_in : float, optional + The assumed blur level of the input image. + c_dog : float, optional + Threshold to discard low contrast extrema in the DoG. It's final + value is dependent on n_scales by the relation: + final_c_dog = (2^(1/n_scales)-1) / (2^(1/3)-1) * c_dog + c_edge : float, optional + Threshold to discard extrema that lie in edges. If H is the + Hessian of an extremum, its "edgeness" is described by + tr(H)²/det(H). If the edgeness is higher than + (c_edge + 1)²/c_edge, the extremum is discarded. + n_bins : int, optional + Number of bins in the histogram that describes the gradient + orientations around keypoint. + lambda_ori : float, optional + The window used to find the reference orientation of a keypoint + has a width of 6 * lambda_ori * sigma and is weighted by a + standard deviation of 2 * lambda_ori * sigma. + c_max : float, optional + The threshold at which a secondary peak in the orientation + histogram is accepted as orientation + lambda_descr : float, optional + The window used to define the descriptor of a keypoint has a width + of 2 * lambda_descr * sigma * (n_hist+1)/n_hist and is weighted by + a standard deviation of lambda_descr * sigma. + n_hist : int, optional + The window used to define the descriptor of a keypoint consists of + n_hist * n_hist histograms. + n_ori : int, optional + The number of bins in the histograms of the descriptor patch. + + Attributes + ---------- + delta_min : float + The sampling distance of the first octave. It's final value is + 1/upsampling. + float_dtype : type + The datatype of the image. + scalespace_sigmas : (n_octaves, n_scales + 3) array + The sigma value of all scales in all octaves. + keypoints : (N, 2) array + Keypoint coordinates as ``(row, col)``. + positions : (N, 2) array + Subpixel-precision keypoint coordinates as ``(row, col)``. + sigmas : (N,) array + The corresponding sigma (blur) value of a keypoint. + scales : (N,) array + The corresponding scale of a keypoint. + orientations : (N,) array + The orientations of the gradient around every keypoint. + octaves : (N,) array + The corresponding octave of a keypoint. + descriptors : (N, n_hist*n_hist*n_ori) array + The descriptors of a keypoint. + + Notes + ----- + The SIFT algorithm was developed by David Lowe [1]_, [2]_ and later + patented by the University of British Columbia. Since the patent expired in + 2020 it's free to use. The implementation here closely follows the + detailed description in [3]_, including use of the same default parameters. + + References + ---------- + .. [1] D.G. Lowe. "Object recognition from local scale-invariant + features", Proceedings of the Seventh IEEE International + Conference on Computer Vision, 1999, vol.2, pp. 1150-1157. + :DOI:`10.1109/ICCV.1999.790410` + + .. [2] D.G. Lowe. "Distinctive Image Features from Scale-Invariant + Keypoints", International Journal of Computer Vision, 2004, + vol. 60, pp. 91–110. + :DOI:`10.1023/B:VISI.0000029664.99615.94` + + .. [3] I. R. Otero and M. Delbracio. "Anatomy of the SIFT Method", + Image Processing On Line, 4 (2014), pp. 370–396. + :DOI:`10.5201/ipol.2014.82` + + Examples + -------- + >>> from skimage.feature import SIFT, match_descriptors + >>> from skimage.data import camera + >>> from skimage.transform import rotate + >>> img1 = camera() + >>> img2 = rotate(camera(), 90) + >>> detector_extractor1 = SIFT() + >>> detector_extractor2 = SIFT() + >>> detector_extractor1.detect_and_extract(img1) + >>> detector_extractor2.detect_and_extract(img2) + >>> matches = match_descriptors(detector_extractor1.descriptors, + ... detector_extractor2.descriptors, + ... max_ratio=0.6) + >>> matches[10:15] + array([[ 10, 412], + [ 11, 417], + [ 12, 407], + [ 13, 411], + [ 14, 406]]) + >>> detector_extractor1.keypoints[matches[10:15, 0]] + array([[ 95, 214], + [ 97, 211], + [ 97, 218], + [102, 215], + [104, 218]]) + >>> detector_extractor2.keypoints[matches[10:15, 1]] + array([[297, 95], + [301, 97], + [294, 97], + [297, 102], + [293, 104]]) + + """ + + def __init__( + self, + upsampling=2, + n_octaves=8, + n_scales=3, + sigma_min=1.6, + sigma_in=0.5, + c_dog=0.04 / 3, + c_edge=10, + n_bins=36, + lambda_ori=1.5, + c_max=0.8, + lambda_descr=6, + n_hist=4, + n_ori=8, + ): + if upsampling in [1, 2, 4]: + self.upsampling = upsampling + else: + raise ValueError("upsampling must be 1, 2 or 4") + self.n_octaves = n_octaves + self.n_scales = n_scales + self.sigma_min = sigma_min / upsampling + self.sigma_in = sigma_in + self.c_dog = (2 ** (1 / n_scales) - 1) / (2 ** (1 / 3) - 1) * c_dog + self.c_edge = c_edge + self.n_bins = n_bins + self.lambda_ori = lambda_ori + self.c_max = c_max + self.lambda_descr = lambda_descr + self.n_hist = n_hist + self.n_ori = n_ori + self.delta_min = 1 / upsampling + self.float_dtype = None + self.scalespace_sigmas = None + self.keypoints = None + self.positions = None + self.sigmas = None + self.scales = None + self.orientations = None + self.octaves = None + self.descriptors = None + + @property + def deltas(self): + """The sampling distances of all octaves""" + deltas = self.delta_min * np.power( + 2, np.arange(self.n_octaves), dtype=self.float_dtype + ) + return deltas + + def _set_number_of_octaves(self, image_shape): + size_min = 12 # minimum size of last octave + s0 = min(image_shape) * self.upsampling + max_octaves = int(math.log2(s0 / size_min) + 1) + if max_octaves < self.n_octaves: + self.n_octaves = max_octaves + + def _create_scalespace(self, image): + """Source: "Anatomy of the SIFT Method" Alg. 1 + Construction of the scalespace by gradually blurring (scales) and + downscaling (octaves) the image. + """ + scalespace = [] + if self.upsampling > 1: + image = rescale(image, self.upsampling, order=1) + + # smooth to sigma_min, assuming sigma_in + image = gaussian( + image, + sigma=self.upsampling * math.sqrt(self.sigma_min**2 - self.sigma_in**2), + mode='reflect', + ) + + # Eq. 10: sigmas.shape = (n_octaves, n_scales + 3). + # The three extra scales are: + # One for the differences needed for DoG and two auxiliary + # images (one at either end) for peak_local_max with exclude + # border = True (see Fig. 5) + # The smoothing doubles after n_scales steps. + tmp = np.power(2, np.arange(self.n_scales + 3) / self.n_scales) + tmp *= self.sigma_min + # all sigmas for the gaussian scalespace + sigmas = self.deltas[:, np.newaxis] / self.deltas[0] * tmp[np.newaxis, :] + self.scalespace_sigmas = sigmas + + # Eq. 7: Gaussian smoothing depends on difference with previous sigma + # gaussian_sigmas.shape = (n_octaves, n_scales + 2) + var_diff = np.diff(sigmas * sigmas, axis=1) + gaussian_sigmas = np.sqrt(var_diff) / self.deltas[:, np.newaxis] + + # one octave is represented by a 3D image with depth (n_scales+x) + for o in range(self.n_octaves): + # Temporarily put scales axis first so octave[i] is C-contiguous + # (this makes Gaussian filtering faster). + octave = np.empty( + (self.n_scales + 3,) + image.shape, dtype=self.float_dtype, order='C' + ) + octave[0] = image + for s in range(1, self.n_scales + 3): + # blur new scale assuming sigma of the last one + gaussian( + octave[s - 1], + sigma=gaussian_sigmas[o, s - 1], + mode='reflect', + out=octave[s], + ) + # move scales to last axis as expected by other methods + scalespace.append(np.moveaxis(octave, 0, -1)) + if o < self.n_octaves - 1: + # downscale the image by taking every second pixel + image = octave[self.n_scales][::2, ::2] + return scalespace + + def _inrange(self, a, dim): + return ( + (a[:, 0] > 0) + & (a[:, 0] < dim[0] - 1) + & (a[:, 1] > 0) + & (a[:, 1] < dim[1] - 1) + ) + + def _find_localize_evaluate(self, dogspace, img_shape): + """Source: "Anatomy of the SIFT Method" Alg. 4-9 + 1) first find all extrema of a (3, 3, 3) neighborhood + 2) use second order Taylor development to refine the positions to + sub-pixel precision + 3) filter out extrema that have low contrast and lie on edges or close + to the image borders + """ + extrema_pos = [] + extrema_scales = [] + extrema_sigmas = [] + threshold = self.c_dog * 0.8 + for o, (octave, delta) in enumerate(zip(dogspace, self.deltas)): + # find extrema + keys = _local_max(np.ascontiguousarray(octave), threshold) + if keys.size == 0: + extrema_pos.append(np.empty((0, 2))) + continue + + # localize extrema + oshape = octave.shape + refinement_iterations = 5 + offset_max = 0.6 + for i in range(refinement_iterations): + if i > 0: + # exclude any keys that have moved out of bounds + keys = keys[self._inrange(keys, oshape), :] + + # Jacobian and Hessian of all extrema + grad = _sparse_gradient(octave, keys) + hess = _hessian(octave, keys) + + # solve for offset of the extremum + off = _offsets(grad, hess) + if i == refinement_iterations - 1: + break + # offset is too big and an increase would not bring us out of + # bounds + wrong_position_pos = np.logical_and( + off > offset_max, keys + 1 < tuple([a - 1 for a in oshape]) + ) + wrong_position_neg = np.logical_and(off < -offset_max, keys - 1 > 0) + if not np.any(np.logical_or(wrong_position_neg, wrong_position_pos)): + break + keys[wrong_position_pos] += 1 + keys[wrong_position_neg] -= 1 + + # mask for all extrema that have been localized successfully + finished = np.all(np.abs(off) < offset_max, axis=1) + keys = keys[finished] + off = off[finished] + grad = [g[finished] for g in grad] + + # value of extremum in octave + vals = octave[keys[:, 0], keys[:, 1], keys[:, 2]] + # values at interpolated point + w = vals + for i in range(3): + w += 0.5 * grad[i] * off[:, i] + + h00, h11, h01 = hess[0][finished], hess[1][finished], hess[3][finished] + + sigmaratio = self.scalespace_sigmas[0, 1] / self.scalespace_sigmas[0, 0] + + # filter for contrast, edgeness and borders + contrast_threshold = self.c_dog + contrast_filter = np.abs(w) > contrast_threshold + + edge_threshold = np.square(self.c_edge + 1) / self.c_edge + edge_response = _edgeness( + h00[contrast_filter], h11[contrast_filter], h01[contrast_filter] + ) + edge_filter = np.abs(edge_response) <= edge_threshold + + keys = keys[contrast_filter][edge_filter] + off = off[contrast_filter][edge_filter] + yx = ((keys[:, :2] + off[:, :2]) * delta).astype(self.float_dtype) + + sigmas = self.scalespace_sigmas[o, keys[:, 2]] * np.power( + sigmaratio, off[:, 2] + ) + border_filter = np.all( + np.logical_and( + (yx - sigmas[:, np.newaxis]) > 0.0, + (yx + sigmas[:, np.newaxis]) < img_shape, + ), + axis=1, + ) + extrema_pos.append(yx[border_filter]) + extrema_scales.append(keys[border_filter, 2]) + extrema_sigmas.append(sigmas[border_filter]) + + octave_indices = np.concatenate( + [np.full(len(p), i) for i, p in enumerate(extrema_pos)] + ) + + if len(octave_indices) == 0: + raise RuntimeError( + "SIFT found no features. Try passing in an image containing " + "greater intensity contrasts between adjacent pixels." + ) + + extrema_pos = np.concatenate(extrema_pos) + extrema_scales = np.concatenate(extrema_scales) + extrema_sigmas = np.concatenate(extrema_sigmas) + return extrema_pos, extrema_scales, extrema_sigmas, octave_indices + + def _fit(self, h): + """Refine the position of the peak by fitting it to a parabola""" + return (h[0] - h[2]) / (2 * (h[0] + h[2] - 2 * h[1])) + + def _compute_orientation( + self, positions_oct, scales_oct, sigmas_oct, octaves, gaussian_scalespace + ): + """Source: "Anatomy of the SIFT Method" Alg. 11 + Calculates the orientation of the gradient around every keypoint + """ + gradient_space = [] + # list for keypoints that have more than one reference orientation + keypoint_indices = [] + keypoint_angles = [] + keypoint_octave = [] + orientations = np.zeros_like(sigmas_oct, dtype=self.float_dtype) + key_count = 0 + for o, (octave, delta) in enumerate(zip(gaussian_scalespace, self.deltas)): + gradient_space.append(np.gradient(octave)) + + in_oct = octaves == o + if not np.any(in_oct): + continue + positions = positions_oct[in_oct] + scales = scales_oct[in_oct] + sigmas = sigmas_oct[in_oct] + + oshape = octave.shape[:2] + # convert to octave's dimensions + yx = positions / delta + sigma = sigmas / delta + + # dimensions of the patch + radius = 3 * self.lambda_ori * sigma + p_min = np.maximum(0, yx - radius[:, np.newaxis] + 0.5).astype(int) + p_max = np.minimum( + yx + radius[:, np.newaxis] + 0.5, (oshape[0] - 1, oshape[1] - 1) + ).astype(int) + # orientation histogram + hist = np.empty(self.n_bins, dtype=self.float_dtype) + avg_kernel = np.full((3,), 1 / 3, dtype=self.float_dtype) + for k in range(len(yx)): + hist[:] = 0 + + # use the patch coordinates to get the gradient and then + # normalize them + r, c = np.meshgrid( + np.arange(p_min[k, 0], p_max[k, 0] + 1), + np.arange(p_min[k, 1], p_max[k, 1] + 1), + indexing='ij', + sparse=True, + ) + gradient_row = gradient_space[o][0][r, c, scales[k]] + gradient_col = gradient_space[o][1][r, c, scales[k]] + r = r.astype(self.float_dtype, copy=False) + c = c.astype(self.float_dtype, copy=False) + r -= yx[k, 0] + c -= yx[k, 1] + + # gradient magnitude and angles + magnitude = np.sqrt(np.square(gradient_row) + np.square(gradient_col)) + theta = np.mod(np.arctan2(gradient_col, gradient_row), 2 * np.pi) + + # more weight to center values + kernel = np.exp( + np.divide(r * r + c * c, -2 * (self.lambda_ori * sigma[k]) ** 2) + ) + + # fill the histogram + bins = np.floor( + (theta / (2 * np.pi) * self.n_bins + 0.5) % self.n_bins + ).astype(int) + np.add.at(hist, bins, kernel * magnitude) + + # smooth the histogram and find the maximum + hist = np.concatenate((hist[-6:], hist, hist[:6])) + for _ in range(6): # number of smoothings + hist = np.convolve(hist, avg_kernel, mode='same') + hist = hist[6:-6] + max_filter = ndi.maximum_filter(hist, [3], mode='wrap') + + # if an angle is in 80% percent range of the maximum, a + # new keypoint is created for it + maxima = np.nonzero( + np.logical_and( + hist >= (self.c_max * np.max(hist)), max_filter == hist + ) + ) + + # save the angles + for c, m in enumerate(maxima[0]): + neigh = np.arange(m - 1, m + 2) % len(hist) + # use neighbors to fit a parabola, to get more accurate + # result + ori = (m + self._fit(hist[neigh]) + 0.5) * 2 * np.pi / self.n_bins + if ori > np.pi: + ori -= 2 * np.pi + if c == 0: + orientations[key_count] = ori + else: + keypoint_indices.append(key_count) + keypoint_angles.append(ori) + keypoint_octave.append(o) + key_count += 1 + self.positions = np.concatenate( + (positions_oct, positions_oct[keypoint_indices]) + ) + self.scales = np.concatenate((scales_oct, scales_oct[keypoint_indices])) + self.sigmas = np.concatenate((sigmas_oct, sigmas_oct[keypoint_indices])) + self.orientations = np.concatenate((orientations, keypoint_angles)) + self.octaves = np.concatenate((octaves, keypoint_octave)) + # return the gradient_space to reuse it to find the descriptor + return gradient_space + + def _rotate(self, row, col, angle): + c = math.cos(angle) + s = math.sin(angle) + rot_row = c * row + s * col + rot_col = -s * row + c * col + return rot_row, rot_col + + def _compute_descriptor(self, gradient_space): + """Source: "Anatomy of the SIFT Method" Alg. 12 + Calculates the descriptor for every keypoint + """ + n_key = len(self.scales) + self.descriptors = np.empty( + (n_key, self.n_hist**2 * self.n_ori), dtype=np.uint8 + ) + + # indices of the histograms + hists = np.arange(1, self.n_hist + 1, dtype=self.float_dtype) + # indices of the bins + bins = np.arange(1, self.n_ori + 1, dtype=self.float_dtype) + + key_numbers = np.arange(n_key) + for o, (gradient, delta) in enumerate(zip(gradient_space, self.deltas)): + in_oct = self.octaves == o + if not np.any(in_oct): + continue + positions = self.positions[in_oct] + scales = self.scales[in_oct] + sigmas = self.sigmas[in_oct] + orientations = self.orientations[in_oct] + numbers = key_numbers[in_oct] + + dim = gradient[0].shape[:2] + center_pos = positions / delta + sigma = sigmas / delta + + # dimensions of the patch + radius = self.lambda_descr * (1 + 1 / self.n_hist) * sigma + radius_patch = math.sqrt(2) * radius + p_min = np.asarray( + np.maximum(0, center_pos - radius_patch[:, np.newaxis] + 0.5), dtype=int + ) + p_max = np.asarray( + np.minimum( + center_pos + radius_patch[:, np.newaxis] + 0.5, + (dim[0] - 1, dim[1] - 1), + ), + dtype=int, + ) + + for k in range(len(p_max)): + rad_k = float(radius[k]) + ori = float(orientations[k]) + histograms = np.zeros( + (self.n_hist, self.n_hist, self.n_ori), dtype=self.float_dtype + ) + # the patch + r, c = np.meshgrid( + np.arange(p_min[k, 0], p_max[k, 0]), + np.arange(p_min[k, 1], p_max[k, 1]), + indexing='ij', + sparse=True, + ) + # normalized coordinates + r_norm = np.subtract(r, center_pos[k, 0], dtype=self.float_dtype) + c_norm = np.subtract(c, center_pos[k, 1], dtype=self.float_dtype) + r_norm, c_norm = self._rotate(r_norm, c_norm, ori) + + # select coordinates and gradient values within the patch + inside = np.maximum(np.abs(r_norm), np.abs(c_norm)) < rad_k + r_norm, c_norm = r_norm[inside], c_norm[inside] + r_idx, c_idx = np.nonzero(inside) + r = r[r_idx, 0] + c = c[0, c_idx] + gradient_row = gradient[0][r, c, scales[k]] + gradient_col = gradient[1][r, c, scales[k]] + # compute the (relative) gradient orientation + theta = np.arctan2(gradient_col, gradient_row) - ori + lam_sig = self.lambda_descr * float(sigma[k]) + # Gaussian weighted kernel magnitude + kernel = np.exp((r_norm * r_norm + c_norm * c_norm) / (-2 * lam_sig**2)) + magnitude = ( + np.sqrt(gradient_row * gradient_row + gradient_col * gradient_col) + * kernel + ) + + lam_sig_ratio = 2 * lam_sig / self.n_hist + rc_bins = (hists - (1 + self.n_hist) / 2) * lam_sig_ratio + rc_bin_spacing = lam_sig_ratio + ori_bins = (2 * np.pi * bins) / self.n_ori + + # distances to the histograms and bins + dist_r = np.abs(np.subtract.outer(rc_bins, r_norm)) + dist_c = np.abs(np.subtract.outer(rc_bins, c_norm)) + + # the orientation histograms/bins that get the contribution + near_t, near_t_val = _ori_distances(ori_bins, theta) + + # create the histogram + _update_histogram( + histograms, + near_t, + near_t_val, + magnitude, + dist_r, + dist_c, + rc_bin_spacing, + ) + + # convert the histograms to a 1d descriptor + histograms = histograms.reshape(-1) + # saturate the descriptor + histograms = np.minimum(histograms, 0.2 * np.linalg.norm(histograms)) + # normalize the descriptor + descriptor = (512 * histograms) / np.linalg.norm(histograms) + # quantize the descriptor + descriptor = np.minimum(np.floor(descriptor), 255) + self.descriptors[numbers[k], :] = descriptor + + def _preprocess(self, image): + check_nD(image, 2) + image = img_as_float(image) + self.float_dtype = _supported_float_type(image.dtype) + image = image.astype(self.float_dtype, copy=False) + + self._set_number_of_octaves(image.shape) + return image + + def detect(self, image): + """Detect the keypoints. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + dog_scalespace = [np.diff(layer, axis=2) for layer in gaussian_scalespace] + + positions, scales, sigmas, octaves = self._find_localize_evaluate( + dog_scalespace, image.shape + ) + + self._compute_orientation( + positions, scales, sigmas, octaves, gaussian_scalespace + ) + + self.keypoints = self.positions.round().astype(int) + + def extract(self, image): + """Extract the descriptors for all keypoints in the image. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + gradient_space = [np.gradient(octave) for octave in gaussian_scalespace] + + self._compute_descriptor(gradient_space) + + def detect_and_extract(self, image): + """Detect the keypoints and extract their descriptors. + + Parameters + ---------- + image : 2D array + Input image. + + """ + image = self._preprocess(image) + + gaussian_scalespace = self._create_scalespace(image) + + dog_scalespace = [np.diff(layer, axis=2) for layer in gaussian_scalespace] + + positions, scales, sigmas, octaves = self._find_localize_evaluate( + dog_scalespace, image.shape + ) + + gradient_space = self._compute_orientation( + positions, scales, sigmas, octaves, gaussian_scalespace + ) + + self._compute_descriptor(gradient_space) + + self.keypoints = self.positions.round().astype(int) diff --git a/envs/kitoverlay/skimage/feature/template.py b/envs/kitoverlay/skimage/feature/template.py new file mode 100644 index 0000000000000000000000000000000000000000..06defe96f96b48d0dea6c66b4974e4f3ef1daedc --- /dev/null +++ b/envs/kitoverlay/skimage/feature/template.py @@ -0,0 +1,186 @@ +import math + +import numpy as np +from scipy.signal import fftconvolve + +from .._shared.utils import check_nD, _supported_float_type + + +def _window_sum_2d(image, window_shape): + window_sum = np.cumsum(image, axis=0) + window_sum = window_sum[window_shape[0] : -1] - window_sum[: -window_shape[0] - 1] + + window_sum = np.cumsum(window_sum, axis=1) + window_sum = ( + window_sum[:, window_shape[1] : -1] - window_sum[:, : -window_shape[1] - 1] + ) + + return window_sum + + +def _window_sum_3d(image, window_shape): + window_sum = _window_sum_2d(image, window_shape) + + window_sum = np.cumsum(window_sum, axis=2) + window_sum = ( + window_sum[:, :, window_shape[2] : -1] + - window_sum[:, :, : -window_shape[2] - 1] + ) + + return window_sum + + +def match_template( + image, template, pad_input=False, mode='constant', constant_values=0 +): + """Match a template to a 2-D or 3-D image using normalized correlation. + + The output is an array with values between -1.0 and 1.0. The value at a + given position corresponds to the correlation coefficient between the image + and the template. + + For `pad_input=True` matches correspond to the center and otherwise to the + top-left corner of the template. To find the best match you must search for + peaks in the response (output) image. + + Parameters + ---------- + image : (M, N[, P]) array + 2-D or 3-D input image. + template : (m, n[, p]) array + Template to locate. It must be `(m <= M, n <= N[, p <= P])`. + pad_input : bool + If True, pad `image` so that output is the same size as the image, and + output values correspond to the template center. Otherwise, the output + is an array with shape `(M - m + 1, N - n + 1)` for an `(M, N)` image + and an `(m, n)` template, and matches correspond to origin + (top-left corner) of the template. + mode : see `numpy.pad`, optional + Padding mode. + constant_values : see `numpy.pad`, optional + Constant values used in conjunction with ``mode='constant'``. + + Returns + ------- + output : array + Response image with correlation coefficients. + + Notes + ----- + Details on the cross-correlation are presented in [1]_. This implementation + uses FFT convolutions of the image and the template. Reference [2]_ + presents similar derivations but the approximation presented in this + reference is not used in our implementation. + + References + ---------- + .. [1] J. P. Lewis, "Fast Normalized Cross-Correlation", Industrial Light + and Magic. + .. [2] Briechle and Hanebeck, "Template Matching using Fast Normalized + Cross Correlation", Proceedings of the SPIE (2001). + :DOI:`10.1117/12.421129` + + Examples + -------- + >>> template = np.zeros((3, 3)) + >>> template[1, 1] = 1 + >>> template + array([[0., 0., 0.], + [0., 1., 0.], + [0., 0., 0.]]) + >>> image = np.zeros((6, 6)) + >>> image[1, 1] = 1 + >>> image[4, 4] = -1 + >>> image + array([[ 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., -1., 0.], + [ 0., 0., 0., 0., 0., 0.]]) + >>> result = match_template(image, template) + >>> np.round(result, 3) + array([[ 1. , -0.125, 0. , 0. ], + [-0.125, -0.125, 0. , 0. ], + [ 0. , 0. , 0.125, 0.125], + [ 0. , 0. , 0.125, -1. ]]) + >>> result = match_template(image, template, pad_input=True) + >>> np.round(result, 3) + array([[-0.125, -0.125, -0.125, 0. , 0. , 0. ], + [-0.125, 1. , -0.125, 0. , 0. , 0. ], + [-0.125, -0.125, -0.125, 0. , 0. , 0. ], + [ 0. , 0. , 0. , 0.125, 0.125, 0.125], + [ 0. , 0. , 0. , 0.125, -1. , 0.125], + [ 0. , 0. , 0. , 0.125, 0.125, 0.125]]) + """ + check_nD(image, (2, 3)) + + if image.ndim < template.ndim: + raise ValueError( + "Dimensionality of template must be less than or " + "equal to the dimensionality of image." + ) + if np.any(np.less(image.shape, template.shape)): + raise ValueError("Image must be larger than template.") + + image_shape = image.shape + + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + pad_width = tuple((width, width) for width in template.shape) + if mode == 'constant': + image = np.pad( + image, pad_width=pad_width, mode=mode, constant_values=constant_values + ) + else: + image = np.pad(image, pad_width=pad_width, mode=mode) + + # Use special case for 2-D images for much better performance in + # computation of integral images + if image.ndim == 2: + image_window_sum = _window_sum_2d(image, template.shape) + image_window_sum2 = _window_sum_2d(image**2, template.shape) + elif image.ndim == 3: + image_window_sum = _window_sum_3d(image, template.shape) + image_window_sum2 = _window_sum_3d(image**2, template.shape) + + template_mean = template.mean() + template_volume = math.prod(template.shape) + template_ssd = np.sum((template - template_mean) ** 2) + + if image.ndim == 2: + xcorr = fftconvolve(image, template[::-1, ::-1], mode="valid")[1:-1, 1:-1] + elif image.ndim == 3: + xcorr = fftconvolve(image, template[::-1, ::-1, ::-1], mode="valid")[ + 1:-1, 1:-1, 1:-1 + ] + + numerator = xcorr - image_window_sum * template_mean + + denominator = image_window_sum2 + np.multiply(image_window_sum, image_window_sum, out=image_window_sum) + np.divide(image_window_sum, template_volume, out=image_window_sum) + denominator -= image_window_sum + denominator *= template_ssd + np.maximum(denominator, 0, out=denominator) # sqrt of negative number not allowed + np.sqrt(denominator, out=denominator) + + response = np.zeros_like(xcorr, dtype=float_dtype) + + # avoid zero-division + mask = denominator > np.finfo(float_dtype).eps + + response[mask] = numerator[mask] / denominator[mask] + + slices = [] + for i in range(template.ndim): + if pad_input: + d0 = (template.shape[i] - 1) // 2 + d1 = d0 + image_shape[i] + else: + d0 = template.shape[i] - 1 + d1 = d0 + image_shape[i] - template.shape[i] + 1 + slices.append(slice(d0, d1)) + + return response[tuple(slices)] diff --git a/envs/kitoverlay/skimage/feature/texture.py b/envs/kitoverlay/skimage/feature/texture.py new file mode 100644 index 0000000000000000000000000000000000000000..200aca450147045b9a015c67db182c5542756484 --- /dev/null +++ b/envs/kitoverlay/skimage/feature/texture.py @@ -0,0 +1,562 @@ +""" +Methods to characterize image textures. +""" + +import warnings + +import numpy as np + +from .._shared.utils import check_nD +from ..color import gray2rgb +from ..util import img_as_float +from ._texture import _glcm_loop, _local_binary_pattern, _multiblock_lbp + + +def graycomatrix(image, distances, angles, levels=None, symmetric=False, normed=False): + """Calculate the gray-level co-occurrence matrix. + + A gray level co-occurrence matrix is a histogram of co-occurring + grayscale values at a given offset over an image. + + .. versionchanged:: 0.19 + `greymatrix` was renamed to `graymatrix` in 0.19. + + Parameters + ---------- + image : array_like + Integer typed input image. Only positive valued images are supported. + If type is other than uint8, the argument `levels` needs to be set. + distances : array_like + List of pixel pair distance offsets. + angles : array_like + List of pixel pair angles in radians. + levels : int, optional + The input image should contain integers in [0, `levels`-1], + where levels indicate the number of gray-levels counted + (typically 256 for an 8-bit image). This argument is required for + 16-bit images or higher and is typically the maximum of the image. + As the output matrix is at least `levels` x `levels`, it might + be preferable to use binning of the input image rather than + large values for `levels`. + symmetric : bool, optional + If True, the output matrix `P[:, :, d, theta]` is symmetric. This + is accomplished by ignoring the order of value pairs, so both + (i, j) and (j, i) are accumulated when (i, j) is encountered + for a given offset. The default is False. + normed : bool, optional + If True, normalize each matrix `P[:, :, d, theta]` by dividing + by the total number of accumulated co-occurrences for the given + offset. The elements of the resulting matrix sum to 1. The + default is False. + + Returns + ------- + P : 4-D ndarray + The gray-level co-occurrence histogram. The value + `P[i,j,d,theta]` is the number of times that gray-level `j` + occurs at a distance `d` and at an angle `theta` from + gray-level `i`. If `normed` is `False`, the output is of + type uint32, otherwise it is float64. The dimensions are: + levels x levels x number of distances x number of angles. + + References + ---------- + .. [1] M. Hall-Beyer, 2007. GLCM Texture: A Tutorial + https://prism.ucalgary.ca/handle/1880/51900 + DOI:`10.11575/PRISM/33280` + .. [2] R.M. Haralick, K. Shanmugam, and I. Dinstein, "Textural features for + image classification", IEEE Transactions on Systems, Man, and + Cybernetics, vol. SMC-3, no. 6, pp. 610-621, Nov. 1973. + :DOI:`10.1109/TSMC.1973.4309314` + .. [3] M. Nadler and E.P. Smith, Pattern Recognition Engineering, + Wiley-Interscience, 1993. + .. [4] Wikipedia, https://en.wikipedia.org/wiki/Co-occurrence_matrix + + + Examples + -------- + Compute 4 GLCMs using 1-pixel distance and 4 different angles. For example, + an angle of 0 radians refers to the neighboring pixel to the right; + pi/4 radians to the top-right diagonal neighbor; pi/2 radians to the pixel + above, and so forth. + + >>> image = np.array([[0, 0, 1, 1], + ... [0, 0, 1, 1], + ... [0, 2, 2, 2], + ... [2, 2, 3, 3]], dtype=np.uint8) + >>> result = graycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], + ... levels=4) + >>> result[:, :, 0, 0] + array([[2, 2, 1, 0], + [0, 2, 0, 0], + [0, 0, 3, 1], + [0, 0, 0, 1]], dtype=uint32) + >>> result[:, :, 0, 1] + array([[1, 1, 3, 0], + [0, 1, 1, 0], + [0, 0, 0, 2], + [0, 0, 0, 0]], dtype=uint32) + >>> result[:, :, 0, 2] + array([[3, 0, 2, 0], + [0, 2, 2, 0], + [0, 0, 1, 2], + [0, 0, 0, 0]], dtype=uint32) + >>> result[:, :, 0, 3] + array([[2, 0, 0, 0], + [1, 1, 2, 0], + [0, 0, 2, 1], + [0, 0, 0, 0]], dtype=uint32) + + """ + check_nD(image, 2) + check_nD(distances, 1, 'distances') + check_nD(angles, 1, 'angles') + + image = np.ascontiguousarray(image) + + image_max = image.max() + + if np.issubdtype(image.dtype, np.floating): + raise ValueError( + "Float images are not supported by graycomatrix. " + "Convert the image to an unsigned integer type." + ) + + # for image type > 8bit, levels must be set. + if image.dtype not in (np.uint8, np.int8) and levels is None: + raise ValueError( + "The levels argument is required for data types " + "other than uint8. The resulting matrix will be at " + "least levels ** 2 in size." + ) + + if np.issubdtype(image.dtype, np.signedinteger) and np.any(image < 0): + raise ValueError("Negative-valued images are not supported.") + + if levels is None: + levels = 256 + + if image_max >= levels: + raise ValueError( + "The maximum grayscale value in the image should be " + "smaller than the number of levels." + ) + + distances = np.ascontiguousarray(distances, dtype=np.float64) + angles = np.ascontiguousarray(angles, dtype=np.float64) + + P = np.zeros( + (levels, levels, len(distances), len(angles)), dtype=np.uint32, order='C' + ) + + # count co-occurences + _glcm_loop(image, distances, angles, levels, P) + + # make each GLMC symmetric + if symmetric: + Pt = np.transpose(P, (1, 0, 2, 3)) + P = P + Pt + + # normalize each GLCM + if normed: + P = P.astype(np.float64) + glcm_sums = np.sum(P, axis=(0, 1), keepdims=True) + glcm_sums[glcm_sums == 0] = 1 + P /= glcm_sums + + return P + + +def graycoprops(P, prop='contrast'): + """Calculate texture properties of a GLCM. + + Compute a feature of a gray level co-occurrence matrix to serve as + a compact summary of the matrix. The properties are computed as + follows: + + - 'contrast': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2` + - 'dissimilarity': :math:`\\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|` + - 'homogeneity': :math:`\\sum_{i,j=0}^{levels-1}\\frac{P_{i,j}}{1+(i-j)^2}` + - 'ASM': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}^2` + - 'energy': :math:`\\sqrt{ASM}` + - 'correlation': + .. math:: \\sum_{i,j=0}^{levels-1} P_{i,j}\\left[\\frac{(i-\\mu_i) \\ + (j-\\mu_j)}{\\sqrt{(\\sigma_i^2)(\\sigma_j^2)}}\\right] + - 'mean': :math:`\\sum_{i=0}^{levels-1} i*P_{i}` + - 'variance': :math:`\\sum_{i=0}^{levels-1} P_{i}*(i-mean)^2` + - 'std': :math:`\\sqrt{variance}` + - 'entropy': :math:`\\sum_{i,j=0}^{levels-1} -P_{i,j}*log(P_{i,j})` + + Each GLCM is normalized to have a sum of 1 before the computation of + texture properties. + + .. versionchanged:: 0.19 + `greycoprops` was renamed to `graycoprops` in 0.19. + + Parameters + ---------- + P : ndarray + Input array. `P` is the gray-level co-occurrence histogram + for which to compute the specified property. The value + `P[i,j,d,theta]` is the number of times that gray-level j + occurs at a distance d and at an angle theta from + gray-level i. + prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy', \ + 'correlation', 'ASM', 'mean', 'variance', 'std', 'entropy'}, optional + The property of the GLCM to compute. The default is 'contrast'. + + Returns + ------- + results : 2-D ndarray + 2-dimensional array. `results[d, a]` is the property 'prop' for + the d'th distance and the a'th angle. + + References + ---------- + .. [1] M. Hall-Beyer, 2007. GLCM Texture: A Tutorial v. 1.0 through 3.0. + The GLCM Tutorial Home Page, + https://prism.ucalgary.ca/handle/1880/51900 + DOI:`10.11575/PRISM/33280` + + Examples + -------- + Compute the contrast for GLCMs with distances [1, 2] and angles + [0 degrees, 90 degrees] + + >>> image = np.array([[0, 0, 1, 1], + ... [0, 0, 1, 1], + ... [0, 2, 2, 2], + ... [2, 2, 3, 3]], dtype=np.uint8) + >>> g = graycomatrix(image, [1, 2], [0, np.pi/2], levels=4, + ... normed=True, symmetric=True) + >>> contrast = graycoprops(g, 'contrast') + >>> contrast + array([[0.58333333, 1. ], + [1.25 , 2.75 ]]) + + """ + + def glcm_mean(): + I = np.arange(num_level).reshape((num_level, 1, 1, 1)) + mean = np.sum(I * P, axis=(0, 1)) + return I, mean + + check_nD(P, 4, 'P') + + (num_level, num_level2, num_dist, num_angle) = P.shape + if num_level != num_level2: + raise ValueError('num_level and num_level2 must be equal.') + if num_dist <= 0: + raise ValueError('num_dist must be positive.') + if num_angle <= 0: + raise ValueError('num_angle must be positive.') + + # normalize each GLCM + P = P.astype(np.float64) + glcm_sums = np.sum(P, axis=(0, 1), keepdims=True) + glcm_sums[glcm_sums == 0] = 1 + P /= glcm_sums + + # create weights for specified property + I, J = np.ogrid[0:num_level, 0:num_level] + if prop == 'contrast': + weights = (I - J) ** 2 + elif prop == 'dissimilarity': + weights = np.abs(I - J) + elif prop == 'homogeneity': + weights = 1.0 / (1.0 + (I - J) ** 2) + elif prop in ['ASM', 'energy', 'correlation', 'entropy', 'variance', 'mean', 'std']: + pass + else: + raise ValueError(f'{prop} is an invalid property') + + # compute property for each GLCM + if prop == 'energy': + asm = np.sum(P**2, axis=(0, 1)) + results = np.sqrt(asm) + elif prop == 'ASM': + results = np.sum(P**2, axis=(0, 1)) + elif prop == 'mean': + _, results = glcm_mean() + elif prop == 'variance': + I, mean = glcm_mean() + results = np.sum(P * ((I - mean) ** 2), axis=(0, 1)) + elif prop == 'std': + I, mean = glcm_mean() + var = np.sum(P * ((I - mean) ** 2), axis=(0, 1)) + results = np.sqrt(var) + elif prop == 'entropy': + ln = -np.log(P, where=(P != 0), out=np.zeros_like(P)) + results = np.sum(P * ln, axis=(0, 1)) + + elif prop == 'correlation': + results = np.zeros((num_dist, num_angle), dtype=np.float64) + I = np.array(range(num_level)).reshape((num_level, 1, 1, 1)) + J = np.array(range(num_level)).reshape((1, num_level, 1, 1)) + diff_i = I - np.sum(I * P, axis=(0, 1)) + diff_j = J - np.sum(J * P, axis=(0, 1)) + + std_i = np.sqrt(np.sum(P * (diff_i) ** 2, axis=(0, 1))) + std_j = np.sqrt(np.sum(P * (diff_j) ** 2, axis=(0, 1))) + cov = np.sum(P * (diff_i * diff_j), axis=(0, 1)) + + # handle the special case of standard deviations near zero + mask_0 = std_i < 1e-15 + mask_0[std_j < 1e-15] = True + results[mask_0] = 1 + + # handle the standard case + mask_1 = ~mask_0 + results[mask_1] = cov[mask_1] / (std_i[mask_1] * std_j[mask_1]) + elif prop in ['contrast', 'dissimilarity', 'homogeneity']: + weights = weights.reshape((num_level, num_level, 1, 1)) + results = np.sum(P * weights, axis=(0, 1)) + + return results + + +def local_binary_pattern(image, P, R, method='default'): + """Compute the local binary patterns (LBP) of an image. + + LBP is a visual descriptor often used in texture classification. + + Parameters + ---------- + image : (M, N) array + 2D grayscale image. + P : int + Number of circularly symmetric neighbor set points (quantization of + the angular space). + R : float + Radius of circle (spatial resolution of the operator). + method : str {'default', 'ror', 'uniform', 'nri_uniform', 'var'}, optional + Method to determine the pattern: + + ``default`` + Original local binary pattern which is grayscale invariant but not + rotation invariant. + ``ror`` + Extension of default pattern which is grayscale invariant and + rotation invariant. + ``uniform`` + Uniform pattern which is grayscale invariant and rotation + invariant, offering finer quantization of the angular space. + For details, see [1]_. + ``nri_uniform`` + Variant of uniform pattern which is grayscale invariant but not + rotation invariant. For details, see [2]_ and [3]_. + ``var`` + Variance of local image texture (related to contrast) + which is rotation invariant but not grayscale invariant. + + Returns + ------- + output : (M, N) array + LBP image. + + References + ---------- + .. [1] T. Ojala, M. Pietikainen, T. Maenpaa, "Multiresolution gray-scale + and rotation invariant texture classification with local binary + patterns", IEEE Transactions on Pattern Analysis and Machine + Intelligence, vol. 24, no. 7, pp. 971-987, July 2002 + :DOI:`10.1109/TPAMI.2002.1017623` + .. [2] T. Ahonen, A. Hadid and M. Pietikainen. "Face recognition with + local binary patterns", in Proc. Eighth European Conf. Computer + Vision, Prague, Czech Republic, May 11-14, 2004, pp. 469-481, 2004. + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851 + :DOI:`10.1007/978-3-540-24670-1_36` + .. [3] T. Ahonen, A. Hadid and M. Pietikainen, "Face Description with + Local Binary Patterns: Application to Face Recognition", + IEEE Transactions on Pattern Analysis and Machine Intelligence, + vol. 28, no. 12, pp. 2037-2041, Dec. 2006 + :DOI:`10.1109/TPAMI.2006.244` + """ + check_nD(image, 2) + + methods = { + 'default': ord('D'), + 'ror': ord('R'), + 'uniform': ord('U'), + 'nri_uniform': ord('N'), + 'var': ord('V'), + } + if np.issubdtype(image.dtype, np.floating): + warnings.warn( + "Applying `local_binary_pattern` to floating-point images may " + "give unexpected results when small numerical differences between " + "adjacent pixels are present. It is recommended to use this " + "function with images of integer dtype." + ) + image = np.ascontiguousarray(image, dtype=np.float64) + output = _local_binary_pattern(image, P, R, methods[method.lower()]) + return output + + +def multiblock_lbp(int_image, r, c, width, height): + """Multi-block local binary pattern (MB-LBP). + + The features are calculated similarly to local binary patterns (LBPs), + (See :py:meth:`local_binary_pattern`) except that summed blocks are + used instead of individual pixel values. + + MB-LBP is an extension of LBP that can be computed on multiple scales + in constant time using the integral image. Nine equally-sized rectangles + are used to compute a feature. For each rectangle, the sum of the pixel + intensities is computed. Comparisons of these sums to that of the central + rectangle determine the feature, similarly to LBP. + + Parameters + ---------- + int_image : (N, M) array + Integral image. + r : int + Row-coordinate of top left corner of a rectangle containing feature. + c : int + Column-coordinate of top left corner of a rectangle containing feature. + width : int + Width of one of the 9 equal rectangles that will be used to compute + a feature. + height : int + Height of one of the 9 equal rectangles that will be used to compute + a feature. + + Returns + ------- + output : int + 8-bit MB-LBP feature descriptor. + + References + ---------- + .. [1] L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. "Face Detection Based + on Multi-Block LBP Representation", In Proceedings: Advances in + Biometrics, International Conference, ICB 2007, Seoul, Korea. + http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf + :DOI:`10.1007/978-3-540-74549-5_2` + """ + + int_image = np.ascontiguousarray(int_image, dtype=np.float32) + lbp_code = _multiblock_lbp(int_image, r, c, width, height) + return lbp_code + + +def draw_multiblock_lbp( + image, + r, + c, + width, + height, + lbp_code=0, + color_greater_block=(1, 1, 1), + color_less_block=(0, 0.69, 0.96), + alpha=0.5, +): + """Multi-block local binary pattern visualization. + + Blocks with higher sums are colored with alpha-blended white rectangles, + whereas blocks with lower sums are colored alpha-blended cyan. Colors + and the `alpha` parameter can be changed. + + Parameters + ---------- + image : ndarray of float or uint + Image on which to visualize the pattern. + r : int + Row-coordinate of top left corner of a rectangle containing feature. + c : int + Column-coordinate of top left corner of a rectangle containing feature. + width : int + Width of one of 9 equal rectangles that will be used to compute + a feature. + height : int + Height of one of 9 equal rectangles that will be used to compute + a feature. + lbp_code : int + The descriptor of feature to visualize. If not provided, the + descriptor with 0 value will be used. + color_greater_block : tuple of 3 floats + Floats specifying the color for the block that has greater + intensity value. They should be in the range [0, 1]. + Corresponding values define (R, G, B) values. Default value + is white (1, 1, 1). + color_greater_block : tuple of 3 floats + Floats specifying the color for the block that has greater intensity + value. They should be in the range [0, 1]. Corresponding values define + (R, G, B) values. Default value is cyan (0, 0.69, 0.96). + alpha : float + Value in the range [0, 1] that specifies opacity of visualization. + 1 - fully transparent, 0 - opaque. + + Returns + ------- + output : ndarray of float + Image with MB-LBP visualization. + + References + ---------- + .. [1] L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. "Face Detection Based + on Multi-Block LBP Representation", In Proceedings: Advances in + Biometrics, International Conference, ICB 2007, Seoul, Korea. + http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf + :DOI:`10.1007/978-3-540-74549-5_2` + """ + + # Default colors for regions. + # White is for the blocks that are brighter. + # Cyan is for the blocks that has less intensity. + color_greater_block = np.asarray(color_greater_block, dtype=np.float64) + color_less_block = np.asarray(color_less_block, dtype=np.float64) + + # Copy array to avoid the changes to the original one. + output = np.copy(image) + + # As the visualization uses RGB color we need 3 bands. + if len(image.shape) < 3: + output = gray2rgb(image) + + # Colors are specified in floats. + output = img_as_float(output) + + # Offsets of neighbor rectangles relative to central one. + # It has order starting from top left and going clockwise. + neighbor_rect_offsets = ( + (-1, -1), + (-1, 0), + (-1, 1), + (0, 1), + (1, 1), + (1, 0), + (1, -1), + (0, -1), + ) + + # Pre-multiply the offsets with width and height. + neighbor_rect_offsets = np.array(neighbor_rect_offsets) + neighbor_rect_offsets[:, 0] *= height + neighbor_rect_offsets[:, 1] *= width + + # Top-left coordinates of central rectangle. + central_rect_r = r + height + central_rect_c = c + width + + for element_num, offset in enumerate(neighbor_rect_offsets): + offset_r, offset_c = offset + + curr_r = central_rect_r + offset_r + curr_c = central_rect_c + offset_c + + has_greater_value = lbp_code & (1 << (7 - element_num)) + + # Mix-in the visualization colors. + if has_greater_value: + new_value = (1 - alpha) * output[ + curr_r : curr_r + height, curr_c : curr_c + width + ] + alpha * color_greater_block + output[curr_r : curr_r + height, curr_c : curr_c + width] = new_value + else: + new_value = (1 - alpha) * output[ + curr_r : curr_r + height, curr_c : curr_c + width + ] + alpha * color_less_block + output[curr_r : curr_r + height, curr_c : curr_c + width] = new_value + + return output diff --git a/envs/kitoverlay/skimage/feature/util.py b/envs/kitoverlay/skimage/feature/util.py new file mode 100644 index 0000000000000000000000000000000000000000..72e6d292205ffde2ae38bf1c760dbcb32e4933ab --- /dev/null +++ b/envs/kitoverlay/skimage/feature/util.py @@ -0,0 +1,232 @@ +import numpy as np + +from ..util import img_as_float +from .._shared.utils import ( + _supported_float_type, + check_nD, +) + + +class FeatureDetector: + def __init__(self): + self.keypoints_ = np.array([]) + + def detect(self, image): + """Detect keypoints in image. + + Parameters + ---------- + image : 2D array + Input image. + + """ + raise NotImplementedError() + + +class DescriptorExtractor: + def __init__(self): + self.descriptors_ = np.array([]) + + def extract(self, image, keypoints): + """Extract feature descriptors in image for given keypoints. + + Parameters + ---------- + image : 2D array + Input image. + keypoints : (N, 2) array + Keypoint locations as ``(row, col)``. + + """ + raise NotImplementedError() + + +def plot_matched_features( + image0, + image1, + *, + keypoints0, + keypoints1, + matches, + ax, + keypoints_color='k', + matches_color=None, + only_matches=False, + alignment='horizontal', +): + """Plot matched features between two images. + + .. versionadded:: 0.23 + + Parameters + ---------- + image0 : (N, M [, 3]) array + First image. + image1 : (N, M [, 3]) array + Second image. + keypoints0 : (K1, 2) array + First keypoint coordinates as ``(row, col)``. + keypoints1 : (K2, 2) array + Second keypoint coordinates as ``(row, col)``. + matches : (Q, 2) array + Indices of corresponding matches in first and second sets of + descriptors, where `matches[:, 0]` (resp. `matches[:, 1]`) contains + the indices in the first (resp. second) set of descriptors. + ax : matplotlib.axes.Axes + The Axes object where the images and their matched features are drawn. + keypoints_color : matplotlib color, optional + Color for keypoint locations. + matches_color : matplotlib color or sequence thereof, optional + Single color or sequence of colors for each line defined by `matches`, + which connect keypoint matches. See [1]_ for an overview of supported + color formats. By default, colors are picked randomly. + only_matches : bool, optional + Set to True to plot matches only and not the keypoint locations. + alignment : {'horizontal', 'vertical'}, optional + Whether to show the two images side by side (`'horizontal'`), or one above + the other (`'vertical'`). + + References + ---------- + .. [1] https://matplotlib.org/stable/users/explain/colors/colors.html#specifying-colors + + Notes + ----- + To make a sequence of colors passed to `matches_color` work for any number of + `matches`, you can wrap that sequence in :func:`itertools.cycle`. + """ + image0 = img_as_float(image0) + image1 = img_as_float(image1) + + new_shape0 = list(image0.shape) + new_shape1 = list(image1.shape) + + if image0.shape[0] < image1.shape[0]: + new_shape0[0] = image1.shape[0] + elif image0.shape[0] > image1.shape[0]: + new_shape1[0] = image0.shape[0] + + if image0.shape[1] < image1.shape[1]: + new_shape0[1] = image1.shape[1] + elif image0.shape[1] > image1.shape[1]: + new_shape1[1] = image0.shape[1] + + if new_shape0 != image0.shape: + new_image0 = np.zeros(new_shape0, dtype=image0.dtype) + new_image0[: image0.shape[0], : image0.shape[1]] = image0 + image0 = new_image0 + + if new_shape1 != image1.shape: + new_image1 = np.zeros(new_shape1, dtype=image1.dtype) + new_image1[: image1.shape[0], : image1.shape[1]] = image1 + image1 = new_image1 + + offset = np.array(image0.shape) + if alignment == 'horizontal': + image = np.concatenate([image0, image1], axis=1) + offset[0] = 0 + elif alignment == 'vertical': + image = np.concatenate([image0, image1], axis=0) + offset[1] = 0 + else: + mesg = ( + f"`plot_matched_features` accepts either 'horizontal' or 'vertical' for " + f"alignment, but '{alignment}' was given. See " + f"https://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.plot_matched_features " + f"for details." + ) + raise ValueError(mesg) + + if not only_matches: + ax.scatter( + keypoints0[:, 1], + keypoints0[:, 0], + facecolors='none', + edgecolors=keypoints_color, + ) + ax.scatter( + keypoints1[:, 1] + offset[1], + keypoints1[:, 0] + offset[0], + facecolors='none', + edgecolors=keypoints_color, + ) + + ax.imshow(image, cmap='gray') + ax.axis((0, image0.shape[1] + offset[1], image0.shape[0] + offset[0], 0)) + + number_of_matches = matches.shape[0] + + from matplotlib.colors import is_color_like + + if matches_color is None: + rng = np.random.default_rng(seed=0) + colors = [rng.random(3) for _ in range(number_of_matches)] + elif is_color_like(matches_color): + colors = [matches_color for _ in range(number_of_matches)] + elif hasattr(matches_color, "__len__") and len(matches_color) == number_of_matches: + # No need to check each color, matplotlib does so for us + colors = matches_color + else: + error_message = ( + '`matches_color` needs to be a single color ' + 'or a sequence of length equal to the number of matches.' + ) + raise ValueError(error_message) + + for i, match in enumerate(matches): + idx0, idx1 = match + ax.plot( + (keypoints0[idx0, 1], keypoints1[idx1, 1] + offset[1]), + (keypoints0[idx0, 0], keypoints1[idx1, 0] + offset[0]), + '-', + color=colors[i], + ) + + +def _prepare_grayscale_input_2D(image): + image = np.squeeze(image) + check_nD(image, 2) + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + return image.astype(float_dtype, copy=False) + + +def _prepare_grayscale_input_nD(image): + image = np.squeeze(image) + check_nD(image, range(2, 6)) + image = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + return image.astype(float_dtype, copy=False) + + +def _mask_border_keypoints(image_shape, keypoints, distance): + """Mask coordinates that are within certain distance from the image border. + + Parameters + ---------- + image_shape : (2,) array_like + Shape of the image as ``(rows, cols)``. + keypoints : (N, 2) array + Keypoint coordinates as ``(rows, cols)``. + distance : int + Image border distance. + + Returns + ------- + mask : (N,) bool array + Mask indicating if pixels are within the image (``True``) or in the + border region of the image (``False``). + + """ + + rows = image_shape[0] + cols = image_shape[1] + + mask = ( + ((distance - 1) < keypoints[:, 0]) + & (keypoints[:, 0] < (rows - distance + 1)) + & ((distance - 1) < keypoints[:, 1]) + & (keypoints[:, 1] < (cols - distance + 1)) + ) + + return mask diff --git a/envs/kitoverlay/skimage/metrics/__init__.py b/envs/kitoverlay/skimage/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea6126c7dff9565c105cb3eb36408b8f9de38e1 --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/__init__.py @@ -0,0 +1,5 @@ +"""Metrics corresponding to images, e.g., distance metrics, similarity, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/metrics/__init__.pyi b/envs/kitoverlay/skimage/metrics/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f47fa2b97737e14e956a0c93f53b5ddc1cea0270 --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/__init__.pyi @@ -0,0 +1,28 @@ +# 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__ = [ + "adapted_rand_error", + "variation_of_information", + "contingency_table", + "mean_squared_error", + "normalized_mutual_information", + "normalized_root_mse", + "peak_signal_noise_ratio", + "structural_similarity", + "hausdorff_distance", + "hausdorff_pair", +] + +from ._adapted_rand_error import adapted_rand_error +from ._contingency_table import contingency_table +from ._structural_similarity import structural_similarity +from ._variation_of_information import variation_of_information +from .set_metrics import hausdorff_distance, hausdorff_pair +from .simple_metrics import ( + mean_squared_error, + normalized_mutual_information, + normalized_root_mse, + peak_signal_noise_ratio, +) diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5732b879cec1cc877bd1b94a4ea08c5cb1f6be6c Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/_adapted_rand_error.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/_adapted_rand_error.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30fba9a8a6c73f7cff39f7ccf91048e9f6c4e6ee Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/_adapted_rand_error.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/_contingency_table.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/_contingency_table.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85e1b452cfb23d811e710252952072514af113af Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/_contingency_table.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/_structural_similarity.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/_structural_similarity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..551b7dfc21a907671f3a65af48b56ebf5878b9ca Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/_structural_similarity.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/_variation_of_information.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/_variation_of_information.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1201bc8972f2c6beb1bda88d6581d402e9058c5 Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/_variation_of_information.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/set_metrics.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/set_metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..776e6a1309631fa614112fec8e1e7e7ae1a79c3f Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/set_metrics.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/__pycache__/simple_metrics.cpython-311.pyc b/envs/kitoverlay/skimage/metrics/__pycache__/simple_metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d35a02ce60a5da893ed07e33e0bc6d6c8d7aa48 Binary files /dev/null and b/envs/kitoverlay/skimage/metrics/__pycache__/simple_metrics.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/metrics/_adapted_rand_error.py b/envs/kitoverlay/skimage/metrics/_adapted_rand_error.py new file mode 100644 index 0000000000000000000000000000000000000000..c880a14f661cb562aa687b29ac9dde6b2e259c5c --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/_adapted_rand_error.py @@ -0,0 +1,103 @@ +from .._shared.utils import check_shape_equality +from ._contingency_table import contingency_table + +__all__ = ['adapted_rand_error'] + + +def adapted_rand_error( + image_true=None, image_test=None, *, table=None, ignore_labels=(0,), alpha=0.5 +): + r"""Compute Adapted Rand error as defined by the SNEMI3D contest. [1]_ + + Parameters + ---------- + image_true : ndarray of int + Ground-truth label image, same shape as im_test. + image_test : ndarray of int + Test image. + table : scipy.sparse array in crs format, optional + A contingency table built with skimage.evaluate.contingency_table. + If None, it will be computed on the fly. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + alpha : float, optional + Relative weight given to precision and recall in the adapted Rand error + calculation. + + Returns + ------- + are : float + The adapted Rand error. + prec : float + The adapted Rand precision: this is the number of pairs of pixels that + have the same label in the test label image *and* in the true image, + divided by the number in the test image. + rec : float + The adapted Rand recall: this is the number of pairs of pixels that + have the same label in the test label image *and* in the true image, + divided by the number in the true image. + + Notes + ----- + Pixels with label 0 in the true segmentation are ignored in the score. + + The adapted Rand error is calculated as follows: + + :math:`1 - \frac{\sum_{ij} p_{ij}^{2}}{\alpha \sum_{k} s_{k}^{2} + + (1-\alpha)\sum_{k} t_{k}^{2}}`, + where :math:`p_{ij}` is the probability that a pixel has the same label + in the test image *and* in the true image, :math:`t_{k}` is the + probability that a pixel has label :math:`k` in the true image, + and :math:`s_{k}` is the probability that a pixel has label :math:`k` + in the test image. + + Default behavior is to weight precision and recall equally in the + adapted Rand error calculation. + When alpha = 0, adapted Rand error = recall. + When alpha = 1, adapted Rand error = precision. + + + References + ---------- + .. [1] Arganda-Carreras I, Turaga SC, Berger DR, et al. (2015) + Crowdsourcing the creation of image segmentation algorithms + for connectomics. Front. Neuroanat. 9:142. + :DOI:`10.3389/fnana.2015.00142` + """ + if image_test is not None and image_true is not None: + check_shape_equality(image_true, image_test) + + if table is None: + p_ij = contingency_table( + image_true, + image_test, + ignore_labels=ignore_labels, + normalize=False, + sparse_type="array", + ) + else: + p_ij = table + + if alpha < 0.0 or alpha > 1.0: + raise ValueError('alpha must be between 0 and 1') + + # Sum of the joint distribution squared + sum_p_ij2 = p_ij.data @ p_ij.data - p_ij.sum() + + a_i = p_ij.sum(axis=1).ravel() + b_i = p_ij.sum(axis=0).ravel() + + # Sum of squares of the test segment sizes (this is 2x the number of pairs + # of pixels with the same label in im_test) + sum_a2 = a_i @ a_i - a_i.sum() + # Same for im_true + sum_b2 = b_i @ b_i - b_i.sum() + + precision = sum_p_ij2 / sum_a2 + recall = sum_p_ij2 / sum_b2 + + fscore = sum_p_ij2 / (alpha * sum_a2 + (1 - alpha) * sum_b2) + are = 1.0 - fscore + + return are, precision, recall diff --git a/envs/kitoverlay/skimage/metrics/_contingency_table.py b/envs/kitoverlay/skimage/metrics/_contingency_table.py new file mode 100644 index 0000000000000000000000000000000000000000..85860a09044a0128f616b6e9e2db766f4966ae23 --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/_contingency_table.py @@ -0,0 +1,51 @@ +import scipy.sparse as sparse +import numpy as np + +__all__ = ['contingency_table'] + + +def contingency_table( + im_true, im_test, *, ignore_labels=None, normalize=False, sparse_type="matrix" +): + """ + Return the contingency table for all regions in matched segmentations. + + Parameters + ---------- + im_true : ndarray of int + Ground-truth label image, same shape as im_test. + im_test : ndarray of int + Test image. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + normalize : bool + Determines if the contingency table is normalized by pixel count. + sparse_type : {"matrix", "array"}, optional + The return type of `cont`, either `scipy.sparse.csr_array` or + `scipy.sparse.csr_matrix` (default). + + Returns + ------- + cont : scipy.sparse.csr_matrix or scipy.sparse.csr_array + A contingency table. `cont[i, j]` will equal the number of voxels + labeled `i` in `im_true` and `j` in `im_test`. Depending on `sparse_type`, + this can be returned as a `scipy.sparse.csr_array`. + """ + + if ignore_labels is None: + ignore_labels = [] + im_test_r = im_test.reshape(-1) + im_true_r = im_true.reshape(-1) + data = np.isin(im_true_r, ignore_labels, invert=True).astype(float) + if normalize: + data /= np.count_nonzero(data) + cont = sparse.csr_array((data, (im_true_r, im_test_r))) + + if sparse_type == "matrix": + cont = sparse.csr_matrix(cont) + elif sparse_type != "array": + msg = f"`sparse_type` must be 'array' or 'matrix', got {sparse_type}" + raise ValueError(msg) + + return cont diff --git a/envs/kitoverlay/skimage/metrics/_structural_similarity.py b/envs/kitoverlay/skimage/metrics/_structural_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..e17d39330c79884a841120912d3a9f3c0b8a0ffc --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/_structural_similarity.py @@ -0,0 +1,292 @@ +import functools + +import numpy as np +from scipy.ndimage import uniform_filter + +from .._shared import utils +from .._shared.filters import gaussian +from .._shared.utils import _supported_float_type, check_shape_equality, warn +from ..util.arraycrop import crop +from ..util.dtype import dtype_range + +__all__ = ['structural_similarity'] + + +def structural_similarity( + im1, + im2, + *, + win_size=None, + gradient=False, + data_range=None, + channel_axis=None, + gaussian_weights=False, + full=False, + **kwargs, +): + """ + Compute the mean structural similarity index between two images. + Please pay attention to the `data_range` parameter with floating-point images. + + Parameters + ---------- + im1, im2 : ndarray + Images. Any dimensionality with same shape. + win_size : int or None, optional + The side-length of the sliding window used in comparison. Must be an + odd value. If `gaussian_weights` is True, this is ignored and the + window size will depend on `sigma`. + gradient : bool, optional + If True, also return the gradient with respect to im2. + data_range : float, optional + The data range of the input image (difference between maximum and + minimum possible values). By default, this is estimated from the image + data type. This estimate may be wrong for floating-point image data. + Therefore it is recommended to always pass this scalar value explicitly + (see note below). + 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. + gaussian_weights : bool, optional + If True, each patch has its mean and variance spatially weighted by a + normalized Gaussian kernel of width sigma=1.5. + full : bool, optional + If True, also return the full structural similarity image. + + Other Parameters + ---------------- + use_sample_covariance : bool + If True, normalize covariances by N-1 rather than, N where N is the + number of pixels within the sliding window. + K1 : float + Algorithm parameter, K1 (small constant, see [1]_). + K2 : float + Algorithm parameter, K2 (small constant, see [1]_). + sigma : float + Standard deviation for the Gaussian when `gaussian_weights` is True. + + Returns + ------- + mssim : float + The mean structural similarity index over the image. + grad : ndarray + The gradient of the structural similarity between im1 and im2 [2]_. + This is only returned if `gradient` is set to True. + S : ndarray + The full SSIM image. This is only returned if `full` is set to True. + + Notes + ----- + If `data_range` is not specified, the range is automatically guessed + based on the image data type. However for floating-point image data, this + estimate yields a result double the value of the desired range, as the + `dtype_range` in `skimage.util.dtype.py` has defined intervals from -1 to + +1. This yields an estimate of 2, instead of 1, which is most often + required when working with image data (as negative light intensities are + nonsensical). In case of working with YCbCr-like color data, note that + these ranges are different per channel (Cb and Cr have double the range + of Y), so one cannot calculate a channel-averaged SSIM with a single call + to this function, as identical ranges are assumed for each channel. + + To match the implementation of Wang et al. [1]_, set `gaussian_weights` + to True, `sigma` to 1.5, `use_sample_covariance` to False, and + specify the `data_range` argument. + + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_ssim`` to + ``skimage.metrics.structural_similarity``. + + References + ---------- + .. [1] Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. + (2004). Image quality assessment: From error visibility to + structural similarity. IEEE Transactions on Image Processing, + 13, 600-612. + https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf, + :DOI:`10.1109/TIP.2003.819861` + + .. [2] Avanaki, A. N. (2009). Exact global histogram specification + optimized for structural similarity. Optical Review, 16, 613-621. + :arxiv:`0901.0065` + :DOI:`10.1007/s10043-009-0119-z` + + """ + check_shape_equality(im1, im2) + float_type = _supported_float_type(im1.dtype) + + if channel_axis is not None: + # loop over channels + args = dict( + win_size=win_size, + gradient=gradient, + data_range=data_range, + channel_axis=None, + gaussian_weights=gaussian_weights, + full=full, + ) + args.update(kwargs) + nch = im1.shape[channel_axis] + mssim = np.empty(nch, dtype=float_type) + + if gradient: + G = np.empty(im1.shape, dtype=float_type) + if full: + S = np.empty(im1.shape, dtype=float_type) + channel_axis = channel_axis % im1.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + for ch in range(nch): + ch_result = structural_similarity(im1[_at(ch)], im2[_at(ch)], **args) + if gradient and full: + mssim[ch], G[_at(ch)], S[_at(ch)] = ch_result + elif gradient: + mssim[ch], G[_at(ch)] = ch_result + elif full: + mssim[ch], S[_at(ch)] = ch_result + else: + mssim[ch] = ch_result + mssim = mssim.mean() + if gradient and full: + return mssim, G, S + elif gradient: + return mssim, G + elif full: + return mssim, S + else: + return mssim + + K1 = kwargs.pop('K1', 0.01) + K2 = kwargs.pop('K2', 0.03) + sigma = kwargs.pop('sigma', 1.5) + if K1 < 0: + raise ValueError("K1 must be positive") + if K2 < 0: + raise ValueError("K2 must be positive") + if sigma < 0: + raise ValueError("sigma must be positive") + use_sample_covariance = kwargs.pop('use_sample_covariance', True) + + if gaussian_weights: + # Set to give an 11-tap filter with the default sigma of 1.5 to match + # Wang et. al. 2004. + truncate = 3.5 + + if win_size is None: + if gaussian_weights: + # set win_size used by crop to match the filter size + r = int(truncate * sigma + 0.5) # radius as in ndimage + win_size = 2 * r + 1 + else: + win_size = 7 # backwards compatibility + + if np.any((np.asarray(im1.shape) - win_size) < 0): + raise ValueError( + 'win_size exceeds image extent. ' + 'Either ensure that your images are ' + 'at least 7x7; or pass win_size explicitly ' + 'in the function call, with an odd value ' + 'less than or equal to the smaller side of your ' + 'images. If your images are multichannel ' + '(with color channels), set channel_axis to ' + 'the axis number corresponding to the channels.' + ) + + if not (win_size % 2 == 1): + raise ValueError('Window size must be odd.') + + if data_range is None: + if np.issubdtype(im1.dtype, np.floating) or np.issubdtype( + im2.dtype, np.floating + ): + raise ValueError( + 'Since image dtype is floating point, you must specify ' + 'the data_range parameter. Please read the documentation ' + 'carefully (including the note). It is recommended that ' + 'you always specify the data_range anyway.' + ) + if im1.dtype != im2.dtype: + warn( + "Inputs have mismatched dtypes. Setting data_range based on im1.dtype.", + stacklevel=2, + ) + dmin, dmax = dtype_range[im1.dtype.type] + data_range = dmax - dmin + if np.issubdtype(im1.dtype, np.integer) and (im1.dtype != np.uint8): + warn( + "Setting data_range based on im1.dtype. " + + f"data_range = {data_range:.0f}. " + + "Please specify data_range explicitly to avoid mistakes.", + stacklevel=2, + ) + + ndim = im1.ndim + + if gaussian_weights: + filter_func = gaussian + filter_args = {'sigma': sigma, 'truncate': truncate, 'mode': 'reflect'} + else: + filter_func = uniform_filter + filter_args = {'size': win_size} + + # ndimage filters need floating point data + im1 = im1.astype(float_type, copy=False) + im2 = im2.astype(float_type, copy=False) + + NP = win_size**ndim + + # filter has already normalized by NP + if use_sample_covariance: + cov_norm = NP / (NP - 1) # sample covariance + else: + cov_norm = 1.0 # population covariance to match Wang et. al. 2004 + + # compute (weighted) means + ux = filter_func(im1, **filter_args) + uy = filter_func(im2, **filter_args) + + # compute (weighted) variances and covariances + uxx = filter_func(im1 * im1, **filter_args) + uyy = filter_func(im2 * im2, **filter_args) + uxy = filter_func(im1 * im2, **filter_args) + vx = cov_norm * (uxx - ux * ux) + vy = cov_norm * (uyy - uy * uy) + vxy = cov_norm * (uxy - ux * uy) + + R = data_range + C1 = (K1 * R) ** 2 + C2 = (K2 * R) ** 2 + + A1, A2, B1, B2 = ( + 2 * ux * uy + C1, + 2 * vxy + C2, + ux**2 + uy**2 + C1, + vx + vy + C2, + ) + D = B1 * B2 + S = (A1 * A2) / D + + # to avoid edge effects will ignore filter radius strip around edges + pad = (win_size - 1) // 2 + + # compute (weighted) mean of ssim. Use float64 for accuracy. + mssim = crop(S, pad).mean(dtype=np.float64) + + if gradient: + # The following is Eqs. 7-8 of Avanaki 2009. + grad = filter_func(A1 / D, **filter_args) * im1 + grad += filter_func(-S / B2, **filter_args) * im2 + grad += filter_func((ux * (A2 - A1) - uy * (B2 - B1) * S) / D, **filter_args) + grad *= 2 / im1.size + + if full: + return mssim, grad, S + else: + return mssim, grad + else: + if full: + return mssim, S + else: + return mssim diff --git a/envs/kitoverlay/skimage/metrics/_variation_of_information.py b/envs/kitoverlay/skimage/metrics/_variation_of_information.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c546fcb739c4d9a479df778e443241cc66f1ed --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/_variation_of_information.py @@ -0,0 +1,133 @@ +import numpy as np +import scipy.sparse as sparse +from ._contingency_table import contingency_table +from .._shared.utils import check_shape_equality + +__all__ = ['variation_of_information'] + + +def variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=()): + """Return symmetric conditional entropies associated with the VI. [1]_ + + The variation of information is defined as VI(X,Y) = H(X|Y) + H(Y|X). + If X is the ground-truth segmentation, then H(X|Y) can be interpreted + as the amount of under-segmentation and H(Y|X) as the amount + of over-segmentation. In other words, a perfect over-segmentation + will have H(X|Y)=0 and a perfect under-segmentation will have H(Y|X)=0. + + Parameters + ---------- + image0, image1 : ndarray of int + Label images / segmentations, must have same shape. + table : scipy.sparse array in csr format, optional + A contingency table built with skimage.evaluate.contingency_table. + If None, it will be computed with skimage.evaluate.contingency_table. + If given, the entropies will be computed from this table and any images + will be ignored. + ignore_labels : sequence of int, optional + Labels to ignore. Any part of the true image labeled with any of these + values will not be counted in the score. + + Returns + ------- + vi : ndarray of float, shape (2,) + The conditional entropies of image1|image0 and image0|image1. + + References + ---------- + .. [1] Marina Meilă (2007), Comparing clusterings—an information based + distance, Journal of Multivariate Analysis, Volume 98, Issue 5, + Pages 873-895, ISSN 0047-259X, :DOI:`10.1016/j.jmva.2006.11.013`. + """ + h0g1, h1g0 = _vi_tables(image0, image1, table=table, ignore_labels=ignore_labels) + # false splits, false merges + return np.array([h1g0.sum(), h0g1.sum()]) + + +def _xlogx(x): + """Compute x * log_2(x). + + We define 0 * log_2(0) = 0 + + Parameters + ---------- + x : ndarray or scipy.sparse.csc_array or scipy.sparse.csr_array + The input array. + + Returns + ------- + y : same type as x + Result of x * log_2(x). + """ + y = x.copy() + if sparse.issparse(y) and y.format in ('csc', 'csr'): + z = y.data + else: + z = np.asarray(y) # ensure np.matrix converted to np.array + nz = z.nonzero() + z[nz] *= np.log2(z[nz]) + return y + + +def _vi_tables(im_true, im_test, table=None, ignore_labels=()): + """Compute probability tables used for calculating VI. + + Parameters + ---------- + im_true, im_test : ndarray of int + Input label images, any dimensionality. + table : csr_array, optional + Pre-computed contingency table. + ignore_labels : sequence of int, optional + Labels to ignore when computing scores. + + Returns + ------- + hxgy, hygx : ndarray of float + Per-segment conditional entropies of ``im_true`` given ``im_test`` and + vice-versa. + """ + check_shape_equality(im_true, im_test) + + if table is None: + # normalize, since it is an identity op if already done + pxy = contingency_table( + im_true, im_test, ignore_labels=ignore_labels, normalize=True + ) + + else: + pxy = table + + # compute marginal probabilities, converting to 1D array + px = np.ravel(pxy.sum(axis=1)) + py = np.ravel(pxy.sum(axis=0)) + + # use sparse matrix linear algebra to compute VI + # first, compute the inverse diagonal matrices + px_inv = sparse.dia_array((_invert_nonzero(px), 0), shape=(px.size, px.size)) + py_inv = sparse.dia_array((_invert_nonzero(py), 0), shape=(py.size, py.size)) + + # then, compute the entropies + hygx = -px @ _xlogx(px_inv @ pxy).sum(axis=1) + hxgy = -_xlogx(pxy @ py_inv).sum(axis=0) @ py + + return list(map(np.asarray, [hxgy, hygx])) + + +def _invert_nonzero(arr): + """Compute the inverse of the non-zero elements of arr, not changing 0. + + Parameters + ---------- + arr : ndarray + + Returns + ------- + arr_inv : ndarray + Array containing the inverse of the non-zero elements of arr, and + zero elsewhere. + """ + arr_inv = arr.copy() + nz = np.nonzero(arr) + arr_inv[nz] = 1 / arr[nz] + return arr_inv diff --git a/envs/kitoverlay/skimage/metrics/set_metrics.py b/envs/kitoverlay/skimage/metrics/set_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d2eb829b234f54087f9ba60d12579688ce9a1a77 --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/set_metrics.py @@ -0,0 +1,147 @@ +import warnings + +import numpy as np +from scipy.spatial import cKDTree + + +def hausdorff_distance(image0, image1, method="standard"): + """Calculate the Hausdorff distance between nonzero elements of given images. + + Parameters + ---------- + image0, image1 : ndarray + Arrays where ``True`` represents a point that is included in a + set of points. Both arrays must have the same shape. + method : {'standard', 'modified'}, optional, default = 'standard' + The method to use for calculating the Hausdorff distance. + ``standard`` is the standard Hausdorff distance, while ``modified`` + is the modified Hausdorff distance. + + Returns + ------- + distance : float + The Hausdorff distance between coordinates of nonzero pixels in + ``image0`` and ``image1``, using the Euclidean distance. + + Notes + ----- + The Hausdorff distance [1]_ is the maximum distance between any point on + ``image0`` and its nearest point on ``image1``, and vice-versa. + The Modified Hausdorff Distance (MHD) has been shown to perform better + than the directed Hausdorff Distance (HD) in the following work by + Dubuisson et al. [2]_. The function calculates forward and backward + mean distances and returns the largest of the two. + + References + ---------- + .. [1] http://en.wikipedia.org/wiki/Hausdorff_distance + .. [2] M. P. Dubuisson and A. K. Jain. A Modified Hausdorff distance for object + matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994. + :DOI:`10.1109/ICPR.1994.576361` + http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.1.8155 + + Examples + -------- + >>> points_a = (3, 0) + >>> points_b = (6, 0) + >>> shape = (7, 1) + >>> image_a = np.zeros(shape, dtype=bool) + >>> image_b = np.zeros(shape, dtype=bool) + >>> image_a[points_a] = True + >>> image_b[points_b] = True + >>> hausdorff_distance(image_a, image_b) + 3.0 + + """ + + if method not in ('standard', 'modified'): + raise ValueError(f'unrecognized method {method}') + + a_points = np.transpose(np.nonzero(image0)) + b_points = np.transpose(np.nonzero(image1)) + + # Handle empty sets properly: + # - if both sets are empty, return zero + # - if only one set is empty, return infinity + if len(a_points) == 0: + return 0 if len(b_points) == 0 else np.inf + elif len(b_points) == 0: + return np.inf + + fwd, bwd = ( + cKDTree(a_points).query(b_points, k=1)[0], + cKDTree(b_points).query(a_points, k=1)[0], + ) + + if method == 'standard': # standard Hausdorff distance + return max(max(fwd), max(bwd)) + elif method == 'modified': # modified Hausdorff distance + return max(np.mean(fwd), np.mean(bwd)) + + +def hausdorff_pair(image0, image1): + """Returns pair of points that are Hausdorff distance apart between nonzero + elements of given images. + + The Hausdorff distance [1]_ is the maximum distance between any point on + ``image0`` and its nearest point on ``image1``, and vice-versa. + + Parameters + ---------- + image0, image1 : ndarray + Arrays where ``True`` represents a point that is included in a + set of points. Both arrays must have the same shape. + + Returns + ------- + point_a, point_b : array + A pair of points that have Hausdorff distance between them. + + References + ---------- + .. [1] http://en.wikipedia.org/wiki/Hausdorff_distance + + Examples + -------- + >>> points_a = (3, 0) + >>> points_b = (6, 0) + >>> shape = (7, 1) + >>> image_a = np.zeros(shape, dtype=bool) + >>> image_b = np.zeros(shape, dtype=bool) + >>> image_a[points_a] = True + >>> image_b[points_b] = True + >>> hausdorff_pair(image_a, image_b) + (array([3, 0]), array([6, 0])) + + """ + a_points = np.transpose(np.nonzero(image0)) + b_points = np.transpose(np.nonzero(image1)) + + # If either of the sets are empty, there is no corresponding pair of points + if len(a_points) == 0 or len(b_points) == 0: + warnings.warn("One or both of the images is empty.", stacklevel=2) + return (), () + + nearest_dists_from_b, nearest_a_point_indices_from_b = cKDTree(a_points).query( + b_points + ) + nearest_dists_from_a, nearest_b_point_indices_from_a = cKDTree(b_points).query( + a_points + ) + + max_index_from_a = nearest_dists_from_b.argmax() + max_index_from_b = nearest_dists_from_a.argmax() + + max_dist_from_a = nearest_dists_from_b[max_index_from_a] + max_dist_from_b = nearest_dists_from_a[max_index_from_b] + + if max_dist_from_b > max_dist_from_a: + return ( + a_points[max_index_from_b], + b_points[nearest_b_point_indices_from_a[max_index_from_b]], + ) + else: + return ( + a_points[nearest_a_point_indices_from_b[max_index_from_a]], + b_points[max_index_from_a], + ) diff --git a/envs/kitoverlay/skimage/metrics/simple_metrics.py b/envs/kitoverlay/skimage/metrics/simple_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..08c9a66d454b8a5996bd77beb79988523b56af9a --- /dev/null +++ b/envs/kitoverlay/skimage/metrics/simple_metrics.py @@ -0,0 +1,275 @@ +import numpy as np +from scipy.stats import entropy + +from ..util._backends import dispatchable +from ..util.dtype import dtype_range +from .._shared.utils import _supported_float_type, check_shape_equality, warn + +__all__ = [ + 'mean_squared_error', + 'normalized_root_mse', + 'peak_signal_noise_ratio', + 'normalized_mutual_information', +] + + +def _as_floats(image0, image1): + """ + Promote im1, im2 to nearest appropriate floating point precision. + """ + float_type = _supported_float_type((image0.dtype, image1.dtype)) + image0 = np.asarray(image0, dtype=float_type) + image1 = np.asarray(image1, dtype=float_type) + return image0, image1 + + +@dispatchable +def mean_squared_error(image0, image1): + """ + Compute the mean-squared error between two images. + + Parameters + ---------- + image0, image1 : ndarray + Images. Any dimensionality, must have same shape. + + Returns + ------- + mse : float + The mean-squared error (MSE) metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_mse`` to + ``skimage.metrics.mean_squared_error``. + + """ + check_shape_equality(image0, image1) + image0, image1 = _as_floats(image0, image1) + return np.mean((image0 - image1) ** 2, dtype=np.float64) + + +@dispatchable +def normalized_root_mse(image_true, image_test, *, normalization='euclidean'): + """ + Compute the normalized root mean-squared error (NRMSE) between two + images. + + Parameters + ---------- + image_true : ndarray + Ground-truth image, same shape as im_test. + image_test : ndarray + Test image. + normalization : {'euclidean', 'min-max', 'mean'}, optional + Controls the normalization method to use in the denominator of the + NRMSE. There is no standard method of normalization across the + literature [1]_. The methods available here are as follows: + + - 'euclidean' : normalize by the averaged Euclidean norm of + ``im_true``:: + + NRMSE = RMSE * sqrt(N) / || im_true || + + where || . || denotes the Frobenius norm and ``N = im_true.size``. + This result is equivalent to:: + + NRMSE = || im_true - im_test || / || im_true ||. + + - 'min-max' : normalize by the intensity range of ``im_true``. + - 'mean' : normalize by the mean of ``im_true`` + + Returns + ------- + nrmse : float + The NRMSE metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_nrmse`` to + ``skimage.metrics.normalized_root_mse``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Root-mean-square_deviation + + """ + check_shape_equality(image_true, image_test) + image_true, image_test = _as_floats(image_true, image_test) + + # Ensure that both 'Euclidean' and 'euclidean' match + normalization = normalization.lower() + if normalization == 'euclidean': + denom = np.sqrt(np.mean((image_true * image_true), dtype=np.float64)) + elif normalization == 'min-max': + denom = image_true.max() - image_true.min() + elif normalization == 'mean': + denom = image_true.mean() + else: + raise ValueError("Unsupported norm_type") + return np.sqrt(mean_squared_error(image_true, image_test)) / denom + + +def peak_signal_noise_ratio(image_true, image_test, *, data_range=None): + """ + Compute the peak signal to noise ratio (PSNR) for an image. + + Parameters + ---------- + image_true : ndarray + Ground-truth image, same shape as im_test. + image_test : ndarray + Test image. + data_range : int, optional + The data range of the input image (distance between minimum and + maximum possible values). By default, this is estimated from the image + data-type. + + Returns + ------- + psnr : float + The PSNR metric. + + Notes + ----- + .. versionchanged:: 0.16 + This function was renamed from ``skimage.measure.compare_psnr`` to + ``skimage.metrics.peak_signal_noise_ratio``. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio + + """ + check_shape_equality(image_true, image_test) + + if data_range is None: + if image_true.dtype != image_test.dtype: + warn( + "Inputs have mismatched dtype. Setting data_range based on " + "image_true." + ) + dmin, dmax = dtype_range[image_true.dtype.type] + true_min, true_max = np.min(image_true), np.max(image_true) + if true_max > dmax or true_min < dmin: + raise ValueError( + "image_true has intensity values outside the range expected " + "for its data type. Please manually specify the data_range." + ) + if true_min >= 0: + # most common case (255 for uint8, 1 for float) + data_range = dmax + else: + data_range = dmax - dmin + + image_true, image_test = _as_floats(image_true, image_test) + + err = mean_squared_error(image_true, image_test) + data_range = float(data_range) # prevent overflow for small integer types + return 10 * np.log10((data_range**2) / err) + + +def _pad_to(arr, shape): + """Pad an array with trailing zeros to a given target shape. + + Parameters + ---------- + arr : ndarray + The input array. + shape : tuple + The target shape. + + Returns + ------- + padded : ndarray + The padded array. + + Examples + -------- + >>> _pad_to(np.ones((1, 1), dtype=int), (1, 3)) + array([[1, 0, 0]]) + """ + if not all(s >= i for s, i in zip(shape, arr.shape)): + raise ValueError( + f'Target shape {shape} cannot be smaller than input' + f'shape {arr.shape} along any axis.' + ) + padding = [(0, s - i) for s, i in zip(shape, arr.shape)] + return np.pad(arr, pad_width=padding, mode='constant', constant_values=0) + + +def normalized_mutual_information(image0, image1, *, bins=100): + r"""Compute the normalized mutual information (NMI). + + The normalized mutual information of :math:`A` and :math:`B` is given by: + + .. math:: + + Y(A, B) = \frac{H(A) + H(B)}{H(A, B)} + + where :math:`H(X) := - \sum_{x \in X}{p(x) \log p(x)}` is the entropy, + :math:`X` is the set of image values, and :math:`p(x)` is the probability + of occurrence of value :math:`x \in X`. + + It was proposed to be useful in registering images by Colin Studholme and + colleagues [1]_. It ranges from 1 (perfectly uncorrelated image values) + to 2 (perfectly correlated image values, whether positively or negatively). + + Parameters + ---------- + image0, image1 : ndarray + Images to be compared. The two input images must have the same number + of dimensions. + bins : int or sequence of int, optional + The number of bins along each axis of the joint histogram. + + Returns + ------- + nmi : float + The normalized mutual information between the two arrays, computed at + the granularity given by ``bins``. Higher NMI implies more similar + input images. + + Raises + ------ + ValueError + If the images don't have the same number of dimensions. + + Notes + ----- + If the two input images are not the same shape, the smaller image is padded + with zeros. + + References + ---------- + .. [1] C. Studholme, D.L.G. Hill, & D.J. Hawkes (1999). An overlap + invariant entropy measure of 3D medical image alignment. + Pattern Recognition 32(1):71-86 + :DOI:`10.1016/S0031-3203(98)00091-0` + """ + if image0.ndim != image1.ndim: + raise ValueError( + f'NMI requires images of same number of dimensions. ' + f'Got {image0.ndim}D for `image0` and ' + f'{image1.ndim}D for `image1`.' + ) + if image0.shape != image1.shape: + max_shape = np.maximum(image0.shape, image1.shape) + padded0 = _pad_to(image0, max_shape) + padded1 = _pad_to(image1, max_shape) + else: + padded0, padded1 = image0, image1 + + hist, bin_edges = np.histogramdd( + [np.reshape(padded0, -1), np.reshape(padded1, -1)], + bins=bins, + density=True, + ) + + H0 = entropy(np.sum(hist, axis=0)) + H1 = entropy(np.sum(hist, axis=1)) + H01 = entropy(np.reshape(hist, -1)) + + return (H0 + H1) / H01 diff --git a/envs/kitoverlay/skimage/morphology/_skeletonize.py b/envs/kitoverlay/skimage/morphology/_skeletonize.py new file mode 100644 index 0000000000000000000000000000000000000000..62e01f9685d510f13e0b202c9162f233fb296e8f --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/_skeletonize.py @@ -0,0 +1,655 @@ +""" +Algorithms for computing the skeleton of a binary image +""" + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD +from ..util import crop +from ._skeletonize_lee_cy import _compute_thin_image +from ._skeletonize_various_cy import ( + _fast_skeletonize, + _skeletonize_loop, + _table_lookup_index, +) + + +def skeletonize(image, *, method=None): + """Compute the skeleton of the input image via thinning. + + Parameters + ---------- + image : (M, N[, P]) ndarray of bool or int + The image containing the objects to be skeletonized. Each connected component + in the image is reduced to a single-pixel wide skeleton. The image is binarized + prior to thinning; thus, adjacent objects of different intensities are + considered as one. Zero or ``False`` values represent the background, nonzero + or ``True`` values -- foreground. + method : {'zhang', 'lee'}, optional + Which algorithm to use. Zhang's algorithm [Zha84]_ only works for + 2D images, and is the default for 2D. Lee's algorithm [Lee94]_ + works for 2D or 3D images and is the default for 3D. + + Returns + ------- + skeleton : (M, N[, P]) ndarray of bool + The thinned image. + + See Also + -------- + medial_axis + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + 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, 0, 1, 0, 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, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + image = image.astype(bool, order="C", copy=False) + + if method not in {'zhang', 'lee', None}: + raise ValueError( + f'skeletonize method should be either "lee" or "zhang", ' f'got {method}.' + ) + if image.ndim == 2 and (method is None or method == 'zhang'): + skeleton = _skeletonize_zhang(image) + elif image.ndim == 3 and method == 'zhang': + raise ValueError('skeletonize method "zhang" only works for 2D ' 'images.') + elif image.ndim == 3 or (image.ndim == 2 and method == 'lee'): + skeleton = _skeletonize_lee(image) + else: + raise ValueError( + f'skeletonize requires a 2D or 3D image as input, ' f'got {image.ndim}D.' + ) + return skeleton + + +def _skeletonize_zhang(image): + """Return the skeleton of a 2D binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : numpy.ndarray + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray + A matrix containing the thinned image. + + See Also + -------- + medial_axis, skeletonize, thin + + Notes + ----- + The algorithm [Zha84]_ works by making successive passes of the image, + removing pixels on object borders. This continues until no + more pixels can be removed. The image is correlated with a + mask that assigns each pixel a number in the range [0...255] + corresponding to each possible pattern of its 8 neighboring + pixels. A look up table is then used to assign the pixels a + value of 0, 1, 2 or 3, which are selectively removed during + the iterations. + + Note that this algorithm will give different results than a + medial axis transform, which is also often referred to as + "skeletonization". + + References + ---------- + .. [Zha84] A fast parallel algorithm for thinning digital patterns, + T. Y. Zhang and C. Y. Suen, Communications of the ACM, + March 1984, Volume 27, Number 3. + + Examples + -------- + >>> X, Y = np.ogrid[0:9, 0:9] + >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(bool) + >>> ellipse.view(np.uint8) + array([[0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) + >>> skel = skeletonize(ellipse) + >>> skel.view(np.uint8) + 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, 0, 1, 0, 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, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + if image.ndim != 2: + raise ValueError("Zhang's skeletonize method requires a 2D array") + return _fast_skeletonize(image) + + +# --------- Skeletonization and thinning based on Guo and Hall 1989 --------- + + +def _generate_thin_luts(): + """generate LUTs for thinning algorithm (for reference)""" + + def nabe(n): + return np.array([n >> i & 1 for i in range(0, 9)]).astype(bool) + + def G1(n): + s = 0 + bits = nabe(n) + for i in (0, 2, 4, 6): + if not (bits[i]) and (bits[i + 1] or bits[(i + 2) % 8]): + s += 1 + return s == 1 + + g1_lut = np.array([G1(n) for n in range(256)]) + + def G2(n): + n1, n2 = 0, 0 + bits = nabe(n) + for k in (1, 3, 5, 7): + if bits[k] or bits[k - 1]: + n1 += 1 + if bits[k] or bits[(k + 1) % 8]: + n2 += 1 + return min(n1, n2) in [2, 3] + + g2_lut = np.array([G2(n) for n in range(256)]) + + g12_lut = g1_lut & g2_lut + + def G3(n): + bits = nabe(n) + return not ((bits[1] or bits[2] or not (bits[7])) and bits[0]) + + def G3p(n): + bits = nabe(n) + return not ((bits[5] or bits[6] or not (bits[3])) and bits[4]) + + g3_lut = np.array([G3(n) for n in range(256)]) + g3p_lut = np.array([G3p(n) for n in range(256)]) + + g123_lut = g12_lut & g3_lut + g123p_lut = g12_lut & g3p_lut + + return g123_lut, g123p_lut + + +# fmt: off +G123_LUT = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=bool) + +G123P_LUT = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 1, 0, 1, 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, 1, 0, + 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 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, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, + 0, 1, 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], dtype=bool) +# fmt: on + + +def thin(image, max_num_iter=None): + """ + Perform morphological thinning of a binary image. + + Parameters + ---------- + image : binary (M, N) ndarray + The image to thin. If this input isn't already a binary image, + it gets converted into one: In this case, zero values are considered + background (False), nonzero values are considered foreground (True). + max_num_iter : int, number of iterations, optional + Regardless of the value of this parameter, the thinned image + is returned immediately if an iteration produces no change. + If this parameter is specified it thus sets an upper bound on + the number of iterations performed. + + Returns + ------- + out : ndarray of bool + Thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + This algorithm [1]_ works by making multiple passes over the image, + removing pixels matching a set of criteria designed to thin + connected regions while preserving eight-connected components and + 2 x 2 squares [2]_. In each of the two sub-iterations the algorithm + correlates the intermediate skeleton image with a neighborhood mask, + then looks up each neighborhood in a lookup table indicating whether + the central pixel should be deleted in that sub-iteration. + + References + ---------- + .. [1] Z. Guo and R. W. Hall, "Parallel thinning with + two-subiteration algorithms," Comm. ACM, vol. 32, no. 3, + pp. 359-373, 1989. :DOI:`10.1145/62065.62074` + .. [2] Lam, L., Seong-Whan Lee, and Ching Y. Suen, "Thinning + Methodologies-A Comprehensive Survey," IEEE Transactions on + Pattern Analysis and Machine Intelligence, Vol 14, No. 9, + p. 879, 1992. :DOI:`10.1109/34.161346` + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square[0, 1] = 1 + >>> square.view(np.uint8) + array([[0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> skel = thin(square) + >>> skel.view(np.uint8) + array([[0, 1, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + """ + # check that image is 2d + check_nD(image, 2) + + # convert image to uint8 with values in {0, 1} + skel = np.asanyarray(image, dtype=bool).copy().view(np.uint8) + + # neighborhood mask + mask = np.array([[8, 4, 2], [16, 0, 1], [32, 64, 128]], dtype=np.uint8) + + # iterate until convergence, up to the iteration limit + max_num_iter = max_num_iter or np.inf + num_iter = 0 + n_pts_old, n_pts_new = np.inf, np.sum(skel) + while n_pts_old != n_pts_new and num_iter < max_num_iter: + n_pts_old = n_pts_new + + # perform the two "subiterations" described in the paper + for lut in [G123_LUT, G123P_LUT]: + # correlate image with neighborhood mask + N = ndi.correlate(skel, mask, mode='constant') + # take deletion decision from this subiteration's LUT + D = np.take(lut, N) + # perform deletion + skel[D] = 0 + + n_pts_new = np.sum(skel) # count points after thinning + num_iter += 1 + + return skel.astype(bool) + + +# --------- Skeletonization by medial axis transform -------- + +_eight_connect = ndi.generate_binary_structure(2, 2) + + +def medial_axis(image, mask=None, return_distance=False, *, rng=None): + """Compute the medial axis transform of a binary image. + + Parameters + ---------- + image : binary ndarray, shape (M, N) + The image of the shape to skeletonize. If this input isn't already a + binary image, it gets converted into one: In this case, zero values are + considered background (False), nonzero values are considered + foreground (True). + mask : binary ndarray, shape (M, N), optional + If a mask is given, only those elements in `image` with a true + value in `mask` are used for computing the medial axis. + return_distance : bool, optional + If true, the distance transform is returned as well as the skeleton. + rng : {`numpy.random.Generator`, int}, optional + Pseudo-random number generator. + By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`). + If `rng` is an int, it is used to seed the generator. + + The PRNG determines the order in which pixels are processed for + tiebreaking. + + .. versionadded:: 0.19 + + Returns + ------- + out : ndarray of bools + Medial axis transform of the image + dist : ndarray of ints, optional + Distance transform of the image (only returned if `return_distance` + is True) + + See Also + -------- + skeletonize, thin + + Notes + ----- + This algorithm computes the medial axis transform of an image + as the ridges of its distance transform. + + The different steps of the algorithm are as follows + * A lookup table is used, that assigns 0 or 1 to each configuration of + the 3x3 binary square, whether the central pixel should be removed + or kept. We want a point to be removed if it has more than one neighbor + and if removing it does not change the number of connected components. + + * The distance transform to the background is computed, as well as + the cornerness of the pixel. + + * The foreground (value of 1) points are ordered by + the distance transform, then the cornerness. + + * A cython function is called to reduce the image to its skeleton. It + processes pixels in the order determined at the previous step, and + removes or maintains a pixel according to the lookup table. Because + of the ordering, it is possible to process all pixels in only one + pass. + + Examples + -------- + >>> square = np.zeros((7, 7), dtype=bool) + >>> square[1:-1, 2:-2] = 1 + >>> square.view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> medial_axis(square).view(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + + """ + global _eight_connect + if mask is None: + masked_image = image.astype(bool) + else: + masked_image = image.astype(bool).copy() + masked_image[~mask] = False + # + # Build lookup table - three conditions + # 1. Keep only positive pixels (center_is_foreground array). + # AND + # 2. Keep if removing the pixel results in a different connectivity + # (if the number of connected components is different with and + # without the central pixel) + # OR + # 3. Keep if # pixels in neighborhood is 2 or less + # Note that table is independent of image + center_is_foreground = (np.arange(512) & 2**4).astype(bool) + table = ( + center_is_foreground # condition 1. + & ( + np.array( + [ + ndi.label(_pattern_of(index), _eight_connect)[1] + != ndi.label(_pattern_of(index & ~(2**4)), _eight_connect)[1] + for index in range(512) + ] + ) # condition 2 + | np.array([np.sum(_pattern_of(index)) < 3 for index in range(512)]) + ) + # condition 3 + ) + + # Build distance transform + distance = ndi.distance_transform_edt(masked_image) + if return_distance: + store_distance = distance.copy() + + # Corners + # The processing order along the edge is critical to the shape of the + # resulting skeleton: if you process a corner first, that corner will + # be eroded and the skeleton will miss the arm from that corner. Pixels + # with fewer neighbors are more "cornery" and should be processed last. + # We use a cornerness_table lookup table where the score of a + # configuration is the number of background (0-value) pixels in the + # 3x3 neighborhood + cornerness_table = np.array( + [9 - np.sum(_pattern_of(index)) for index in range(512)] + ) + corner_score = _table_lookup(masked_image, cornerness_table) + + # Define arrays for inner loop + i, j = np.mgrid[0 : image.shape[0], 0 : image.shape[1]] + result = masked_image.copy() + distance = distance[result] + i = np.ascontiguousarray(i[result], dtype=np.intp) + j = np.ascontiguousarray(j[result], dtype=np.intp) + result = np.ascontiguousarray(result, np.uint8) + + # Determine the order in which pixels are processed. + # We use a random # for tiebreaking. Assign each pixel in the image a + # predictable, random # so that masking doesn't affect arbitrary choices + # of skeletons + # + generator = np.random.default_rng(rng) + tiebreaker = generator.permutation(np.arange(masked_image.sum())) + order = np.lexsort((tiebreaker, corner_score[masked_image], distance)) + order = np.ascontiguousarray(order, dtype=np.int32) + + table = np.ascontiguousarray(table, dtype=np.uint8) + # Remove pixels not belonging to the medial axis + _skeletonize_loop(result, i, j, order, table) + + result = result.astype(bool) + if mask is not None: + result[~mask] = image[~mask] + if return_distance: + return result, store_distance + else: + return result + + +def _pattern_of(index): + """ + Return the pattern represented by an index value + Byte decomposition of index + """ + return np.array( + [ + [index & 2**0, index & 2**1, index & 2**2], + [index & 2**3, index & 2**4, index & 2**5], + [index & 2**6, index & 2**7, index & 2**8], + ], + bool, + ) + + +def _table_lookup(image, table): + """ + Perform a morphological transform on an image, directed by its + neighbors + + Parameters + ---------- + image : ndarray + A binary image + table : ndarray + A 512-element table giving the transform of each pixel given + the values of that pixel and its 8-connected neighbors. + + Returns + ------- + result : ndarray of same shape as `image` + Transformed image + + Notes + ----- + The pixels are numbered like this:: + + 0 1 2 + 3 4 5 + 6 7 8 + + The index at a pixel is the sum of 2** for pixels + that evaluate to true. + """ + # + # We accumulate into the indexer to get the index into the table + # at each point in the image + # + if image.shape[0] < 3 or image.shape[1] < 3: + image = image.astype(bool) + indexer = np.zeros(image.shape, int) + indexer[1:, 1:] += image[:-1, :-1] * 2**0 + indexer[1:, :] += image[:-1, :] * 2**1 + indexer[1:, :-1] += image[:-1, 1:] * 2**2 + + indexer[:, 1:] += image[:, :-1] * 2**3 + indexer[:, :] += image[:, :] * 2**4 + indexer[:, :-1] += image[:, 1:] * 2**5 + + indexer[:-1, 1:] += image[1:, :-1] * 2**6 + indexer[:-1, :] += image[1:, :] * 2**7 + indexer[:-1, :-1] += image[1:, 1:] * 2**8 + else: + indexer = _table_lookup_index(np.ascontiguousarray(image, np.uint8)) + image = table[indexer] + return image + + +def _skeletonize_lee(image): + """Compute the skeleton of a binary image. + + Thinning is used to reduce each connected component in a binary image + to a single-pixel wide skeleton. + + Parameters + ---------- + image : ndarray, 2D or 3D + An image containing the objects to be skeletonized. Zeros or ``False`` + represent background, nonzero values or ``True`` are foreground. + + Returns + ------- + skeleton : ndarray of bool + The thinned image. + + See Also + -------- + skeletonize, medial_axis + + Notes + ----- + The method of [Lee94]_ uses an octree data structure to examine a 3x3x3 + neighborhood of a pixel. The algorithm proceeds by iteratively sweeping + over the image, and removing pixels at each iteration until the image + stops changing. Each iteration consists of two steps: first, a list of + candidates for removal is assembled; then pixels from this list are + rechecked sequentially, to better preserve connectivity of the image. + + The algorithm this function implements is different from the algorithms + used by either `skeletonize` or `medial_axis`, thus for 2D images the + results produced by this function are generally different. + + References + ---------- + .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models + via 3-D medial surface/axis thinning algorithms. + Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. + + """ + # make sure the image is 3D or 2D + if image.ndim < 2 or image.ndim > 3: + raise ValueError( + "skeletonize can only handle 2D or 3D images; " + f"got image.ndim = {image.ndim} instead." + ) + + image_o = image.astype(bool, order="C", copy=False) + + # make a 2D input image 3D and pad it w/ zeros to simplify dealing w/ boundaries + # NB: careful here to not clobber the original *and* minimize copying + if image.ndim == 2: + image_o = image_o[np.newaxis, ...] + image_o = np.pad(image_o, pad_width=1, mode='constant') # copies + + # do the computation + image_o = _compute_thin_image(image_o) + + # crop it back and restore the original intensity range + image_o = crop(image_o, crop_width=1) + if image.ndim == 2: + image_o = image_o[0] + + return image_o diff --git a/envs/kitoverlay/skimage/morphology/_util.py b/envs/kitoverlay/skimage/morphology/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..bcdfdb643e08b95f2d6a36ef1719991180353113 --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/_util.py @@ -0,0 +1,328 @@ +"""Utility functions used in the morphology subpackage.""" + +import numpy as np +from scipy import ndimage as ndi + + +def _validate_connectivity(image_dim, connectivity, offset): + """Convert any valid connectivity to a footprint and offset. + + Parameters + ---------- + image_dim : int + The number of dimensions of the input image. + connectivity : int, array, or None + The neighborhood connectivity. An integer is interpreted as in + ``scipy.ndimage.generate_binary_structure``, as the maximum number + of orthogonal steps to reach a neighbor. An array is directly + interpreted as a footprint and its shape is validated against + the input image shape. ``None`` is interpreted as a connectivity of 1. + offset : tuple of int, or None + The coordinates of the center of the footprint. + + Returns + ------- + c_connectivity : array of bool + The footprint (structuring element) corresponding to the input + `connectivity`. + offset : array of int + The offset corresponding to the center of the footprint. + + Raises + ------ + ValueError: + If the image dimension and the connectivity or offset dimensions don't + match. + """ + if connectivity is None: + connectivity = 1 + + if np.isscalar(connectivity): + c_connectivity = ndi.generate_binary_structure(image_dim, connectivity) + else: + c_connectivity = np.array(connectivity, bool) + if c_connectivity.ndim != image_dim: + raise ValueError("Connectivity dimension must be same as image") + + if offset is None: + if any([x % 2 == 0 for x in c_connectivity.shape]): + raise ValueError("Connectivity array must have an unambiguous " "center") + + offset = np.array(c_connectivity.shape) // 2 + + return c_connectivity, offset + + +def _raveled_offsets_and_distances( + image_shape, + *, + footprint=None, + connectivity=1, + center=None, + spacing=None, + order='C', +): + """Compute offsets to neighboring pixels in raveled coordinate space. + + This function also returns the corresponding distances from the center + pixel given a spacing (assumed to be 1 along each axis by default). + + Parameters + ---------- + image_shape : tuple of int + The shape of the image for which the offsets are being computed. + footprint : array of bool + The footprint of the neighborhood, expressed as an n-dimensional array + of 1s and 0s. If provided, the connectivity argument is ignored. + connectivity : {1, ..., ndim} + The square connectivity of the neighborhood: the number of orthogonal + steps allowed to consider a pixel a neighbor. See + `scipy.ndimage.generate_binary_structure`. Ignored if footprint is + provided. + center : tuple of int + Tuple of indices to the center of the footprint. If not provided, it + is assumed to be the center of the footprint, either provided or + generated by the connectivity argument. + spacing : tuple of float + The spacing between pixels/voxels along each axis. + order : 'C' or 'F' + The ordering of the array, either C or Fortran ordering. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + distances : ndarray + The pixel distances corresponding to each offset. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> off, d = _raveled_offsets_and_distances( + ... (4, 5), footprint=np.ones((4, 3)), center=(1, 1) + ... ) + >>> off + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> d[0] + 1.0 + >>> d[-1] # distance from (1, 1) to (3, 2) + 2.236... + """ + ndim = len(image_shape) + if footprint is None: + footprint = ndi.generate_binary_structure(rank=ndim, connectivity=connectivity) + if center is None: + center = tuple(s // 2 for s in footprint.shape) + + if not footprint.ndim == ndim == len(center): + raise ValueError( + "number of dimensions in image shape, footprint and its" + "center index does not match" + ) + + offsets = np.stack( + [(idx - c) for idx, c in zip(np.nonzero(footprint), center)], axis=-1 + ) + + if order == 'F': + offsets = offsets[:, ::-1] + image_shape = image_shape[::-1] + elif order != 'C': + raise ValueError("order must be 'C' or 'F'") + + # Scale offsets in each dimension and sum + ravel_factors = image_shape[1:] + (1,) + ravel_factors = np.cumprod(ravel_factors[::-1])[::-1] + raveled_offsets = (offsets * ravel_factors).sum(axis=1) + + # Sort by distance + if spacing is None: + spacing = np.ones(ndim) + weighted_offsets = offsets * spacing + distances = np.sqrt(np.sum(weighted_offsets**2, axis=1)) + sorted_raveled_offsets = raveled_offsets[np.argsort(distances, kind="stable")] + sorted_distances = np.sort(distances, kind="stable") + + # If any dimension in image_shape is smaller than footprint.shape + # duplicates might occur, remove them + if any(x < y for x, y in zip(image_shape, footprint.shape)): + # np.unique reorders, which we don't want + _, indices = np.unique(sorted_raveled_offsets, return_index=True) + indices = np.sort(indices, kind="stable") + sorted_raveled_offsets = sorted_raveled_offsets[indices] + sorted_distances = sorted_distances[indices] + + # Remove "offset to center" + sorted_raveled_offsets = sorted_raveled_offsets[1:] + sorted_distances = sorted_distances[1:] + + return sorted_raveled_offsets, sorted_distances + + +def _offsets_to_raveled_neighbors(image_shape, footprint, center, order='C'): + """Compute offsets to a samples neighbors if the image would be raveled. + + Parameters + ---------- + image_shape : tuple + The shape of the image for which the offsets are computed. + footprint : ndarray + The footprint (structuring element) determining the neighborhood + expressed as an n-D array of 1's and 0's. + center : tuple + Tuple of indices to the center of `footprint`. + order : {"C", "F"}, optional + Whether the image described by `image_shape` is in row-major (C-style) + or column-major (Fortran-style) order. + + Returns + ------- + raveled_offsets : ndarray + Linear offsets to a samples neighbors in the raveled image, sorted by + their distance from the center. + + Notes + ----- + This function will return values even if `image_shape` contains a dimension + length that is smaller than `footprint`. + + Examples + -------- + >>> _offsets_to_raveled_neighbors((4, 5), np.ones((4, 3)), (1, 1)) + array([-5, -1, 1, 5, -6, -4, 4, 6, 10, 9, 11]) + >>> _offsets_to_raveled_neighbors((2, 3, 2), np.ones((3, 3, 3)), (1, 1, 1)) + array([-6, -2, -1, 1, 2, 6, -8, -7, -5, -4, -3, 3, 4, 5, 7, 8, -9, + 9]) + """ + raveled_offsets = _raveled_offsets_and_distances( + image_shape, footprint=footprint, center=center, order=order + )[0] + + return raveled_offsets + + +def _resolve_neighborhood(footprint, connectivity, ndim, enforce_adjacency=True): + """Validate or create a footprint (structuring element). + + Depending on the values of `connectivity` and `footprint` this function + either creates a new footprint (`footprint` is None) using `connectivity` + or validates the given footprint (`footprint` is not None). + + Parameters + ---------- + footprint : ndarray + The footprint (structuring) element used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + connectivity : int + 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. + ndim : int + Number of dimensions `footprint` ought to have. + enforce_adjacency : bool + A boolean that determines whether footprint must only specify direct + neighbors. + + Returns + ------- + footprint : ndarray + Validated or new footprint specifying the neighborhood. + + Examples + -------- + >>> _resolve_neighborhood(None, 1, 2) + array([[False, True, False], + [ True, True, True], + [False, True, False]]) + >>> _resolve_neighborhood(None, None, 3).shape + (3, 3, 3) + """ + if footprint is None: + if connectivity is None: + connectivity = ndim + footprint = ndi.generate_binary_structure(ndim, connectivity) + else: + # Validate custom structured element + footprint = np.asarray(footprint, dtype=bool) + # Must specify neighbors for all dimensions + if footprint.ndim != ndim: + raise ValueError( + "number of dimensions in image and footprint do not" "match" + ) + # Must only specify direct neighbors + if enforce_adjacency and any(s != 3 for s in footprint.shape): + raise ValueError("dimension size in footprint is not 3") + elif any((s % 2 != 1) for s in footprint.shape): + raise ValueError("footprint size must be odd along all dimensions") + + return footprint + + +def _set_border_values(image, value, border_width=1): + """Set edge values along all axes to a constant value. + + Parameters + ---------- + image : ndarray + The array to modify inplace. + value : scalar + The value to use. Should be compatible with `image`'s dtype. + border_width : int or sequence of tuples + A sequence with one 2-tuple per axis where the first and second values + are the width of the border at the start and end of the axis, + respectively. If an int is provided, a uniform border width along all + axes is used. + + Examples + -------- + >>> image = np.zeros((4, 5), dtype=int) + >>> _set_border_values(image, 1) + >>> image + array([[1, 1, 1, 1, 1], + [1, 0, 0, 0, 1], + [1, 0, 0, 0, 1], + [1, 1, 1, 1, 1]]) + >>> image = np.zeros((8, 8), dtype=int) + >>> _set_border_values(image, 1, border_width=((1, 1), (2, 3))) + >>> image + array([[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 0, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1]]) + """ + if np.isscalar(border_width): + border_width = ((border_width, border_width),) * image.ndim + elif len(border_width) != image.ndim: + raise ValueError('length of `border_width` must match image.ndim') + for axis, npad in enumerate(border_width): + if len(npad) != 2: + raise ValueError('each sequence in `border_width` must have ' 'length 2') + w_start, w_end = npad + if w_start == w_end == 0: + continue + elif w_start == w_end == 1: + # Index first and last element in the current dimension + sl = (slice(None),) * axis + ((0, -1),) + (...,) + image[sl] = value + continue + if w_start > 0: + # set first w_start entries along axis to value + sl = (slice(None),) * axis + (slice(0, w_start),) + (...,) + image[sl] = value + if w_end > 0: + # set last w_end entries along axis to value + sl = (slice(None),) * axis + (slice(-w_end, None),) + (...,) + image[sl] = value diff --git a/envs/kitoverlay/skimage/morphology/extrema.py b/envs/kitoverlay/skimage/morphology/extrema.py new file mode 100644 index 0000000000000000000000000000000000000000..a87cef0c0a2e335bf6bfe773c0660a9f6451ba0a --- /dev/null +++ b/envs/kitoverlay/skimage/morphology/extrema.py @@ -0,0 +1,549 @@ +"""extrema.py - local minima and maxima + +This module provides functions to find local maxima and minima of an image. +Here, local maxima (minima) are defined as connected sets of pixels with equal +gray level which is strictly greater (smaller) than the gray level of all +pixels in direct neighborhood of the connected set. In addition, the module +provides the related functions h-maxima and h-minima. + +Soille, P. (2003). Morphological Image Analysis: Principles and Applications +(2nd ed.), Chapter 6. Springer-Verlag New York, Inc. +""" + +import numpy as np + +from .._shared.utils import warn +from ..util import dtype_limits, invert, crop +from . import grayreconstruct, _util +from ._extrema_cy import _local_maxima + + +def _add_constant_clip(image, const_value): + """Add constant to the image while handling overflow issues gracefully.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The added constant is not compatible" "with the image data type." + ) + + result = image + const_value + result[image > max_dtype - const_value] = max_dtype + return result + + +def _subtract_constant_clip(image, const_value): + """Subtract constant from image while handling underflow issues.""" + min_dtype, max_dtype = dtype_limits(image, clip_negative=False) + + if const_value > (max_dtype - min_dtype): + raise ValueError( + "The subtracted constant is not compatible" "with the image data type." + ) + + result = image - const_value + result[image < (const_value + min_dtype)] = min_dtype + return result + + +def h_maxima(image, h, footprint=None): + """Determine all maxima of the image with height >= h. + + The local maxima are defined as connected sets of pixels with equal + gray level strictly greater than the gray level of all pixels in direct + neighborhood of the set. + + A local maximum M of height h is a local maximum for which + there is at least one path joining M with an equal or higher local maximum + on which the minimal value is f(M) - h (i.e. the values along the path + are not decreasing by more than h with respect to the maximum's value) + and no path to an equal or higher local maximum for which the minimal + value is greater. + + The global maxima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the maxima are to be calculated. + h : unsigned integer + The minimal height of all extracted maxima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_max : ndarray + The local maxima of height >= h and the global maxima. + The resulting image is a binary image, where pixels belonging to + the determined maxima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_minima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a maximum in the center and + 4 additional constant maxima. + The heights of the maxima are: 1, 21, 41, 61, 81 + + >>> 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 maxima with a height of at least 40: + + >>> maxima = extrema.h_maxima(f, 40) + + The resulting image will contain 3 local maxima. + """ + + # Check for h value that is larger then range of the image. If this + # is True then there are no h-maxima in the image. + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + # Check for floating point h value. For this to work properly + # we need to explicitly convert image to float64. + # + # FIXME: This could give incorrect results if image is int64 and + # has a very high dynamic range. The dtype of image is + # changed to float64, and different integer values could + # become the same float due to rounding. + # + # >>> ii64 = np.iinfo(np.int64) + # >>> a = np.array([ii64.max, ii64.max - 2]) + # >>> a[0] == a[1] + # False + # >>> b = a.astype(np.float64) + # >>> b[0] == b[1] + # True + # + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_maxima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + # The purpose of the resolution variable is to allow for the + # small rounding errors that inevitably occur when doing + # floating point arithmetic. We want shifted_img to be + # guaranteed to be h less than image. If we only subtract h + # there may be pixels were shifted_img ends up being + # slightly greater than image - h. + # + # The resolution is scaled based on the pixel values in the + # image because floating point precision is relative. A + # very large value of 1.0e10 will have a large precision, + # say +-1.0e4, and a very small value of 1.0e-10 will have + # a very small precision, say +-1.0e-16. + # + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image - h - resolution + else: + shifted_img = _subtract_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='dilation', footprint=footprint + ) + residue_img = image - rec_img + return (residue_img >= h).astype(np.uint8) + + +def h_minima(image, h, footprint=None): + """Determine all minima of the image with depth >= h. + + The local minima are defined as connected sets of pixels with equal + gray level strictly smaller than the gray levels of all pixels in direct + neighborhood of the set. + + A local minimum M of depth h is a local minimum for which + there is at least one path joining M with an equal or lower local minimum + on which the maximal value is f(M) + h (i.e. the values along the path + are not increasing by more than h with respect to the minimum's value) + and no path to an equal or lower local minimum for which the maximal + value is smaller. + + The global minima of the image are also found by this function. + + Parameters + ---------- + image : ndarray + The input image for which the minima are to be calculated. + h : unsigned integer + The minimal depth of all extracted minima. + footprint : ndarray, optional + The neighborhood expressed as an n-D array of 1's and 0's. + Default is the ball of radius 1 according to the maximum norm + (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) + + Returns + ------- + h_min : ndarray + The local minima of depth >= h and the global minima. + The resulting image is a binary image, where pixels belonging to + the determined minima take value 1, the others take value 0. + + See Also + -------- + skimage.morphology.h_maxima + skimage.morphology.local_maxima + skimage.morphology.local_minima + + References + ---------- + .. [1] Soille, P., "Morphological Image Analysis: Principles and + Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883. + + Examples + -------- + >>> import numpy as np + >>> from skimage.morphology import extrema + + We create an image (quadratic function with a minimum in the center and + 4 additional constant maxima. + The depth of the minima are: 1, 21, 41, 61, 81 + + >>> w = 10 + >>> x, y = np.mgrid[0:w,0:w] + >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) + >>> f[2:4,2:4] = 160; f[2:4,7:9] = 140; f[7:9,2:4] = 120; f[7:9,7:9] = 100 + >>> f = f.astype(int) + + We can calculate all minima with a depth of at least 40: + + >>> minima = extrema.h_minima(f, 40) + + The resulting image will contain 3 local minima. + """ + if h > np.ptp(image): + return np.zeros(image.shape, dtype=np.uint8) + + if np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer): + if (h % 1) != 0: + warn( + 'possible precision loss converting image to ' + 'floating point. To silence this warning, ' + 'ensure image and h have same data type.', + stacklevel=2, + ) + image = image.astype(float) + else: + h = image.dtype.type(h) + + if h == 0: + raise ValueError("h = 0 is ambiguous, use local_minima() " "instead?") + + if np.issubdtype(image.dtype, np.floating): + resolution = 2 * np.finfo(image.dtype).resolution * np.abs(image) + shifted_img = image + h + resolution + else: + shifted_img = _add_constant_clip(image, h) + + rec_img = grayreconstruct.reconstruction( + shifted_img, image, method='erosion', footprint=footprint + ) + residue_img = rec_img - image + return (residue_img >= h).astype(np.uint8) + + +def local_maxima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local maxima of n-dimensional array. + + The local maxima are defined as connected sets of pixels with equal gray + level (plateaus) strictly greater than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + 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. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local maxima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid maxima. + + Returns + ------- + maxima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local maxima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found maxima. + + Warns + ----- + UserWarning + If `allow_borders` is false and any dimension of the given `image` is + shorter than 3 samples, maxima can't exist and a warning is shown. + + See Also + -------- + skimage.morphology.local_minima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local maxima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a higher gray level, mark the plateau as a definite local maximum. + + Examples + -------- + >>> from skimage.morphology import local_maxima + >>> 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]]) + + Find local maxima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_maxima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_maxima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local maxima without comparing to diagonal pixels (connectivity 1): + + >>> local_maxima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude maxima that border the image edge: + + >>> local_maxima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + image = np.asarray(image, order="C") + if image.size == 0: + # Return early for empty input + if indices: + # Make sure that output is a tuple of 1 empty array per dimension + return np.nonzero(image) + else: + return np.zeros(image.shape, dtype=bool) + + if allow_borders: + # Ensure that local maxima are always at least one smaller sample away + # from the image border + image = np.pad(image, 1, mode='constant', constant_values=image.min()) + + # Array of flags used to store the state of each pixel during evaluation. + # See _extrema_cy.pyx for their meaning + flags = np.zeros(image.shape, dtype=np.uint8) + _util._set_border_values(flags, value=3) + + if any(s < 3 for s in image.shape): + # Warn and skip if any dimension is smaller than 3 + # -> no maxima can exist & footprint can't be applied + warn( + "maxima can't exist for an image with any dimension smaller 3 " + "if borders aren't allowed", + stacklevel=3, + ) + else: + footprint = _util._resolve_neighborhood(footprint, connectivity, image.ndim) + neighbor_offsets = _util._offsets_to_raveled_neighbors( + image.shape, footprint, center=((1,) * image.ndim) + ) + + try: + _local_maxima(image.ravel(), flags.ravel(), neighbor_offsets) + except TypeError: + if 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 # Otherwise raise original message + + if allow_borders: + # Revert padding performed at the beginning of the function + flags = crop(flags, 1) + else: + # No padding was performed but set edge values back to 0 + _util._set_border_values(flags, value=0) + + if indices: + return np.nonzero(flags) + else: + return flags.view(bool) + + +def local_minima( + image, footprint=None, connectivity=None, indices=False, allow_borders=True +): + """Find local minima of n-dimensional array. + + The local minima are defined as connected sets of pixels with equal gray + level (plateaus) strictly smaller than the gray levels of all pixels in the + neighborhood. + + Parameters + ---------- + image : ndarray + An n-dimensional array. + footprint : ndarray, optional + The footprint (structuring element) used to determine the neighborhood + of each evaluated pixel (``True`` denotes a connected pixel). It must + be a boolean array and have the same number of dimensions as `image`. + If neither `footprint` nor `connectivity` are given, all adjacent + pixels are considered as part of the neighborhood. + 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. + indices : bool, optional + If True, the output will be a tuple of one-dimensional arrays + representing the indices of local minima in each dimension. If False, + the output will be a boolean array with the same shape as `image`. + allow_borders : bool, optional + If true, plateaus that touch the image border are valid minima. + + Returns + ------- + minima : ndarray or tuple[ndarray] + If `indices` is false, a boolean array with the same shape as `image` + is returned with ``True`` indicating the position of local minima + (``False`` otherwise). If `indices` is true, a tuple of one-dimensional + arrays containing the coordinates (indices) of all found minima. + + See Also + -------- + skimage.morphology.local_maxima + skimage.morphology.h_maxima + skimage.morphology.h_minima + + Notes + ----- + This function operates on the following ideas: + + 1. Make a first pass over the image's last dimension and flag candidates + for local minima by comparing pixels in only one direction. + If the pixels aren't connected in the last dimension all pixels are + flagged as candidates instead. + + For each candidate: + + 2. Perform a flood-fill to find all connected pixels that have the same + gray value and are part of the plateau. + 3. Consider the connected neighborhood of a plateau: if no bordering sample + has a smaller gray level, mark the plateau as a definite local minimum. + + Examples + -------- + >>> from skimage.morphology import local_minima + >>> 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]]) + + Find local minima by comparing to all neighboring pixels (maximal + connectivity): + + >>> local_minima(image) + array([[False, False, False, False, False, False, False], + [False, True, True, False, False, False, False], + [False, True, True, False, False, False, False], + [ True, False, False, False, False, False, True]]) + >>> local_minima(image, indices=True) + (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) + + Find local minima without comparing to diagonal pixels (connectivity 1): + + >>> local_minima(image, connectivity=1) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [ True, False, False, False, False, False, True]]) + + and exclude minima that border the image edge: + + >>> local_minima(image, connectivity=1, allow_borders=False) + array([[False, False, False, False, False, False, False], + [False, True, True, False, True, True, False], + [False, True, True, False, True, True, False], + [False, False, False, False, False, False, False]]) + """ + return local_maxima( + image=invert(image, signed_float=True), + footprint=footprint, + connectivity=connectivity, + indices=indices, + allow_borders=allow_borders, + ) diff --git a/envs/kitoverlay/skimage/restoration/__init__.py b/envs/kitoverlay/skimage/restoration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13c8e7421d0898c0da6029dc1e31c2362176eb4c --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/__init__.py @@ -0,0 +1,5 @@ +"""Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/restoration/__init__.pyi b/envs/kitoverlay/skimage/restoration/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..399036ae296af775c89461588d417ab4ca950129 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/__init__.pyi @@ -0,0 +1,38 @@ +# 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__ = [ + 'wiener', + 'unsupervised_wiener', + 'richardson_lucy', + 'unwrap_phase', + 'denoise_tv_bregman', + 'denoise_tv_chambolle', + 'denoise_bilateral', + 'denoise_wavelet', + 'denoise_nl_means', + 'denoise_invariant', + 'estimate_sigma', + 'inpaint_biharmonic', + 'cycle_spin', + 'calibrate_denoiser', + 'rolling_ball', + 'ellipsoid_kernel', + 'ball_kernel', +] + +from .deconvolution import wiener, unsupervised_wiener, richardson_lucy +from .unwrap import unwrap_phase +from ._denoise import ( + denoise_tv_chambolle, + denoise_tv_bregman, + denoise_bilateral, + denoise_wavelet, + estimate_sigma, +) +from ._cycle_spin import cycle_spin +from .non_local_means import denoise_nl_means +from .inpaint import inpaint_biharmonic +from .j_invariant import calibrate_denoiser, denoise_invariant +from ._rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea3d8b1a25432a273971bbeb6dbe59be159ecd4f Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/_cycle_spin.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/_cycle_spin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc24e1a7c35682f867ef269bbf4e61a9e077940 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/_cycle_spin.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/_denoise.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/_denoise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42a336e7dd9437b757c0ae9e1be6444d646c10ec Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/_denoise.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/_rolling_ball.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/_rolling_ball.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9039b3d84fdb156b6880564c67c766d9bb9e224 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/_rolling_ball.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/deconvolution.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/deconvolution.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd4aca6692de89b18c9d3d2ebb231fc6982d603f Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/deconvolution.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/inpaint.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/inpaint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41daa198ede311d262fc90d95b2c437e6e7e51c8 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/inpaint.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/j_invariant.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/j_invariant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4185f1c6966720e123e402c6b60b4a671f462104 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/j_invariant.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/non_local_means.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/non_local_means.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fbcfa66bcbea32533288f65569aacc7cf4a3c32 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/non_local_means.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/uft.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/uft.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ba4bf1cc32e93ddfe370196b826e8608b989919 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/uft.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/__pycache__/unwrap.cpython-311.pyc b/envs/kitoverlay/skimage/restoration/__pycache__/unwrap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64a219604849b94e86c25975f681e44e8e301e07 Binary files /dev/null and b/envs/kitoverlay/skimage/restoration/__pycache__/unwrap.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/restoration/_cycle_spin.py b/envs/kitoverlay/skimage/restoration/_cycle_spin.py new file mode 100644 index 0000000000000000000000000000000000000000..fba0b4ca85b5a183c8e872a069fbb84ba87ebdb8 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/_cycle_spin.py @@ -0,0 +1,172 @@ +from itertools import product +import numpy as np +from .._shared import utils +from .._shared.utils import warn, deprecate_parameter, DEPRECATED + +try: + import dask + + dask_available = True +except ImportError: + dask_available = False + + +def _generate_shifts(ndim, multichannel, max_shifts, shift_steps=1): + """Returns all combinations of shifts in n dimensions over the specified + max_shifts and step sizes. + + Examples + -------- + >>> s = list(_generate_shifts(2, False, max_shifts=(1, 2), shift_steps=1)) + >>> print(s) + [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)] + """ + mc = int(multichannel) + if np.isscalar(max_shifts): + max_shifts = (max_shifts,) * (ndim - mc) + (0,) * mc + elif multichannel and len(max_shifts) == ndim - 1: + max_shifts = tuple(max_shifts) + (0,) + elif len(max_shifts) != ndim: + raise ValueError("max_shifts should have length ndim") + + if np.isscalar(shift_steps): + shift_steps = (shift_steps,) * (ndim - mc) + (1,) * mc + elif multichannel and len(shift_steps) == ndim - 1: + shift_steps = tuple(shift_steps) + (1,) + elif len(shift_steps) != ndim: + raise ValueError("max_shifts should have length ndim") + + if any(s < 1 for s in shift_steps): + raise ValueError("shift_steps must all be >= 1") + + if multichannel and max_shifts[-1] != 0: + raise ValueError( + "Multichannel cycle spinning should not have shifts along the " "last axis." + ) + + return product(*[range(0, s + 1, t) for s, t in zip(max_shifts, shift_steps)]) + + +@deprecate_parameter( + deprecated_name="num_workers", + new_name="workers", + start_version="0.26", + stop_version="0.28", +) +@utils.channel_as_last_axis() +def cycle_spin( + x, + func, + max_shifts, + shift_steps=1, + num_workers=DEPRECATED, + func_kw=None, + *, + workers=None, + channel_axis=None, +): + """Cycle spinning (repeatedly apply func to shifted versions of x). + + Parameters + ---------- + x : array-like + Data for input to ``func``. + func : function + A function to apply to circularly shifted versions of ``x``. Should + take ``x`` as its first argument. Any additional arguments can be + supplied via ``func_kw``. + max_shifts : int or tuple + If an integer, shifts in ``range(0, max_shifts+1)`` will be used along + each axis of ``x``. If a tuple, ``range(0, max_shifts[i]+1)`` will be + along axis i. + shift_steps : int or tuple, optional + The step size for the shifts applied along axis, i, are:: + ``range((0, max_shifts[i]+1, shift_steps[i]))``. If an integer is + provided, the same step size is used for all axes. + workers : int or None, optional + The number of parallel threads to use during cycle spinning. If set to + ``None``, the full set of available cores are used. + func_kw : dict, optional + Additional keyword arguments to supply to ``func``. + 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 + ------- + avg_y : np.ndarray + The output of ``func(x, **func_kw)`` averaged over all combinations of + the specified axis shifts. + + Notes + ----- + Cycle spinning was proposed as a way to approach shift-invariance via + performing several circular shifts of a shift-variant transform [1]_. + + For a n-level discrete wavelet transforms, one may wish to perform all + shifts up to ``max_shifts = 2**n - 1``. In practice, much of the benefit + can often be realized with only a small number of shifts per axis. + + For transforms such as the blockwise discrete cosine transform, one may + wish to evaluate shifts up to the block size used by the transform. + + References + ---------- + .. [1] R.R. Coifman and D.L. Donoho. "Translation-Invariant De-Noising". + Wavelets and Statistics, Lecture Notes in Statistics, vol.103. + Springer, New York, 1995, pp.125-150. + :DOI:`10.1007/978-1-4612-2544-7_9` + + Examples + -------- + >>> import skimage.data + >>> from skimage import img_as_float + >>> from skimage.restoration import denoise_tv_chambolle, cycle_spin + >>> img = img_as_float(skimage.data.camera()) + >>> sigma = 0.1 + >>> img = img + sigma * np.random.standard_normal(img.shape) + >>> denoised = cycle_spin(img, func=denoise_tv_chambolle, + ... max_shifts=3) # doctest: +IGNORE_WARNINGS + + """ + if func_kw is None: + func_kw = {} + + x = np.asanyarray(x) + multichannel = channel_axis is not None + all_shifts = _generate_shifts(x.ndim, multichannel, max_shifts, shift_steps) + all_shifts = list(all_shifts) + roll_axes = tuple(range(x.ndim)) + + def _run_one_shift(shift): + # shift, apply function, inverse shift + xs = np.roll(x, shift, axis=roll_axes) + tmp = func(xs, **func_kw) + return np.roll(tmp, tuple(-s for s in shift), axis=roll_axes) + + if not dask_available and (workers is None or workers > 1): + workers = 1 + warn( + 'The optional dask dependency is not installed. ' + 'The number of workers is set to 1. To silence ' + 'this warning, install dask or explicitly set `workers=1` ' + 'when calling the `cycle_spin` function', + stacklevel=4, + ) + # compute a running average across the cycle shifts + if workers == 1: + # serial processing + mean = _run_one_shift(all_shifts[0]) + for shift in all_shifts[1:]: + mean += _run_one_shift(shift) + mean /= len(all_shifts) + else: + # multithreaded via dask + futures = [dask.delayed(_run_one_shift)(s) for s in all_shifts] + mean = sum(futures) / len(futures) + mean = mean.compute(workers=workers) + return mean diff --git a/envs/kitoverlay/skimage/restoration/_denoise.py b/envs/kitoverlay/skimage/restoration/_denoise.py new file mode 100644 index 0000000000000000000000000000000000000000..d79819c41f47494ca6b69ba9d14e28ce227a89c1 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/_denoise.py @@ -0,0 +1,1125 @@ +import functools +from math import ceil +import numbers + +import scipy.stats +import numpy as np + +from ..util.dtype import img_as_float +from .._shared import utils +from .._shared.utils import _supported_float_type, warn +from ._denoise_cy import _denoise_bilateral, _denoise_tv_bregman +from .. import color +from ..color.colorconv import ycbcr_from_rgb + + +__doctest_requires__ = {("denoise_wavelet", "estimate_sigma"): ["pywt"]} + + +def _gaussian_weight(array, sigma_squared, *, dtype=float): + """Helping function. Define a Gaussian weighting from array and + sigma_square. + + Parameters + ---------- + array : ndarray + Input array. + sigma_squared : float + The squared standard deviation used in the filter. + dtype : data type object, optional (default : float) + The type and size of the data to be returned. + + Returns + ------- + gaussian : ndarray + The input array filtered by the Gaussian. + """ + return np.exp(-0.5 * (array**2 / sigma_squared), dtype=dtype) + + +def _compute_color_lut(bins, sigma, max_value, *, dtype=float): + """Helping function. Define a lookup table containing Gaussian filter + values using the color distance sigma. + + Parameters + ---------- + bins : int + Number of discrete values for Gaussian weights of color filtering. + A larger value results in improved accuracy. + sigma : float + Standard deviation for grayvalue/color distance (radiometric + similarity). A larger value results in averaging of pixels with larger + radiometric differences. Note, that the image will be converted using + the `img_as_float` function and thus the standard deviation is in + respect to the range ``[0, 1]``. If the value is ``None`` the standard + deviation of the ``image`` will be used. + max_value : float + Maximum value of the input image. + dtype : data type object, optional (default : float) + The type and size of the data to be returned. + + Returns + ------- + color_lut : ndarray + Lookup table for the color distance sigma. + """ + values = np.linspace(0, max_value, bins, endpoint=False) + return _gaussian_weight(values, sigma**2, dtype=dtype) + + +def _compute_spatial_lut(win_size, sigma, *, dtype=float): + """Helping function. Define a lookup table containing Gaussian filter + values using the spatial sigma. + + Parameters + ---------- + win_size : int + Window size for filtering. + If win_size is not specified, it is calculated as + ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``. + sigma : float + Standard deviation for range distance. A larger value results in + averaging of pixels with larger spatial differences. + dtype : data type object + The type and size of the data to be returned. + + Returns + ------- + spatial_lut : ndarray + Lookup table for the spatial sigma. + """ + grid_points = np.arange(-win_size // 2, win_size // 2 + 1) + rr, cc = np.meshgrid(grid_points, grid_points, indexing='ij') + distances = np.hypot(rr, cc) + return _gaussian_weight(distances, sigma**2, dtype=dtype).ravel() + + +@utils.channel_as_last_axis() +def denoise_bilateral( + image, + win_size=None, + sigma_color=None, + sigma_spatial=1, + bins=10000, + mode='constant', + cval=0, + *, + channel_axis=None, +): + """Denoise image using bilateral filter. + + Parameters + ---------- + image : ndarray, shape (M, N[, 3]) + Input image, 2D grayscale or RGB. + win_size : int + Window size for filtering. + If win_size is not specified, it is calculated as + ``max(5, 2 * ceil(3 * sigma_spatial) + 1)``. + sigma_color : float + Standard deviation for grayvalue/color distance (radiometric + similarity). A larger value results in averaging of pixels with larger + radiometric differences. If ``None``, the standard deviation of + ``image`` will be used. + sigma_spatial : float + Standard deviation for range distance. A larger value results in + averaging of pixels with larger spatial differences. + bins : int + Number of discrete values for Gaussian weights of color filtering. + A larger value results in improved accuracy. + mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'} + How to handle values outside the image borders. See + `numpy.pad` for detail. + cval : int or float + Used in conjunction with mode 'constant', the value outside + the image boundaries. + 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 channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + denoised : ndarray + Denoised image. + + Notes + ----- + This is an edge-preserving, denoising filter. It averages pixels based on + their spatial closeness and radiometric similarity [1]_. + + Spatial closeness is measured by the Gaussian function of the Euclidean + distance between two pixels and a certain standard deviation + (`sigma_spatial`). + + Radiometric similarity is measured by the Gaussian function of the + Euclidean distance between two color values and a certain standard + deviation (`sigma_color`). + + Note that, if the image is of any `int` dtype, ``image`` will be + converted using the `img_as_float` function and thus the standard + deviation (`sigma_color`) will be in range ``[0, 1]``. + + For more information on scikit-image's data type conversions and how + images are rescaled in these conversions, + see: https://scikit-image.org/docs/stable/user_guide/data_types.html. + + References + ---------- + .. [1] C. Tomasi and R. Manduchi. "Bilateral Filtering for Gray and Color + Images." IEEE International Conference on Computer Vision (1998) + 839-846. :DOI:`10.1109/ICCV.1998.710815` + + Examples + -------- + >>> from skimage import data, img_as_float + >>> astro = img_as_float(data.astronaut()) + >>> astro = astro[220:300, 220:320] + >>> rng = np.random.default_rng() + >>> noisy = astro + 0.6 * astro.std() * rng.random(astro.shape) + >>> noisy = np.clip(noisy, 0, 1) + >>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15, + ... channel_axis=-1) + """ + if channel_axis is not None: + if image.ndim != 3: + if image.ndim == 2: + raise ValueError( + "Use ``channel_axis=None`` for 2D grayscale " + "images. The last axis of the input image " + "must be multiple color channels not another " + "spatial dimension." + ) + else: + raise ValueError( + f'Bilateral filter is only implemented for ' + f'2D grayscale images (image.ndim == 2) and ' + f'2D multichannel (image.ndim == 3) images, ' + f'but the input image has {image.ndim} dimensions.' + ) + elif image.shape[2] not in (3, 4): + if image.shape[2] > 4: + msg = ( + f'The last axis of the input image is ' + f'interpreted as channels. Input image with ' + f'shape {image.shape} has {image.shape[2]} channels ' + f'in last axis. ``denoise_bilateral``is implemented ' + f'for 2D grayscale and color images only.' + ) + warn(msg) + else: + msg = ( + f'Input image must be grayscale, RGB, or RGBA; ' + f'but has shape {image.shape}.' + ) + warn(msg) + else: + if image.ndim > 2: + raise ValueError( + f'Bilateral filter is not implemented for ' + f'grayscale images of 3 or more dimensions, ' + f'but input image has {image.shape} shape. Use ' + f'``channel_axis=-1`` for 2D RGB images.' + ) + + if win_size is None: + win_size = max(5, 2 * int(ceil(3 * sigma_spatial)) + 1) + + min_value = image.min() + max_value = image.max() + + if min_value == max_value: + return image + + # if image.max() is 0, then dist_scale can have an unverified value + # and color_lut[(dist * dist_scale)] may cause a segmentation fault + # so we verify we have a positive image and that the max is not 0.0. + + image = np.atleast_3d(img_as_float(image)) + image = np.ascontiguousarray(image) + + sigma_color = sigma_color or image.std() + + color_lut = _compute_color_lut(bins, sigma_color, max_value, dtype=image.dtype) + + range_lut = _compute_spatial_lut(win_size, sigma_spatial, dtype=image.dtype) + + out = np.empty(image.shape, dtype=image.dtype) + + dims = image.shape[2] + + # There are a number of arrays needed in the Cython function. + # It's easier to allocate them outside of Cython so that all + # arrays are in the same type, then just copy the empty array + # where needed within Cython. + empty_dims = np.empty(dims, dtype=image.dtype) + + if min_value < 0: + image = image - min_value + max_value -= min_value + _denoise_bilateral( + image, + max_value, + win_size, + sigma_color, + sigma_spatial, + bins, + mode, + cval, + color_lut, + range_lut, + empty_dims, + out, + ) + # need to drop the added channels axis for grayscale images + out = np.squeeze(out) + if min_value < 0: + out += min_value + return out + + +@utils.channel_as_last_axis() +def denoise_tv_bregman( + image, weight=5.0, max_num_iter=100, eps=1e-3, isotropic=True, *, channel_axis=None +): + r"""Perform total variation denoising using split-Bregman optimization. + + Given :math:`f`, a noisy image (input data), + total variation denoising (also known as total variation regularization) + aims to find an image :math:`u` with less total variation than :math:`f`, + under the constraint that :math:`u` remain similar to :math:`f`. + This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization + problem: + + .. math:: + + \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right) + + where :math:`\lambda` is a positive parameter. + The first term of this cost function is the total variation; + the second term represents data fidelity. As :math:`\lambda \to 0`, + the total variation term dominates, forcing the solution to have smaller + total variation, at the expense of looking less like the input data. + + This code is an implementation of the split Bregman algorithm of Goldstein + and Osher to solve the ROF problem ([1]_, [2]_, [3]_). + + Parameters + ---------- + image : ndarray + Input image to be denoised (converted using :func:`~.img_as_float`). + weight : float, optional + Denoising weight. It is equal to :math:`\frac{\lambda}{2}`. Therefore, + the smaller the `weight`, the more denoising (at + the expense of less similarity to `image`). + eps : float, optional + Tolerance :math:`\varepsilon > 0` for the stop criterion: + The algorithm stops when :math:`\|u_n - u_{n-1}\|_2 < \varepsilon`. + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + isotropic : bool, optional + Switch between isotropic and anisotropic TV denoising. + 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 channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + u : ndarray + Denoised image. + + Notes + ----- + Ensure that `channel_axis` parameter is set appropriately for color + images. + + The principle of total variation denoising is explained in [4]_. + It is about minimizing the total variation of an image, + which can be roughly described as + the integral of the norm of the image gradient. Total variation + denoising tends to produce cartoon-like images, that is, + piecewise-constant images. + + See Also + -------- + denoise_tv_chambolle : Perform total variation denoising in nD. + + References + ---------- + .. [1] Tom Goldstein and Stanley Osher, "The Split Bregman Method For L1 + Regularized Problems", + https://ww3.math.ucla.edu/camreport/cam08-29.pdf + .. [2] Pascal Getreuer, "Rudin–Osher–Fatemi Total Variation Denoising + using Split Bregman" in Image Processing On Line on 2012–05–19, + https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf + .. [3] https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf + .. [4] https://en.wikipedia.org/wiki/Total_variation_denoising + + """ + image = np.atleast_3d(img_as_float(image)) + + rows = image.shape[0] + cols = image.shape[1] + dims = image.shape[2] + + shape_ext = (rows + 2, cols + 2, dims) + + out = np.zeros(shape_ext, image.dtype) + + if channel_axis is not None: + channel_out = np.zeros(shape_ext[:2] + (1,), dtype=out.dtype) + for c in range(image.shape[-1]): + # the algorithm below expects 3 dimensions to always be present. + # slicing the array in this fashion preserves the channel dimension + # for us + channel_in = np.ascontiguousarray(image[..., c : c + 1]) + + _denoise_tv_bregman( + channel_in, + image.dtype.type(weight), + max_num_iter, + eps, + isotropic, + channel_out, + ) + + out[..., c] = channel_out[..., 0] + + else: + image = np.ascontiguousarray(image) + + _denoise_tv_bregman( + image, image.dtype.type(weight), max_num_iter, eps, isotropic, out + ) + + return np.squeeze(out[1:-1, 1:-1]) + + +def _denoise_tv_chambolle_nd(image, weight=0.1, eps=2.0e-4, max_num_iter=200): + """Perform total-variation denoising on n-dimensional images. + + Parameters + ---------- + image : ndarray + n-D input data to be denoised. + weight : float, optional + Denoising weight. The greater `weight`, the more denoising (at + the expense of fidelity to `input`). + eps : float, optional + Relative difference of the value of the cost function that determines + the stop criterion. The algorithm stops when: + + (E_(n-1) - E_n) < eps * E_0 + + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + + Returns + ------- + out : ndarray + Denoised array of floats. + + Notes + ----- + Rudin, Osher and Fatemi algorithm. + """ + + ndim = image.ndim + p = np.zeros((image.ndim,) + image.shape, dtype=image.dtype) + g = np.zeros_like(p) + d = np.zeros_like(image) + i = 0 + while i < max_num_iter: + if i > 0: + # d will be the (negative) divergence of p + d = -p.sum(0) + slices_d = [ + slice(None), + ] * ndim + slices_p = [ + slice(None), + ] * (ndim + 1) + for ax in range(ndim): + slices_d[ax] = slice(1, None) + slices_p[ax + 1] = slice(0, -1) + slices_p[0] = ax + d[tuple(slices_d)] += p[tuple(slices_p)] + slices_d[ax] = slice(None) + slices_p[ax + 1] = slice(None) + out = image + d + else: + out = image + E = (d**2).sum() + + # g stores the gradients of out along each axis + # e.g. g[0] is the first order finite difference along axis 0 + slices_g = [ + slice(None), + ] * (ndim + 1) + for ax in range(ndim): + slices_g[ax + 1] = slice(0, -1) + slices_g[0] = ax + g[tuple(slices_g)] = np.diff(out, axis=ax) + slices_g[ax + 1] = slice(None) + + norm = np.sqrt((g**2).sum(axis=0))[np.newaxis, ...] + E += weight * norm.sum() + tau = 1.0 / (2.0 * ndim) + norm *= tau / weight + norm += 1.0 + p -= tau * g + p /= norm + E /= float(image.size) + if i == 0: + E_init = E + E_previous = E + else: + if np.abs(E_previous - E) < eps * E_init: + break + else: + E_previous = E + i += 1 + return out + + +def denoise_tv_chambolle( + image, weight=0.1, eps=2.0e-4, max_num_iter=200, *, channel_axis=None +): + r"""Perform total variation denoising in nD. + + Given :math:`f`, a noisy image (input data), + total variation denoising (also known as total variation regularization) + aims to find an image :math:`u` with less total variation than :math:`f`, + under the constraint that :math:`u` remain similar to :math:`f`. + This can be expressed by the Rudin--Osher--Fatemi (ROF) minimization + problem: + + .. math:: + + \min_{u} \sum_{i=0}^{N-1} \left( \left| \nabla{u_i} \right| + \frac{\lambda}{2}(f_i - u_i)^2 \right) + + where :math:`\lambda` is a positive parameter. + The first term of this cost function is the total variation; + the second term represents data fidelity. As :math:`\lambda \to 0`, + the total variation term dominates, forcing the solution to have smaller + total variation, at the expense of looking less like the input data. + + This code is an implementation of the algorithm proposed by Chambolle + in [1]_ to solve the ROF problem. + + Parameters + ---------- + image : ndarray + Input image to be denoised. If its dtype is not float, it gets + converted with :func:`~.img_as_float`. + weight : float, optional + Denoising weight. It is equal to :math:`\frac{1}{\lambda}`. Therefore, + the greater the `weight`, the more denoising (at the expense of + fidelity to `image`). + eps : float, optional + Tolerance :math:`\varepsilon > 0` for the stop criterion (compares to + absolute value of relative difference of the cost function :math:`E`): + The algorithm stops when :math:`|E_{n-1} - E_n| < \varepsilon * E_0`. + max_num_iter : int, optional + Maximal number of iterations used for the optimization. + 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 channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + u : ndarray + Denoised image. + + Notes + ----- + Make sure to set the `channel_axis` parameter appropriately for color + images. + + The principle of total variation denoising is explained in [2]_. + It is about minimizing the total variation of an image, + which can be roughly described as + the integral of the norm of the image gradient. Total variation + denoising tends to produce cartoon-like images, that is, + piecewise-constant images. + + See Also + -------- + denoise_tv_bregman : Perform total variation denoising using split-Bregman + optimization. + + References + ---------- + .. [1] A. Chambolle, An algorithm for total variation minimization and + applications, Journal of Mathematical Imaging and Vision, + Springer, 2004, 20, 89-97. + .. [2] https://en.wikipedia.org/wiki/Total_variation_denoising + + Examples + -------- + 2D example on astronaut image: + + >>> from skimage import color, data + >>> img = color.rgb2gray(data.astronaut())[:50, :50] + >>> rng = np.random.default_rng() + >>> img += 0.5 * img.std() * rng.standard_normal(img.shape) + >>> denoised_img = denoise_tv_chambolle(img, weight=60) + + 3D example on synthetic data: + + >>> x, y, z = np.ogrid[0:20, 0:20, 0:20] + >>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 + >>> mask = mask.astype(float) + >>> rng = np.random.default_rng() + >>> mask += 0.2 * rng.standard_normal(mask.shape) + >>> res = denoise_tv_chambolle(mask, weight=100) + + """ + + im_type = image.dtype + if not im_type.kind == 'f': + image = img_as_float(image) + + # enforce float16->float32 and float128->float64 + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + out = np.zeros_like(image) + for c in range(image.shape[channel_axis]): + out[_at(c)] = _denoise_tv_chambolle_nd( + image[_at(c)], weight, eps, max_num_iter + ) + else: + out = _denoise_tv_chambolle_nd(image, weight, eps, max_num_iter) + return out + + +def _bayes_thresh(details, var): + """BayesShrink threshold for a zero-mean details coeff array.""" + # Equivalent to: dvar = np.var(details) for 0-mean details array + dvar = np.mean(details * details) + eps = np.finfo(details.dtype).eps + thresh = var / np.sqrt(max(dvar - var, eps)) + return thresh + + +def _universal_thresh(img, sigma): + """Universal threshold used by the VisuShrink method""" + return sigma * np.sqrt(2 * np.log(img.size)) + + +def _sigma_est_dwt(detail_coeffs, distribution='Gaussian'): + """Calculate the robust median estimator of the noise standard deviation. + + Parameters + ---------- + detail_coeffs : ndarray + The detail coefficients corresponding to the discrete wavelet + transform of an image. + distribution : str + The underlying noise distribution. + + Returns + ------- + sigma : float + The estimated noise standard deviation (see section 4.2 of [1]_). + + References + ---------- + .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + """ + # Consider regions with detail coefficients exactly zero to be masked out + detail_coeffs = detail_coeffs[np.nonzero(detail_coeffs)] + + if distribution.lower() == 'gaussian': + # 75th quantile of the underlying, symmetric noise distribution + denom = scipy.stats.norm.ppf(0.75) + sigma = np.median(np.abs(detail_coeffs)) / denom + else: + raise ValueError("Only Gaussian noise estimation is currently " "supported") + return sigma + + +def _wavelet_threshold( + image, + wavelet, + method=None, + threshold=None, + sigma=None, + mode='soft', + wavelet_levels=None, +): + """Perform wavelet thresholding. + + Parameters + ---------- + image : ndarray (2d or 3d) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into an ndarray of floats for the computation + of the denoised image. + wavelet : string + The type of wavelet to perform. Can be any of the options + pywt.wavelist outputs. For example, this may be any of ``{db1, db2, + db3, db4, haar}``. + method : {'BayesShrink', 'VisuShrink'}, optional + Thresholding method to be used. The currently supported methods are + "BayesShrink" [1]_ and "VisuShrink" [2]_. If it is set to None, a + user-specified ``threshold`` must be supplied instead. + threshold : float, optional + The thresholding value to apply during wavelet coefficient + thresholding. The default value (None) uses the selected ``method`` to + estimate appropriate threshold(s) for noise removal. + sigma : float, optional + The standard deviation of the noise. The noise is estimated when sigma + is None (the default) by the method in [2]_. + mode : {'soft', 'hard'}, optional + An optional argument to choose the type of denoising performed. It + noted that choosing soft thresholding given additive noise finds the + best approximation of the original image. + wavelet_levels : int or None, optional + The number of wavelet decomposition levels to use. The default is + three less than the maximum number of possible decomposition levels + (see Notes below). + + Returns + ------- + out : ndarray + Denoised image. + + References + ---------- + .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet + thresholding for image denoising and compression." Image Processing, + IEEE Transactions on 9.9 (2000): 1532-1546. + :DOI:`10.1109/83.862633` + .. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + """ + try: + import pywt + except ImportError: + raise ImportError( + 'PyWavelets is not installed. Please ensure it is installed in ' + 'order to use this function.' + ) + + wavelet = pywt.Wavelet(wavelet) + if not wavelet.orthogonal: + warn( + f'Wavelet thresholding was designed for ' + f'use with orthogonal wavelets. For nonorthogonal ' + f'wavelets such as {wavelet.name},results are ' + f'likely to be suboptimal.' + ) + + # original_extent is used to workaround PyWavelets issue #80 + # odd-sized input results in an image with 1 extra sample after waverecn + original_extent = tuple(slice(s) for s in image.shape) + + # Determine the number of wavelet decomposition levels + if wavelet_levels is None: + # Determine the maximum number of possible levels for image + wavelet_levels = pywt.dwtn_max_level(image.shape, wavelet) + + # Skip coarsest wavelet scales (see Notes in docstring). + wavelet_levels = max(wavelet_levels - 3, 1) + + coeffs = pywt.wavedecn(image, wavelet=wavelet, level=wavelet_levels) + # Detail coefficients at each decomposition level + dcoeffs = coeffs[1:] + + if sigma is None: + # Estimate the noise via the method in [2]_ + detail_coeffs = dcoeffs[-1]['d' * image.ndim] + sigma = _sigma_est_dwt(detail_coeffs, distribution='Gaussian') + + if method is not None and threshold is not None: + warn( + f'Thresholding method {method} selected. The ' + f'user-specified threshold will be ignored.' + ) + + if threshold is None: + var = sigma**2 + if method is None: + raise ValueError("If method is None, a threshold must be provided.") + elif method == "BayesShrink": + # The BayesShrink thresholds from [1]_ in docstring + threshold = [ + {key: _bayes_thresh(level[key], var) for key in level} + for level in dcoeffs + ] + elif method == "VisuShrink": + # The VisuShrink thresholds from [2]_ in docstring + threshold = _universal_thresh(image, sigma) + else: + raise ValueError(f'Unrecognized method: {method}') + + if np.isscalar(threshold): + # A single threshold for all coefficient arrays + denoised_detail = [ + { + key: pywt.threshold(level[key], value=threshold, mode=mode) + for key in level + } + for level in dcoeffs + ] + else: + # Dict of unique threshold coefficients for each detail coeff. array + denoised_detail = [ + { + key: pywt.threshold(level[key], value=thresh[key], mode=mode) + for key in level + } + for thresh, level in zip(threshold, dcoeffs) + ] + denoised_coeffs = [coeffs[0]] + denoised_detail + out = pywt.waverecn(denoised_coeffs, wavelet)[original_extent] + out = out.astype(image.dtype) + return out + + +def _scale_sigma_and_image_consistently(image, sigma, multichannel, rescale_sigma): + """If the ``image`` is rescaled, also rescale ``sigma`` consistently. + + Images that are not floating point will be rescaled via ``img_as_float``. + Half-precision images will be promoted to single precision. + """ + if multichannel: + if isinstance(sigma, numbers.Number) or sigma is None: + sigma = [sigma] * image.shape[-1] + elif len(sigma) != image.shape[-1]: + raise ValueError( + "When channel_axis is not None, sigma must be a scalar or have " + "length equal to the number of channels" + ) + if image.dtype.kind != 'f': + if rescale_sigma: + range_pre = image.max() - image.min() + image = img_as_float(image) + if rescale_sigma: + range_post = image.max() - image.min() + # apply the same magnitude scaling to sigma + scale_factor = range_post / range_pre + if multichannel: + sigma = [s * scale_factor if s is not None else s for s in sigma] + elif sigma is not None: + sigma *= scale_factor + elif image.dtype == np.float16: + image = image.astype(np.float32) + return image, sigma + + +def _rescale_sigma_rgb2ycbcr(sigmas): + """Convert user-provided noise standard deviations to YCbCr space. + + Notes + ----- + If R, G, B are linearly independent random variables and a1, a2, a3 are + scalars, then random variable C: + C = a1 * R + a2 * G + a3 * B + has variance, var_C, given by: + var_C = a1**2 * var_R + a2**2 * var_G + a3**2 * var_B + """ + if sigmas[0] is None: + return sigmas + sigmas = np.asarray(sigmas) + rgv_variances = sigmas * sigmas + for i in range(3): + scalars = ycbcr_from_rgb[i, :] + var_channel = np.sum(scalars * scalars * rgv_variances) + sigmas[i] = np.sqrt(var_channel) + return sigmas + + +@utils.channel_as_last_axis() +def denoise_wavelet( + image, + sigma=None, + wavelet='db1', + mode='soft', + wavelet_levels=None, + convert2ycbcr=False, + method='BayesShrink', + rescale_sigma=True, + *, + channel_axis=None, +): + """Perform wavelet denoising on an image. + + Parameters + ---------- + image : ndarray (M[, N[, ...P]][, C]) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into an ndarray of floats for the computation + of the denoised image. + sigma : float or list, optional + The noise standard deviation used when computing the wavelet detail + coefficient threshold(s). When None (default), the noise standard + deviation is estimated via the method in [2]_. + wavelet : str, optional + The type of wavelet to perform and can be any of the options + ``pywt.wavelist`` outputs. The default is `'db1'`. For example, + ``wavelet`` can be any of ``{'db2', 'haar', 'sym9'}`` and many more. + mode : {'soft', 'hard'}, optional + An optional argument to choose the type of denoising performed. It + noted that choosing soft thresholding given additive noise finds the + best approximation of the original image. + wavelet_levels : int or None, optional + The number of wavelet decomposition levels to use. The default is + three less than the maximum number of possible decomposition levels. + convert2ycbcr : bool, optional + If True and channel_axis is set, do the wavelet denoising in the YCbCr + colorspace instead of the RGB color space. This typically results in + better performance for RGB images. + method : {'BayesShrink', 'VisuShrink'}, optional + Thresholding method to be used. The currently supported methods are + "BayesShrink" [1]_ and "VisuShrink" [2]_. Defaults to "BayesShrink". + rescale_sigma : bool, optional + If False, no rescaling of the user-provided ``sigma`` will be + performed. The default of ``True`` rescales sigma appropriately if the + image is rescaled internally. + + .. versionadded:: 0.16 + ``rescale_sigma`` was introduced in 0.16 + 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 channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : ndarray + Denoised image. + + Notes + ----- + The wavelet domain is a sparse representation of the image, and can be + thought of similarly to the frequency domain of the Fourier transform. + Sparse representations have most values zero or near-zero and truly random + noise is (usually) represented by many small values in the wavelet domain. + Setting all values below some threshold to 0 reduces the noise in the + image, but larger thresholds also decrease the detail present in the image. + + If the input is 3D, this function performs wavelet denoising on each color + plane separately. + + .. versionchanged:: 0.16 + For floating point inputs, the original input range is maintained and + there is no clipping applied to the output. Other input types will be + converted to a floating point value in the range [-1, 1] or [0, 1] + depending on the input image range. Unless ``rescale_sigma = False``, + any internal rescaling applied to the ``image`` will also be applied + to ``sigma`` to maintain the same relative amplitude. + + Many wavelet coefficient thresholding approaches have been proposed. By + default, ``denoise_wavelet`` applies BayesShrink, which is an adaptive + thresholding method that computes separate thresholds for each wavelet + sub-band as described in [1]_. + + If ``method == "VisuShrink"``, a single "universal threshold" is applied to + all wavelet detail coefficients as described in [2]_. This threshold + is designed to remove all Gaussian noise at a given ``sigma`` with high + probability, but tends to produce images that appear overly smooth. + + Although any of the wavelets from ``PyWavelets`` can be selected, the + thresholding methods assume an orthogonal wavelet transform and may not + choose the threshold appropriately for biorthogonal wavelets. Orthogonal + wavelets are desirable because white noise in the input remains white noise + in the subbands. Biorthogonal wavelets lead to colored noise in the + subbands. Additionally, the orthogonal wavelets in PyWavelets are + orthonormal so that noise variance in the subbands remains identical to the + noise variance of the input. Example orthogonal wavelets are the Daubechies + (e.g. 'db2') or symmlet (e.g. 'sym2') families. + + References + ---------- + .. [1] Chang, S. Grace, Bin Yu, and Martin Vetterli. "Adaptive wavelet + thresholding for image denoising and compression." Image Processing, + IEEE Transactions on 9.9 (2000): 1532-1546. + :DOI:`10.1109/83.862633` + .. [2] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + + Examples + -------- + >>> from skimage import color, data + >>> img = img_as_float(data.astronaut()) + >>> img = color.rgb2gray(img) + >>> rng = np.random.default_rng() + >>> img += 0.1 * rng.standard_normal(img.shape) + >>> img = np.clip(img, 0, 1) + >>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True) + + """ + multichannel = channel_axis is not None + if method not in ["BayesShrink", "VisuShrink"]: + raise ValueError( + f'Invalid method: {method}. The currently supported ' + f'methods are "BayesShrink" and "VisuShrink".' + ) + + # floating-point inputs are not rescaled, so don't clip their output. + clip_output = image.dtype.kind != 'f' + + if convert2ycbcr and not multichannel: + raise ValueError("convert2ycbcr requires channel_axis to be set") + + image, sigma = _scale_sigma_and_image_consistently( + image, sigma, multichannel, rescale_sigma + ) + if multichannel: + if convert2ycbcr: + out = color.rgb2ycbcr(image) + # convert user-supplied sigmas to the new colorspace as well + if rescale_sigma: + sigma = _rescale_sigma_rgb2ycbcr(sigma) + for i in range(3): + # renormalizing this color channel to live in [0, 1] + _min, _max = out[..., i].min(), out[..., i].max() + scale_factor = _max - _min + if scale_factor == 0: + # skip any channel containing only zeros! + continue + channel = out[..., i] - _min + channel /= scale_factor + sigma_channel = sigma[i] + if sigma_channel is not None: + sigma_channel /= scale_factor + out[..., i] = denoise_wavelet( + channel, + wavelet=wavelet, + method=method, + sigma=sigma_channel, + mode=mode, + wavelet_levels=wavelet_levels, + rescale_sigma=rescale_sigma, + ) + out[..., i] = out[..., i] * scale_factor + out[..., i] += _min + out = color.ycbcr2rgb(out) + else: + out = np.empty_like(image) + for c in range(image.shape[-1]): + out[..., c] = _wavelet_threshold( + image[..., c], + wavelet=wavelet, + method=method, + sigma=sigma[c], + mode=mode, + wavelet_levels=wavelet_levels, + ) + else: + out = _wavelet_threshold( + image, + wavelet=wavelet, + method=method, + sigma=sigma, + mode=mode, + wavelet_levels=wavelet_levels, + ) + + if clip_output: + clip_range = (-1, 1) if image.min() < 0 else (0, 1) + out = np.clip(out, *clip_range, out=out) + return out + + +def estimate_sigma(image, average_sigmas=False, *, channel_axis=None): + """ + Robust wavelet-based estimator of the (Gaussian) noise standard deviation. + + Parameters + ---------- + image : ndarray + Image for which to estimate the noise standard deviation. + average_sigmas : bool, optional + If true, average the channel estimates of `sigma`. Otherwise return + a list of sigmas corresponding to each channel. + 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 channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + sigma : float or list + Estimated noise standard deviation(s). If `multichannel` is True and + `average_sigmas` is False, a separate noise estimate for each channel + is returned. Otherwise, the average of the individual channel + estimates is returned. + + Notes + ----- + This function assumes the noise follows a Gaussian distribution. The + estimation algorithm is based on the median absolute deviation of the + wavelet detail coefficients as described in section 4.2 of [1]_. + + References + ---------- + .. [1] D. L. Donoho and I. M. Johnstone. "Ideal spatial adaptation + by wavelet shrinkage." Biometrika 81.3 (1994): 425-455. + :DOI:`10.1093/biomet/81.3.425` + + Examples + -------- + >>> import skimage.data + >>> from skimage import img_as_float + >>> img = img_as_float(skimage.data.camera()) + >>> sigma = 0.1 + >>> rng = np.random.default_rng() + >>> img = img + sigma * rng.standard_normal(img.shape) + >>> sigma_hat = estimate_sigma(img, channel_axis=None) + """ + try: + import pywt + except ImportError: + raise ImportError( + 'PyWavelets is not installed. Please ensure it is installed in ' + 'order to use this function.' + ) + + if channel_axis is not None: + channel_axis = channel_axis % image.ndim + _at = functools.partial(utils.slice_at_axis, axis=channel_axis) + nchannels = image.shape[channel_axis] + sigmas = [ + estimate_sigma(image[_at(c)], channel_axis=None) for c in range(nchannels) + ] + if average_sigmas: + sigmas = np.mean(sigmas) + return sigmas + elif image.shape[-1] <= 4: + msg = ( + f'image is size {image.shape[-1]} on the last axis, ' + f'but channel_axis is None. If this is a color image, ' + f'please set channel_axis=-1 for proper noise estimation.' + ) + warn(msg) + coeffs = pywt.dwtn(image, wavelet='db2') + detail_coeffs = coeffs['d' * image.ndim] + return _sigma_est_dwt(detail_coeffs, distribution='Gaussian') diff --git a/envs/kitoverlay/skimage/restoration/_rolling_ball.py b/envs/kitoverlay/skimage/restoration/_rolling_ball.py new file mode 100644 index 0000000000000000000000000000000000000000..284f021a27d927b0871fc598ca777f8887ff6495 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/_rolling_ball.py @@ -0,0 +1,211 @@ +import numpy as np + +from .._shared.utils import _supported_float_type, deprecate_parameter, DEPRECATED +from ._rolling_ball_cy import apply_kernel, apply_kernel_nan + + +@deprecate_parameter( + "num_threads", new_name="workers", start_version="0.26", stop_version="0.28" +) +def rolling_ball( + image, + *, + radius=100, + kernel=None, + nansafe=False, + num_threads=DEPRECATED, + workers=None, +): + """Estimate background intensity using the rolling-ball algorithm. + + This function is a generalization of the rolling-ball algorithm [1]_ to + estimate the background intensity of an n-dimensional image. This is + typically useful for background subtraction in case of uneven exposure. + Think of the image as a landscape (where altitude is determined by + intensity), under which a ball of given radius is rolled. At each + position, the ball's apex gives the resulting background intensity. + + Parameters + ---------- + image : ndarray + The image to be filtered. + radius : int, optional + Radius of the ball-shaped kernel to be rolled under the + image landscape. Used only if `kernel` is ``None``. + kernel : ndarray, optional + An alternative way to specify the rolling ball, as an arbitrary + kernel. It must have the same number of axes as `image`. + nansafe : bool, optional + If ``False`` (default), the function assumes that none of the values + in `image` are ``np.nan``, and uses a faster implementation. + workers : int, optional + The maximum number of threads to use. If ``None``, use the OpenMP + default value; typically equal to the maximum number of virtual cores. + Note: This is an upper limit to the number of threads. The exact number + is determined by the system's OpenMP library. + + .. versionadded:: 0.26 + Replaces deprecated parameter `num_threads`. + + Returns + ------- + background : ndarray + The estimated background of the image. + + Notes + ----- + This implementation assumes that dark pixels correspond to the background. If + you have a bright background, invert the image before passing it to this + function, e.g., using :func:`skimage.util.invert`. + + For this method to give meaningful results, the radius of the ball (or + typical size of the kernel, in the general case) should be larger than the + typical size of the image features of interest. + + This algorithm is sensitive to noise (in particular salt-and-pepper + noise). If this is a problem in your image, you can apply mild + Gaussian smoothing before passing the image to this function. + + This algorithm's complexity is polynomial in the radius, with degree equal + to the image dimensionality (a 2D image is N^2, a 3D image is N^3, etc.), + so it can take a long time as the radius grows beyond 30 or so ([2]_, [3]_). + It is an exact N-dimensional calculation; if all you need is an + approximation, faster options to consider are top-hat filtering [4]_ or + downscaling-then-upscaling to reduce the size of the input processed. + + References + ---------- + .. [1] Sternberg, Stanley R. "Biomedical image processing." Computer 1 + (1983): 22-34. :DOI:`10.1109/MC.1983.1654163` + .. [2] https://github.com/scikit-image/scikit-image/issues/5193 + .. [3] https://github.com/scikit-image/scikit-image/issues/7423 + .. [4] https://forum.image.sc/t/59267/7 + + Examples + -------- + >>> import numpy as np + >>> import skimage as ski + >>> image = ski.data.coins() + >>> background = ski.restoration.rolling_ball(image) + >>> filtered_image = image - background + + >>> import numpy as np + >>> import skimage as ski + >>> image = ski.data.coins() + >>> kernel = ski.restoration.ellipsoid_kernel((101, 101), 75) + >>> background = ski.restoration.rolling_ball(image, kernel=kernel) + >>> filtered_image = image - background + """ + + image = np.asarray(image) + float_type = _supported_float_type(image.dtype) + img = image.astype(float_type, copy=False) + + if workers is None: + workers = 0 + + if kernel is None: + kernel = ball_kernel(radius, image.ndim) + + kernel = kernel.astype(float_type) + kernel_shape = np.asarray(kernel.shape) + kernel_center = kernel_shape // 2 + center_intensity = kernel[tuple(kernel_center)] + + intensity_difference = center_intensity - kernel + intensity_difference[kernel == np.inf] = np.inf + intensity_difference = intensity_difference.astype(img.dtype) + intensity_difference = intensity_difference.reshape(-1) + + img = np.pad( + img, kernel_center[:, np.newaxis], constant_values=np.inf, mode="constant" + ) + + func = apply_kernel_nan if nansafe else apply_kernel + background = func( + img.reshape(-1), + intensity_difference, + np.zeros_like(image, dtype=img.dtype).reshape(-1), + np.array(image.shape, dtype=np.intp), + np.array(img.shape, dtype=np.intp), + kernel_shape.astype(np.intp), + workers, + ) + + background = background.astype(image.dtype, copy=False) + + return background + + +def ball_kernel(radius, ndim): + """Create a ball kernel for restoration.rolling_ball. + + Parameters + ---------- + radius : int + Radius of the ball. + ndim : int + Number of dimensions of the ball. ``ndim`` should match the + dimensionality of the image the kernel will be applied to. + + Returns + ------- + kernel : ndarray + The kernel containing the surface intensity of the top half + of the ellipsoid. + + See Also + -------- + rolling_ball + """ + + kernel_coords = np.stack( + np.meshgrid( + *[np.arange(-x, x + 1) for x in [np.ceil(radius)] * ndim], indexing='ij' + ), + axis=-1, + ) + + sum_of_squares = np.sum(kernel_coords**2, axis=-1) + distance_from_center = np.sqrt(sum_of_squares) + kernel = np.sqrt(np.clip(radius**2 - sum_of_squares, 0, None)) + kernel[distance_from_center > radius] = np.inf + + return kernel + + +def ellipsoid_kernel(shape, intensity): + """Create an ellipoid kernel for restoration.rolling_ball. + + Parameters + ---------- + shape : array-like + Length of the principal axis of the ellipsoid (excluding + the intensity axis). The kernel needs to have the same + dimensionality as the image it will be applied to. + intensity : int + Length of the intensity axis of the ellipsoid. + + Returns + ------- + kernel : ndarray + The kernel containing the surface intensity of the top half + of the ellipsoid. + + See Also + -------- + rolling_ball + """ + + shape = np.asarray(shape) + semi_axis = np.clip(shape // 2, 1, None) + + kernel_coords = np.stack( + np.meshgrid(*[np.arange(-x, x + 1) for x in semi_axis], indexing='ij'), axis=-1 + ) + + intensity_scaling = 1 - np.sum((kernel_coords / semi_axis) ** 2, axis=-1) + kernel = intensity * np.sqrt(np.clip(intensity_scaling, 0, None)) + kernel[intensity_scaling < 0] = np.inf + + return kernel diff --git a/envs/kitoverlay/skimage/restoration/deconvolution.py b/envs/kitoverlay/skimage/restoration/deconvolution.py new file mode 100644 index 0000000000000000000000000000000000000000..a98b5e35247dab67d8b2ec3ca9bfa23da2bc6f4c --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/deconvolution.py @@ -0,0 +1,422 @@ +"""Implementation of various restoration functions.""" + +import numpy as np +from scipy.signal import convolve + +from .._shared.utils import _supported_float_type +from . import uft + + +def wiener(image, psf, balance, reg=None, is_real=True, clip=True): + r"""Restore image using Wiener–Hunt deconvolution. + + Wiener–Hunt deconvolution is a restoration method which follows a Bayesian + approach [1]_. + + Parameters + ---------- + image : (N1, N2, ..., ND) ndarray + Degraded image. + psf : ndarray + Point spread function (PSF). Assumed to be the impulse + response (input image space) if the data type is real, or the + transfer function (Fourier or frequency space) if the data type is + complex. There is no constraint on the shape of the impulse + response. The transfer function though must be of shape + `(N1, N2, ..., ND)` if `is_real is True`, + `(N1, N2, ..., ND // 2 + 1)` otherwise (see :func:`numpy.fft.rfftn`). + balance : float + Regularization parameter. Denoted by :math:`\lambda`: in the Notes + section below, its value lets you balance data adequacy (improving + frequency restoration) with respect to prior adequacy (reducing + frequency restoration and avoiding noise artifacts). A larger value for + this parameter favors the regularization/prior. + reg : ndarray, optional + Regularization operator. Laplacian by default. It can + be an impulse response or a transfer function, as for the PSF. + Shape constraints are the same as for `psf`. + is_real : bool, optional + True by default. Specify if `psf` and `reg` are provided over just half + the frequency space (thanks to the redundancy of the Fourier transform + for real signals). Applies only if `psf` and/or `reg` are + provided as transfer functions. + See ``uft`` module and :func:`np.fft.rfftn`. + clip : bool, optional + True by default. If True, pixel values of the deconvolved image (which + is the return value) above 1 (resp. below -1) are clipped to 1 (resp. + to -1). Be careful to set `clip=False` if you do not want this clipping + and/or if your data range is not [0, 1] or [-1,1]. + + Returns + ------- + im_deconv : (N1, N2, ..., ND) ndarray + The deconvolved image. + + Examples + -------- + >>> import skimage as ski + >>> import scipy as sp + >>> img = ski.color.rgb2gray(ski.data.astronaut()) + >>> psf = np.ones((5, 5)) / 25 + >>> img = sp.signal.convolve2d(img, psf, 'same') + >>> rng = np.random.default_rng() + >>> img += 0.1 * img.std() * rng.standard_normal(img.shape) + >>> deconvolved_img = ski.restoration.wiener(img, psf, 0.1) + + Notes + ----- + This function applies the Wiener filter to a noisy (degraded) + image by an impulse response (or PSF). If the data model is + + .. math:: y = Hx + n + + where :math:`n` is noise, :math:`H` the PSF, and :math:`x` the + unknown original image, the Wiener filter is + + .. math:: + \hat x = F^\dagger \left( |\Lambda_H|^2 + \lambda |\Lambda_D|^2 \right)^{-1} + \Lambda_H^\dagger F y + + where :math:`F` and :math:`F^\dagger` are the Fourier and inverse + Fourier transforms respectively, :math:`\Lambda_H` the transfer + function (or the Fourier transform of the PSF, see [2]_), + and :math:`\Lambda_D` the regularization operator, which is a filter + penalizing the restored image frequencies (Laplacian by default, that is, + penalization of high frequencies). The parameter :math:`\lambda` tunes the + balance between data (which tends to increase high frequencies, even those + coming from noise) and regularization/prior (which tends to avoid noise + artifacts). + + These methods are then specific to a prior model. Consequently, + the application or the true image nature must correspond to the + prior model. By default, the prior model (Laplacian) introduces + image smoothness or pixel correlation. It can also be interpreted + as high-frequency penalization to compensate for the instability of + the solution with respect to the data (sometimes called noise + amplification or "explosive" solution). + + Finally, the use of Fourier space implies a circulant property of + :math:`H`, see [2]_. + + References + ---------- + .. [1] François Orieux, Jean-François Giovannelli, and Thomas + Rodet, "Bayesian estimation of regularization and point + spread function parameters for Wiener–Hunt deconvolution", + J. Opt. Soc. Am. A 27, 1593–1607 (2010) + https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 + https://hal.archives-ouvertes.fr/hal-00674508 + + .. [2] B. R. Hunt "A matrix theory proof of the discrete + convolution theorem", IEEE Trans. on Audio and + Electroacoustics, vol. au-19, no. 4, pp. 285–288, dec. 1971 + """ + if reg is None: + reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) + if not np.iscomplexobj(reg): + reg = uft.ir2tf(reg, image.shape, is_real=is_real) + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.real.astype(float_type, copy=False) + reg = reg.real.astype(float_type, copy=False) + + if psf.shape != reg.shape: + trans_func = uft.ir2tf(psf, image.shape, is_real=is_real) + else: + trans_func = psf + + wiener_filter = np.conj(trans_func) / ( + np.abs(trans_func) ** 2 + balance * np.abs(reg) ** 2 + ) + if is_real: + deconv = uft.uirfftn(wiener_filter * uft.urfftn(image), shape=image.shape) + else: + deconv = uft.uifftn(wiener_filter * uft.ufftn(image)) + + if clip: + deconv[deconv > 1] = 1 + deconv[deconv < -1] = -1 + + return deconv + + +def unsupervised_wiener( + image, psf, reg=None, user_params=None, is_real=True, clip=True, *, rng=None +): + """Unsupervised Wiener-Hunt deconvolution. + + Return the deconvolution with a Wiener-Hunt approach, where the + hyperparameters are automatically estimated. The algorithm is a + stochastic iterative process (Gibbs sampler) described in the + reference below. See also ``wiener`` function. + + Parameters + ---------- + image : (M, N) ndarray + The input degraded image. + psf : ndarray + The impulse response (input image's space) or the transfer + function (Fourier space). Both are accepted. The transfer + function is automatically recognized as being complex + (``np.iscomplexobj(psf)``). + reg : ndarray, optional + The regularisation operator. The Laplacian by default. It can + be an impulse response or a transfer function, as for the psf. + user_params : dict, optional + Dictionary of parameters for the Gibbs sampler. Accepted keys are: + + threshold : float + The stopping criterion: the norm of the difference between to + successive approximated solution (empirical mean of object + samples, see Notes section). 1e-4 by default. + burnin : int + The number of sample to ignore to start computation of the + mean. 15 by default. + min_num_iter : int + The minimum number of iterations. 30 by default. + max_num_iter : int + The maximum number of iterations if ``threshold`` is not + satisfied. 200 by default. + callback : callable + A user provided callable to which is passed, if the function + exists, the current image sample for whatever purpose. The user + can store the sample, or compute other moments than the + mean. It has no influence on the algorithm execution and is + only for inspection. + + clip : bool, optional + True by default. If true, pixel values of the result above 1 or + under -1 are thresholded for skimage pipeline compatibility. + 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. + + .. versionadded:: 0.19 + + Returns + ------- + x_postmean : (M, N) ndarray + The deconvolved image (the posterior mean). + chains : dict + The keys ``noise`` and ``prior`` contain the chain list of + noise and prior precision respectively. + + Examples + -------- + >>> from skimage import color, data, restoration + >>> img = color.rgb2gray(data.astronaut()) + >>> from scipy.signal import convolve2d + >>> psf = np.ones((5, 5)) / 25 + >>> img = convolve2d(img, psf, 'same') + >>> rng = np.random.default_rng() + >>> img += 0.1 * img.std() * rng.standard_normal(img.shape) + >>> deconvolved_img = restoration.unsupervised_wiener(img, psf) + + Notes + ----- + The estimated image is design as the posterior mean of a + probability law (from a Bayesian analysis). The mean is defined as + a sum over all the possible images weighted by their respective + probability. Given the size of the problem, the exact sum is not + tractable. This algorithm use of MCMC to draw image under the + posterior law. The practical idea is to only draw highly probable + images since they have the biggest contribution to the mean. At the + opposite, the less probable images are drawn less often since + their contribution is low. Finally, the empirical mean of these + samples give us an estimation of the mean, and an exact + computation with an infinite sample set. + + References + ---------- + .. [1] François Orieux, Jean-François Giovannelli, and Thomas + Rodet, "Bayesian estimation of regularization and point + spread function parameters for Wiener-Hunt deconvolution", + J. Opt. Soc. Am. A 27, 1593-1607 (2010) + + https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593 + + https://hal.archives-ouvertes.fr/hal-00674508 + """ + params = { + 'threshold': 1e-4, + 'max_num_iter': 200, + 'min_num_iter': 30, + 'burnin': 15, + 'callback': None, + } + params.update(user_params or {}) + + if reg is None: + reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) + if not np.iscomplexobj(reg): + reg = uft.ir2tf(reg, image.shape, is_real=is_real) + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.real.astype(float_type, copy=False) + reg = reg.real.astype(float_type, copy=False) + + if psf.shape != reg.shape: + trans_fct = uft.ir2tf(psf, image.shape, is_real=is_real) + else: + trans_fct = psf + + # The mean of the object + x_postmean = np.zeros(trans_fct.shape, dtype=float_type) + # The previous computed mean in the iterative loop + prev_x_postmean = np.zeros(trans_fct.shape, dtype=float_type) + + # Difference between two successive mean + delta = np.nan + + # Initial state of the chain + gn_chain, gx_chain = [1], [1] + + # The correlation of the object in Fourier space (if size is big, + # this can reduce computation time in the loop) + areg2 = np.abs(reg) ** 2 + atf2 = np.abs(trans_fct) ** 2 + + # The Fourier transform may change the image.size attribute, so we + # store it. + if is_real: + data_spectrum = uft.urfft2(image) + else: + data_spectrum = uft.ufft2(image) + + rng = np.random.default_rng(rng) + + # Gibbs sampling + for iteration in range(params['max_num_iter']): + # Sample of Eq. 27 p(circX^k | gn^k-1, gx^k-1, y). + + # weighting (correlation in direct space) + precision = gn_chain[-1] * atf2 + gx_chain[-1] * areg2 # Eq. 29 + # Note: Use astype instead of dtype argument to standard_normal to get + # similar random values across precisions, as needed for + # reference data used by test_unsupervised_wiener. + _rand1 = rng.standard_normal(data_spectrum.shape) + _rand1 = _rand1.astype(float_type, copy=False) + _rand2 = rng.standard_normal(data_spectrum.shape) + _rand2 = _rand2.astype(float_type, copy=False) + excursion = np.sqrt(0.5 / precision) * (_rand1 + 1j * _rand2) + + # mean Eq. 30 (RLS for fixed gn, gamma0 and gamma1 ...) + wiener_filter = gn_chain[-1] * np.conj(trans_fct) / precision + + # sample of X in Fourier space + x_sample = wiener_filter * data_spectrum + excursion + if params['callback']: + params['callback'](x_sample) + + # sample of Eq. 31 p(gn | x^k, gx^k, y) + gn_chain.append( + rng.gamma( + image.size / 2, + 2 / uft.image_quad_norm(data_spectrum - x_sample * trans_fct), + ) + ) + + # sample of Eq. 31 p(gx | x^k, gn^k-1, y) + gx_chain.append( + rng.gamma((image.size - 1) / 2, 2 / uft.image_quad_norm(x_sample * reg)) + ) + + # current empirical average + if iteration > params['burnin']: + x_postmean = prev_x_postmean + x_sample + + if iteration > (params['burnin'] + 1): + current = x_postmean / (iteration - params['burnin']) + previous = prev_x_postmean / (iteration - params['burnin'] - 1) + + delta = ( + np.sum(np.abs(current - previous)) + / np.sum(np.abs(x_postmean)) + / (iteration - params['burnin']) + ) + + prev_x_postmean = x_postmean + + # stop of the algorithm + if (iteration > params['min_num_iter']) and (delta < params['threshold']): + break + + # Empirical average \approx POSTMEAN Eq. 44 + x_postmean = x_postmean / (iteration - params['burnin']) + if is_real: + x_postmean = uft.uirfft2(x_postmean, shape=image.shape) + else: + x_postmean = uft.uifft2(x_postmean) + + if clip: + x_postmean[x_postmean > 1] = 1 + x_postmean[x_postmean < -1] = -1 + + return (x_postmean, {'noise': gn_chain, 'prior': gx_chain}) + + +def richardson_lucy(image, psf, num_iter=50, clip=True, filter_epsilon=None): + """Richardson-Lucy deconvolution. + + Parameters + ---------- + image : ([P, ]M, N) ndarray + Input degraded image (can be n-dimensional). If you keep the + default `clip=True` parameter, you may want to normalize + the image so that its values fall in the [-1, 1] interval to avoid + information loss. + psf : ndarray + The point spread function. + num_iter : int, optional + Number of iterations. This parameter plays the role of + regularisation. + clip : bool, optional + True by default. If true, pixel value of the result above 1 or + under -1 are thresholded for skimage pipeline compatibility. + filter_epsilon : float, optional + Value below which intermediate results become 0 to avoid division + by small numbers. + + Returns + ------- + im_deconv : ndarray + The deconvolved image. + + Examples + -------- + >>> from skimage import img_as_float, data, restoration + >>> camera = img_as_float(data.camera()) + >>> from scipy.signal import convolve2d + >>> psf = np.ones((5, 5)) / 25 + >>> camera = convolve2d(camera, psf, 'same') + >>> rng = np.random.default_rng() + >>> camera += 0.1 * camera.std() * rng.standard_normal(camera.shape) + >>> deconvolved = restoration.richardson_lucy(camera, psf, 5) + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution + """ + float_type = _supported_float_type(image.dtype) + image = image.astype(float_type, copy=False) + psf = psf.astype(float_type, copy=False) + im_deconv = np.full(image.shape, 0.5, dtype=float_type) + psf_mirror = np.flip(psf) + + # Small regularization parameter used to avoid 0 divisions + eps = 1e-12 + + for _ in range(num_iter): + conv = convolve(im_deconv, psf, mode='same') + eps + if filter_epsilon: + relative_blur = np.where(conv < filter_epsilon, 0, image / conv) + else: + relative_blur = image / conv + im_deconv *= convolve(relative_blur, psf_mirror, mode='same') + + if clip: + im_deconv[im_deconv > 1] = 1 + im_deconv[im_deconv < -1] = -1 + + return im_deconv diff --git a/envs/kitoverlay/skimage/restoration/inpaint.py b/envs/kitoverlay/skimage/restoration/inpaint.py new file mode 100644 index 0000000000000000000000000000000000000000..931206c9bf453566ca6003d17d2ca44647d278dd --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/inpaint.py @@ -0,0 +1,340 @@ +import numpy as np +from scipy import sparse +from scipy.sparse.linalg import spsolve +import scipy.ndimage as ndi +from scipy.ndimage import laplace + +import skimage +from .._shared import utils +from ..measure import label +from ._inpaint import _build_matrix_inner + + +def _get_neighborhood(nd_idx, radius, nd_shape): + bounds_lo = np.maximum(nd_idx - radius, 0) + bounds_hi = np.minimum(nd_idx + radius + 1, nd_shape) + return bounds_lo, bounds_hi + + +def _get_neigh_coef(shape, center, dtype=float): + # Create biharmonic coefficients ndarray + neigh_coef = np.zeros(shape, dtype=dtype) + neigh_coef[center] = 1 + neigh_coef = laplace(laplace(neigh_coef)) + + # extract non-zero locations and values + coef_idx = np.where(neigh_coef) + coef_vals = neigh_coef[coef_idx] + + coef_idx = np.stack(coef_idx, axis=0) + return neigh_coef, coef_idx, coef_vals + + +def _inpaint_biharmonic_single_region( + image, mask, out, neigh_coef_full, coef_vals, raveled_offsets +): + """Solve a (sparse) linear system corresponding to biharmonic inpainting. + + This function creates a linear system of the form: + + ``A @ u = b`` + + where ``A`` is a sparse matrix, ``b`` is a vector enforcing smoothness and + boundary constraints and ``u`` is the vector of inpainted values to be + (uniquely) determined by solving the linear system. + + ``A`` is a sparse matrix of shape (n_mask, n_mask) where ``n_mask`` + corresponds to the number of non-zero values in ``mask`` (i.e. the number + of pixels to be inpainted). Each row in A will have a number of non-zero + values equal to the number of non-zero values in the biharmonic kernel, + ``neigh_coef_full``. In practice, biharmonic kernels with reduced extent + are used at the image borders. This matrix, ``A`` is the same for all + image channels (since the same inpainting mask is currently used for all + channels). + + ``u`` is a dense matrix of shape ``(n_mask, n_channels)`` and represents + the vector of unknown values for each channel. + + ``b`` is a dense matrix of shape ``(n_mask, n_channels)`` and represents + the desired output of convolving the solution with the biharmonic kernel. + At mask locations where there is no overlap with known values, ``b`` will + have a value of 0. This enforces the biharmonic smoothness constraint in + the interior of inpainting regions. For regions near the boundary that + overlap with known values, the entries in ``b`` enforce boundary conditions + designed to avoid discontinuity with the known values. + """ + + n_channels = out.shape[-1] + radius = neigh_coef_full.shape[0] // 2 + + edge_mask = np.ones(mask.shape, dtype=bool) + edge_mask[(slice(radius, -radius),) * mask.ndim] = 0 + boundary_mask = edge_mask * mask + center_mask = ~edge_mask * mask + + boundary_pts = np.where(boundary_mask) + boundary_i = np.flatnonzero(boundary_mask) + center_i = np.flatnonzero(center_mask) + mask_i = np.concatenate((boundary_i, center_i)) + + center_pts = np.where(center_mask) + mask_pts = tuple([np.concatenate((b, c)) for b, c in zip(boundary_pts, center_pts)]) + + # Use convolution to predetermine the number of non-zero entries in the + # sparse system matrix. + structure = neigh_coef_full != 0 + tmp = ndi.convolve(mask, structure, output=np.uint8, mode='constant') + nnz_matrix = tmp[mask].sum() + + # Need to estimate the number of zeros for the right hand side vector. + # The computation below will slightly overestimate the true number of zeros + # due to edge effects (the kernel itself gets shrunk in size near the + # edges, but that isn't accounted for here). We can trim any excess entries + # later. + n_mask = np.count_nonzero(mask) + n_struct = np.count_nonzero(structure) + nnz_rhs_vector_max = n_mask - np.count_nonzero(tmp == n_struct) + + # pre-allocate arrays storing sparse matrix indices and values + row_idx_known = np.empty(nnz_rhs_vector_max, dtype=np.intp) + data_known = np.zeros((nnz_rhs_vector_max, n_channels), dtype=out.dtype) + row_idx_unknown = np.empty(nnz_matrix, dtype=np.intp) + col_idx_unknown = np.empty(nnz_matrix, dtype=np.intp) + data_unknown = np.empty(nnz_matrix, dtype=out.dtype) + + # cache the various small, non-square Laplacians used near the boundary + coef_cache = {} + + # Iterate over masked points near the boundary + mask_flat = mask.reshape(-1) + out_flat = np.ascontiguousarray(out.reshape((-1, n_channels))) + idx_known = 0 + idx_unknown = 0 + mask_pt_n = -1 + boundary_pts = np.stack(boundary_pts, axis=1) + for mask_pt_n, nd_idx in enumerate(boundary_pts): + # Get bounded neighborhood of selected radius + b_lo, b_hi = _get_neighborhood(nd_idx, radius, mask.shape) + + # Create (truncated) biharmonic coefficients ndarray + coef_shape = tuple(b_hi - b_lo) + coef_center = tuple(nd_idx - b_lo) + coef_idx, coefs = coef_cache.get((coef_shape, coef_center), (None, None)) + if coef_idx is None: + _, coef_idx, coefs = _get_neigh_coef( + coef_shape, coef_center, dtype=out.dtype + ) + coef_cache[(coef_shape, coef_center)] = (coef_idx, coefs) + + # compute corresponding 1d indices into the mask + coef_idx = coef_idx + b_lo[:, np.newaxis] + index1d = np.ravel_multi_index(coef_idx, mask.shape) + + # Iterate over masked point's neighborhood + nvals = 0 + for coef, i in zip(coefs, index1d): + if mask_flat[i]: + row_idx_unknown[idx_unknown] = mask_pt_n + col_idx_unknown[idx_unknown] = i + data_unknown[idx_unknown] = coef + idx_unknown += 1 + else: + data_known[idx_known, :] -= coef * out_flat[i, :] + nvals += 1 + if nvals: + row_idx_known[idx_known] = mask_pt_n + idx_known += 1 + + # Call an efficient Cython-based implementation for all interior points + row_start = mask_pt_n + 1 + known_start_idx = idx_known + unknown_start_idx = idx_unknown + nnz_rhs = _build_matrix_inner( + # starting indices + row_start, + known_start_idx, + unknown_start_idx, + # input arrays + center_i, + raveled_offsets, + coef_vals, + mask_flat, + out_flat, + # output arrays + row_idx_known, + data_known, + row_idx_unknown, + col_idx_unknown, + data_unknown, + ) + + # trim RHS vector values and indices to the exact length + row_idx_known = row_idx_known[:nnz_rhs] + data_known = data_known[:nnz_rhs, :] + + # Form sparse matrix of unknown values + sp_shape = (n_mask, out.size) + matrix_unknown = sparse.csr_array( + (data_unknown, (row_idx_unknown, col_idx_unknown)), shape=sp_shape + ) + + # Solve linear system for masked points + matrix_unknown = matrix_unknown[:, mask_i] + + # dense vectors representing the right hand side for each channel + rhs = np.zeros((n_mask, n_channels), dtype=out.dtype) + rhs[row_idx_known, :] = data_known + + # set use_umfpack to False so float32 data is supported + result = spsolve(matrix_unknown, rhs, use_umfpack=False, permc_spec='MMD_ATA') + if result.ndim == 1: + result = result[:, np.newaxis] + + out[mask_pts] = result + return out + + +@utils.channel_as_last_axis() +def inpaint_biharmonic(image, mask, *, split_into_regions=False, channel_axis=None): + """Inpaint masked points in image with biharmonic equations. + + Parameters + ---------- + image : (M[, N[, ..., P]][, C]) ndarray + Input image. + mask : (M[, N[, ..., P]]) ndarray + Array of pixels to be inpainted. Have to be the same shape as one + of the 'image' channels. Unknown pixels have to be represented with 1, + known pixels - with 0. + split_into_regions : bool, optional + If True, inpainting is performed on a region-by-region basis. This is + likely to be slower, but will have reduced memory requirements. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + out : (M[, N[, ..., P]][, C]) ndarray + Input image with masked pixels inpainted. + + References + ---------- + .. [1] S.B.Damelin and N.S.Hoang. "On Surface Completion and Image + Inpainting by Biharmonic Functions: Numerical Aspects", + International Journal of Mathematics and Mathematical Sciences, + Vol. 2018, Article ID 3950312 + :DOI:`10.1155/2018/3950312` + .. [2] C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of + Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., + 28 (2010), 104-113, + :DOI:`10.1016/j.acha.2009.04.004` + + Examples + -------- + >>> img = np.tile(np.square(np.linspace(0, 1, 5)), (5, 1)) + >>> mask = np.zeros_like(img) + >>> mask[2, 2:] = 1 + >>> mask[1, 3:] = 1 + >>> mask[0, 4:] = 1 + >>> out = inpaint_biharmonic(img, mask) + """ + + if image.ndim < 1: + raise ValueError('Input array has to be at least 1D') + + multichannel = channel_axis is not None + img_baseshape = image.shape[:-1] if multichannel else image.shape + if img_baseshape != mask.shape: + raise ValueError('Input arrays have to be the same shape') + + if np.ma.isMaskedArray(image): + raise TypeError('Masked arrays are not supported') + + image = skimage.img_as_float(image) + + # float16->float32 and float128->float64 + float_dtype = utils._supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + mask = mask.astype(bool, copy=False) + if not multichannel: + image = image[..., np.newaxis] + out = np.copy(image, order='C') + + # Create biharmonic coefficients ndarray + radius = 2 + coef_shape = (2 * radius + 1,) * mask.ndim + coef_center = (radius,) * mask.ndim + neigh_coef_full, coef_idx, coef_vals = _get_neigh_coef( + coef_shape, coef_center, dtype=out.dtype + ) + + # stride for the last spatial dimension + channel_stride_bytes = out.strides[-2] + + # offsets to all neighboring non-zero elements in the footprint + offsets = coef_idx - radius + + # determine per-channel intensity limits + known_points = image[~mask] + limits = (known_points.min(axis=0), known_points.max(axis=0)) + + if split_into_regions: + # Split inpainting mask into independent regions + kernel = ndi.generate_binary_structure(mask.ndim, 1) + mask_dilated = ndi.binary_dilation(mask, structure=kernel) + mask_labeled = label(mask_dilated) + mask_labeled *= mask + + bbox_slices = ndi.find_objects(mask_labeled) + + for idx_region, bb_slice in enumerate(bbox_slices, 1): + # expand object bounding boxes by the biharmonic kernel radius + roi_sl = tuple( + slice(max(sl.start - radius, 0), min(sl.stop + radius, size)) + for sl, size in zip(bb_slice, mask_labeled.shape) + ) + # extract only the region surrounding the label of interest + mask_region = mask_labeled[roi_sl] == idx_region + # add slice for axes + roi_sl += (slice(None),) + # copy for contiguity and to account for possible ROI overlap + otmp = out[roi_sl].copy() + + # compute raveled offsets for the ROI + ostrides = np.array( + [s // channel_stride_bytes for s in otmp[..., 0].strides] + ) + raveled_offsets = np.sum(offsets * ostrides[..., np.newaxis], axis=0) + + _inpaint_biharmonic_single_region( + image[roi_sl], + mask_region, + otmp, + neigh_coef_full, + coef_vals, + raveled_offsets, + ) + # assign output to the + out[roi_sl] = otmp + else: + # compute raveled offsets for output image + ostrides = np.array([s // channel_stride_bytes for s in out[..., 0].strides]) + raveled_offsets = np.sum(offsets * ostrides[..., np.newaxis], axis=0) + + _inpaint_biharmonic_single_region( + image, mask, out, neigh_coef_full, coef_vals, raveled_offsets + ) + + # Handle enormous values on a per-channel basis + np.clip(out, a_min=limits[0], a_max=limits[1], out=out) + + if not multichannel: + out = out[..., 0] + + return out diff --git a/envs/kitoverlay/skimage/restoration/j_invariant.py b/envs/kitoverlay/skimage/restoration/j_invariant.py new file mode 100644 index 0000000000000000000000000000000000000000..e799de8281e6a6c0845562b1131e32f303c989e1 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/j_invariant.py @@ -0,0 +1,358 @@ +import itertools +import functools + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type +from ..metrics import mean_squared_error +from ..util import img_as_float + + +def _interpolate_image(image, *, multichannel=False): + """Replacing each pixel in ``image`` with the average of its neighbors. + + Parameters + ---------- + image : ndarray + Input data to be interpolated. + multichannel : bool, optional + Whether the last axis of the image is to be interpreted as multiple + channels or another spatial dimension. + + Returns + ------- + interp : ndarray + Interpolated version of `image`. + """ + spatialdims = image.ndim if not multichannel else image.ndim - 1 + conv_filter = ndi.generate_binary_structure(spatialdims, 1).astype(image.dtype) + conv_filter.ravel()[conv_filter.size // 2] = 0 + conv_filter /= conv_filter.sum() + + if multichannel: + interp = np.zeros_like(image) + for i in range(image.shape[-1]): + interp[..., i] = ndi.convolve(image[..., i], conv_filter, mode='mirror') + else: + interp = ndi.convolve(image, conv_filter, mode='mirror') + return interp + + +def _generate_grid_slice(shape, *, offset, stride=3): + """Generate slices of uniformly-spaced points in an array. + + Parameters + ---------- + shape : tuple of int + Shape of the mask. + offset : int + The offset of the grid of ones. Iterating over ``offset`` will cover + the entire array. It should be between 0 and ``stride ** ndim``, not + inclusive, where ``ndim = len(shape)``. + stride : int, optional + The spacing between ones, used in each dimension. + + Returns + ------- + mask : ndarray + The mask. + + Examples + -------- + >>> shape = (4, 4) + >>> array = np.zeros(shape, dtype=int) + >>> grid_slice = _generate_grid_slice(shape, offset=0, stride=2) + >>> array[grid_slice] = 1 + >>> print(array) + [[1 0 1 0] + [0 0 0 0] + [1 0 1 0] + [0 0 0 0]] + + Changing the offset moves the location of the 1s: + + >>> array = np.zeros(shape, dtype=int) + >>> grid_slice = _generate_grid_slice(shape, offset=3, stride=2) + >>> array[grid_slice] = 1 + >>> print(array) + [[0 0 0 0] + [0 1 0 1] + [0 0 0 0] + [0 1 0 1]] + """ + phases = np.unravel_index(offset, (stride,) * len(shape)) + mask = tuple(slice(p, None, stride) for p in phases) + + return mask + + +def denoise_invariant( + image, denoise_function, *, stride=4, masks=None, denoiser_kwargs=None +): + """Apply a J-invariant version of a denoising function. + + Parameters + ---------- + image : ndarray (M[, N[, ...]][, C]) of ints, uints or floats + Input data to be denoised. `image` can be of any numeric type, + but it is cast into a ndarray of floats (using `img_as_float`) for the + computation of the denoised image. + denoise_function : function + Original denoising function. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + masks : list of ndarray, optional + Set of masks to use for computing J-invariant output. If `None`, + a full set of masks covering the image will be used. + denoiser_kwargs : + Keyword arguments passed to `denoise_function`. + + Returns + ------- + output : ndarray + Denoised image, of same shape as `image`. + + Notes + ----- + A denoising function is J-invariant if the prediction it makes for each + pixel does not depend on the value of that pixel in the original image. + The prediction for each pixel may instead use all the relevant information + contained in the rest of the image, which is typically quite significant. + Any function can be converted into a J-invariant one using a simple masking + procedure, as described in [1]. + + The pixel-wise error of a J-invariant denoiser is uncorrelated to the noise, + so long as the noise in each pixel is independent. Consequently, the average + difference between the denoised image and the oisy image, the + *self-supervised loss*, is the same as the difference between the denoised + image and the original clean image, the *ground-truth loss* (up to a + constant). + + This means that the best J-invariant denoiser for a given image can be found + using the noisy data alone, by selecting the denoiser minimizing the self- + supervised loss. + + References + ---------- + .. [1] J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, + International Conference on Machine Learning, p. 524-533 (2019). + + Examples + -------- + >>> import skimage + >>> from skimage.restoration import denoise_invariant, denoise_tv_chambolle + >>> image = skimage.util.img_as_float(skimage.data.chelsea()) + >>> noisy = skimage.util.random_noise(image, var=0.2 ** 2) + >>> denoised = denoise_invariant(noisy, denoise_function=denoise_tv_chambolle) # doctest: +SKIP + """ + image = img_as_float(image) + + # promote float16->float32 if needed + float_dtype = _supported_float_type(image.dtype) + image = image.astype(float_dtype, copy=False) + + if denoiser_kwargs is None: + denoiser_kwargs = {} + + multichannel = denoiser_kwargs.get('channel_axis', None) is not None + interp = _interpolate_image(image, multichannel=multichannel) + output = np.zeros_like(image) + + if masks is None: + spatialdims = image.ndim if not multichannel else image.ndim - 1 + n_masks = stride**spatialdims + masks = ( + _generate_grid_slice(image.shape[:spatialdims], offset=idx, stride=stride) + for idx in range(n_masks) + ) + + for mask in masks: + input_image = image.copy() + input_image[mask] = interp[mask] + output[mask] = denoise_function(input_image, **denoiser_kwargs)[mask] + return output + + +def _product_from_dict(dictionary): + """Utility function to convert parameter ranges to parameter combinations. + + Converts a dict of lists into a list of dicts whose values consist of the + cartesian product of the values in the original dict. + + Parameters + ---------- + dictionary : dict of lists + Dictionary of lists to be multiplied. + + Yields + ------ + selections : dicts of values + Dicts containing individual combinations of the values in the input + dict. + """ + keys = dictionary.keys() + for element in itertools.product(*dictionary.values()): + yield dict(zip(keys, element)) + + +def calibrate_denoiser( + image, + denoise_function, + denoise_parameters, + *, + stride=4, + approximate_loss=True, + extra_output=False, +): + """Calibrate a denoising function and return optimal J-invariant version. + + The returned function is partially evaluated with optimal parameter values + set for denoising the input image. + + Parameters + ---------- + image : ndarray + Input data to be denoised (converted using `img_as_float`). + denoise_function : function + Denoising function to be calibrated. + denoise_parameters : dict of list + Ranges of parameters for `denoise_function` to be calibrated over. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + approximate_loss : bool, optional + Whether to approximate the self-supervised loss used to evaluate the + denoiser by only computing it on one masked version of the image. + If False, the runtime will be a factor of `stride**image.ndim` longer. + extra_output : bool, optional + If True, return parameters and losses in addition to the calibrated + denoising function + + Returns + ------- + best_denoise_function : function + The optimal J-invariant version of `denoise_function`. + + If `extra_output` is True, the following tuple is also returned: + + (parameters_tested, losses) : tuple (list of dict, list of int) + List of parameters tested for `denoise_function`, as a dictionary of + kwargs + Self-supervised loss for each set of parameters in `parameters_tested`. + + + Notes + ----- + + The calibration procedure uses a self-supervised mean-square-error loss + to evaluate the performance of J-invariant versions of `denoise_function`. + The minimizer of the self-supervised loss is also the minimizer of the + ground-truth loss (i.e., the true MSE error) [1]. The returned function + can be used on the original noisy image, or other images with similar + characteristics. + + Increasing the stride increases the performance of `best_denoise_function` + at the expense of increasing its runtime. It has no effect on the runtime + of the calibration. + + References + ---------- + .. [1] J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, + International Conference on Machine Learning, p. 524-533 (2019). + + Examples + -------- + >>> from skimage import color, data + >>> from skimage.restoration import denoise_tv_chambolle + >>> import numpy as np + >>> img = color.rgb2gray(data.astronaut()[:50, :50]) + >>> rng = np.random.default_rng() + >>> noisy = img + 0.5 * img.std() * rng.standard_normal(img.shape) + >>> parameters = {'weight': np.arange(0.01, 0.3, 0.02)} + >>> denoising_function = calibrate_denoiser(noisy, denoise_tv_chambolle, + ... denoise_parameters=parameters) + >>> denoised_img = denoising_function(img) + + """ + parameters_tested, losses = _calibrate_denoiser_search( + image, + denoise_function, + denoise_parameters=denoise_parameters, + stride=stride, + approximate_loss=approximate_loss, + ) + + idx = np.argmin(losses) + best_parameters = parameters_tested[idx] + + best_denoise_function = functools.partial( + denoise_invariant, + denoise_function=denoise_function, + stride=stride, + denoiser_kwargs=best_parameters, + ) + + if extra_output: + return best_denoise_function, (parameters_tested, losses) + else: + return best_denoise_function + + +def _calibrate_denoiser_search( + image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True +): + """Return a parameter search history with losses for a denoise function. + + Parameters + ---------- + image : ndarray + Input data to be denoised (converted using `img_as_float`). + denoise_function : function + Denoising function to be calibrated. + denoise_parameters : dict of list + Ranges of parameters for `denoise_function` to be calibrated over. + stride : int, optional + Stride used in masking procedure that converts `denoise_function` + to J-invariance. + approximate_loss : bool, optional + Whether to approximate the self-supervised loss used to evaluate the + denoiser by only computing it on one masked version of the image. + If False, the runtime will be a factor of `stride**image.ndim` longer. + + Returns + ------- + parameters_tested : list of dict + List of parameters tested for `denoise_function`, as a dictionary of + kwargs. + losses : list of int + Self-supervised loss for each set of parameters in `parameters_tested`. + """ + image = img_as_float(image) + parameters_tested = list(_product_from_dict(denoise_parameters)) + losses = [] + + for denoiser_kwargs in parameters_tested: + multichannel = denoiser_kwargs.get('channel_axis', None) is not None + if not approximate_loss: + denoised = denoise_invariant( + image, denoise_function, stride=stride, denoiser_kwargs=denoiser_kwargs + ) + loss = mean_squared_error(image, denoised) + else: + spatialdims = image.ndim if not multichannel else image.ndim - 1 + n_masks = stride**spatialdims + mask = _generate_grid_slice( + image.shape[:spatialdims], offset=n_masks // 2, stride=stride + ) + + masked_denoised = denoise_invariant( + image, denoise_function, masks=[mask], denoiser_kwargs=denoiser_kwargs + ) + + loss = mean_squared_error(image[mask], masked_denoised[mask]) + + losses.append(loss) + + return parameters_tested, losses diff --git a/envs/kitoverlay/skimage/restoration/non_local_means.py b/envs/kitoverlay/skimage/restoration/non_local_means.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f15df00cb831ff23abd71de2269dc070ec6668 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/non_local_means.py @@ -0,0 +1,187 @@ +import numpy as np + +from .._shared import utils +from .._shared.utils import convert_to_float +from ._nl_means_denoising import ( + _nl_means_denoising_2d, + _nl_means_denoising_3d, + _fast_nl_means_denoising_2d, + _fast_nl_means_denoising_3d, + _fast_nl_means_denoising_4d, +) + + +@utils.channel_as_last_axis() +def denoise_nl_means( + image, + patch_size=7, + patch_distance=11, + h=0.1, + fast_mode=True, + sigma=0.0, + *, + preserve_range=False, + channel_axis=None, +): + """Perform non-local means denoising on 2D-4D grayscale or RGB images. + + Parameters + ---------- + image : 2D or 3D ndarray + Input image to be denoised, which can be 2D or 3D, and grayscale + or RGB (for 2D images only, see ``channel_axis`` parameter). There can + be any number of channels (does not strictly have to be RGB). + patch_size : int, optional + Size of patches used for denoising. + patch_distance : int, optional + Maximal distance in pixels where to search patches used for denoising. + h : float, optional + Cut-off distance (in gray levels). The higher h, the more permissive + one is in accepting patches. A higher h results in a smoother image, + at the expense of blurring features. For a Gaussian noise of standard + deviation sigma, a rule of thumb is to choose the value of h to be + sigma of slightly less. + fast_mode : bool, optional + If True (default value), a fast version of the non-local means + algorithm is used. If False, the original version of non-local means is + used. See the Notes section for more details about the algorithms. + sigma : float, optional + The standard deviation of the (Gaussian) noise. If provided, a more + robust computation of patch weights is computed that takes the expected + noise variance into account (see Notes below). + preserve_range : bool, optional + Whether to keep the original range of values. Otherwise, the input + image is converted according to the conventions of `img_as_float`. + Also see https://scikit-image.org/docs/dev/user_guide/data_types.html + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + result : ndarray + Denoised image, of same shape as `image`. + + Notes + ----- + + The non-local means algorithm is well suited for denoising images with + specific textures. The principle of the algorithm is to average the value + of a given pixel with values of other pixels in a limited neighborhood, + provided that the *patches* centered on the other pixels are similar enough + to the patch centered on the pixel of interest. + + In the original version of the algorithm [1]_, corresponding to + ``fast=False``, the computational complexity is:: + + image.size * patch_size ** image.ndim * patch_distance ** image.ndim + + Hence, changing the size of patches or their maximal distance has a + strong effect on computing times, especially for 3-D images. + + However, the default behavior corresponds to ``fast_mode=True``, for which + another version of non-local means [2]_ is used, corresponding to a + complexity of:: + + image.size * patch_distance ** image.ndim + + The computing time depends only weakly on the patch size, thanks to + the computation of the integral of patches distances for a given + shift, that reduces the number of operations [1]_. Therefore, this + algorithm executes faster than the classic algorithm + (``fast_mode=False``), at the expense of using twice as much memory. + This implementation has been proven to be more efficient compared to + other alternatives, see e.g. [3]_. + + Compared to the classic algorithm, all pixels of a patch contribute + to the distance to another patch with the same weight, no matter + their distance to the center of the patch. This coarser computation + of the distance can result in a slightly poorer denoising + performance. Moreover, for small images (images with a linear size + that is only a few times the patch size), the classic algorithm can + be faster due to boundary effects. + + The image is padded using the `reflect` mode of `skimage.util.pad` + before denoising. + + If the noise standard deviation, `sigma`, is provided a more robust + computation of patch weights is used. Subtracting the known noise variance + from the computed patch distances improves the estimates of patch + similarity, giving a moderate improvement to denoising performance [4]_. + It was also mentioned as an option for the fast variant of the algorithm in + [3]_. + + When `sigma` is provided, a smaller `h` should typically be used to + avoid oversmoothing. The optimal value for `h` depends on the image + content and noise level, but a reasonable starting point is + ``h = 0.8 * sigma`` when `fast_mode` is `True`, or ``h = 0.6 * sigma`` when + `fast_mode` is `False`. + + References + ---------- + .. [1] A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image + denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. + :DOI:`10.1109/CVPR.2005.38` + + .. [2] J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast + nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE + International Symposium on Biomedical Imaging: From Nano to Macro, + 2008, pp. 1331-1334. + :DOI:`10.1109/ISBI.2008.4541250` + + .. [3] Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means + Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. + :DOI:`10.5201/ipol.2014.120` + + .. [4] A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. + Image Processing On Line, 2011, vol. 1, pp. 208-212. + :DOI:`10.5201/ipol.2011.bcm_nlm` + + Examples + -------- + >>> a = np.zeros((40, 40)) + >>> a[10:-10, 10:-10] = 1. + >>> rng = np.random.default_rng() + >>> a += 0.3 * rng.standard_normal(a.shape) + >>> denoised_a = denoise_nl_means(a, 7, 5, 0.1) + """ + if channel_axis is None: + multichannel = False + image = image[..., np.newaxis] + else: + multichannel = True + + ndim_no_channel = image.ndim - 1 + if (ndim_no_channel < 2) or (ndim_no_channel > 4): + raise NotImplementedError( + "Non-local means denoising is only implemented for 2D, " + "3D or 4D grayscale or multichannel images." + ) + + image = convert_to_float(image, preserve_range) + if not image.flags.c_contiguous: + image = np.ascontiguousarray(image) + + kwargs = dict(s=patch_size, d=patch_distance, h=h, var=sigma * sigma) + if ndim_no_channel == 2: + nlm_func = _fast_nl_means_denoising_2d if fast_mode else _nl_means_denoising_2d + elif ndim_no_channel == 3: + if multichannel and not fast_mode: + raise NotImplementedError("Multichannel 3D requires fast_mode to be True.") + if fast_mode: + nlm_func = _fast_nl_means_denoising_3d + else: + # have to drop the size 1 channel axis for slow mode + image = image[..., 0] + nlm_func = _nl_means_denoising_3d + elif ndim_no_channel == 4: + if fast_mode: + nlm_func = _fast_nl_means_denoising_4d + else: + raise NotImplementedError("4D requires fast_mode to be True.") + dn = np.asarray(nlm_func(image, **kwargs)) + return dn diff --git a/envs/kitoverlay/skimage/restoration/uft.py b/envs/kitoverlay/skimage/restoration/uft.py new file mode 100644 index 0000000000000000000000000000000000000000..40d1a331223da8ec9b0b27dde5d5b3d16e776229 --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/uft.py @@ -0,0 +1,451 @@ +r"""Function of unitary fourier transform (uft) and utilities + +This module implements the unitary fourier transform, also known as +the ortho-normal transform. It is especially useful for convolution +[1], as it respects the Parseval equality. The value of the null +frequency is equal to + +.. math:: \frac{1}{\sqrt{n}} \sum_i x_i + +so the Fourier transform has the same energy as the original image +(see ``image_quad_norm`` function). The transform is applied from the +last axis for performance (assuming a C-order array input). + +References +---------- +.. [1] B. R. Hunt "A matrix theory proof of the discrete convolution + theorem", IEEE Trans. on Audio and Electroacoustics, + vol. au-19, no. 4, pp. 285-288, dec. 1971 + +""" + +import numpy as np +import scipy.fft as fft + +from .._shared.utils import _supported_float_type + + +def ufftn(inarray, dim=None): + """N-dimensional unitary Fourier transform. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray (same shape than inarray) + The unitary N-D Fourier transform of ``inarray``. + + Examples + -------- + >>> input = np.ones((3, 3, 3)) + >>> output = ufftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (3, 3, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.fftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def uifftn(inarray, dim=None): + """N-dimensional unitary inverse Fourier transform. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray + The unitary inverse nD Fourier transform of ``inarray``. Has the same shape as + ``inarray``. + + Examples + -------- + >>> input = np.ones((3, 3, 3)) + >>> output = uifftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (3, 3, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.ifftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def urfftn(inarray, dim=None): + """N-dimensional real unitary Fourier transform. + + This transform considers the Hermitian property of the transform on + real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + + Returns + ------- + outarray : ndarray, shape (M[, ...], P / 2 + 1) + The unitary N-D real Fourier transform of ``inarray``. + + Notes + ----- + The ``urfft`` functions assume an input array of real + values. Consequently, the output has a Hermitian property and + redundant values are not computed or returned. + + Examples + -------- + >>> input = np.ones((5, 5, 5)) + >>> output = urfftn(input) + >>> np.allclose(np.sum(input) / np.sqrt(input.size), output[0, 0, 0]) + True + >>> output.shape + (5, 5, 3) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.rfftn(inarray, axes=range(-dim, 0), norm='ortho') + return outarray + + +def uirfftn(inarray, dim=None, shape=None): + """N-dimensional inverse real unitary Fourier transform. + + This transform considers the Hermitian property of the transform + from complex to real input. + + Parameters + ---------- + inarray : ndarray + The array to transform. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + shape : tuple of int, optional + The shape of the output. The shape of ``rfft`` is ambiguous in + case of odd-valued input shape. In this case, this parameter + should be provided. See ``np.fft.irfftn``. + + Returns + ------- + outarray : ndarray + The unitary N-D inverse real Fourier transform of ``inarray``. + + Notes + ----- + The ``uirfft`` function assumes that the output array is + real-valued. Consequently, the input is assumed to have a Hermitian + property and redundant values are implicit. + + Examples + -------- + >>> input = np.ones((5, 5, 5)) + >>> output = uirfftn(urfftn(input), shape=input.shape) + >>> np.allclose(input, output) + True + >>> output.shape + (5, 5, 5) + """ + if dim is None: + dim = inarray.ndim + outarray = fft.irfftn(inarray, shape, axes=range(-dim, 0), norm='ortho') + return outarray + + +def ufft2(inarray): + """2-dimensional unitary Fourier transform. + + Compute the Fourier transform on the last 2 axes. + + Parameters + ---------- + inarray : ndarray + The array to transform. + + Returns + ------- + outarray : ndarray (same shape as inarray) + The unitary 2-D Fourier transform of ``inarray``. + + See Also + -------- + uifft2, ufftn, urfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = ufft2(input) + >>> np.allclose(np.sum(input[1, ...]) / np.sqrt(input[1, ...].size), + ... output[1, 0, 0]) + True + >>> output.shape + (10, 128, 128) + """ + return ufftn(inarray, 2) + + +def uifft2(inarray): + """2-dimensional inverse unitary Fourier transform. + + Compute the inverse Fourier transform on the last 2 axes. + + Parameters + ---------- + inarray : ndarray + The array to transform. + + Returns + ------- + outarray : ndarray (same shape as inarray) + The unitary 2-D inverse Fourier transform of ``inarray``. + + See Also + -------- + uifft2, uifftn, uirfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = uifft2(input) + >>> np.allclose(np.sum(input[1, ...]) / np.sqrt(input[1, ...].size), + ... output[0, 0, 0]) + True + >>> output.shape + (10, 128, 128) + """ + return uifftn(inarray, 2) + + +def urfft2(inarray): + """2-dimensional real unitary Fourier transform + + Compute the real Fourier transform on the last 2 axes. This + transform considers the Hermitian property of the transform from + complex to real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + + Returns + ------- + outarray : ndarray, shape (M[, ...], 2 * (P - 1)) + The unitary 2-D real Fourier transform of ``inarray``. + + See Also + -------- + ufft2, ufftn, urfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = urfft2(input) + >>> np.allclose(np.sum(input[1,...]) / np.sqrt(input[1,...].size), + ... output[1, 0, 0]) + True + >>> output.shape + (10, 128, 65) + """ + return urfftn(inarray, 2) + + +def uirfft2(inarray, shape=None): + """2-dimensional inverse real unitary Fourier transform. + + Compute the real inverse Fourier transform on the last 2 axes. + This transform considers the Hermitian property of the transform + from complex to real-valued input. + + Parameters + ---------- + inarray : ndarray, shape (M[, ...], P) + The array to transform. + shape : tuple of int, optional + The shape of the output. The shape of ``rfft`` is ambiguous in + case of odd-valued input shape. In this case, this parameter + should be provided. See ``np.fft.irfftn``. + + Returns + ------- + outarray : ndarray, shape (M[, ...], 2 * (P - 1)) + The unitary 2-D inverse real Fourier transform of ``inarray``. + + See Also + -------- + urfft2, uifftn, uirfftn + + Examples + -------- + >>> input = np.ones((10, 128, 128)) + >>> output = uirfftn(urfftn(input), shape=input.shape) + >>> np.allclose(input, output) + True + >>> output.shape + (10, 128, 128) + """ + return uirfftn(inarray, 2, shape=shape) + + +def image_quad_norm(inarray): + """Return the quadratic norm of images in Fourier space. + + This function detects whether the input image satisfies the + Hermitian property. + + Parameters + ---------- + inarray : ndarray + Input image. The image data should reside in the final two + axes. + + Returns + ------- + norm : float + The quadratic norm of ``inarray``. + + Examples + -------- + >>> input = np.ones((5, 5)) + >>> image_quad_norm(ufft2(input)) == np.sum(np.abs(input)**2) + True + >>> image_quad_norm(ufft2(input)) == image_quad_norm(urfft2(input)) + True + """ + # If there is a Hermitian symmetry + if inarray.shape[-1] != inarray.shape[-2]: + return 2 * np.sum(np.sum(np.abs(inarray) ** 2, axis=-1), axis=-1) - np.sum( + np.abs(inarray[..., 0]) ** 2, axis=-1 + ) + else: + return np.sum(np.sum(np.abs(inarray) ** 2, axis=-1), axis=-1) + + +def ir2tf(imp_resp, shape, dim=None, is_real=True): + """Compute the transfer function of an impulse response (IR). + + This function makes the necessary correct zero-padding, zero + convention, correct fft2, etc... to compute the transfer function + of IR. To use with unitary Fourier transform for the signal (ufftn + or equivalent). + + Parameters + ---------- + imp_resp : ndarray + The impulse responses. + shape : tuple of int + A tuple of integer corresponding to the target shape of the + transfer function. + dim : int, optional + The last axis along which to compute the transform. All + axes by default. + is_real : bool, optional + If True (default), imp_resp is supposed real and the Hermitian property + is used with rfftn Fourier transform. + + Returns + ------- + y : complex ndarray + The transfer function of shape ``shape``. + + See Also + -------- + ufftn, uifftn, urfftn, uirfftn + + Examples + -------- + >>> np.all(np.array([[4, 0], [0, 0]]) == ir2tf(np.ones((2, 2)), (2, 2))) + True + >>> ir2tf(np.ones((2, 2)), (512, 512)).shape == (512, 257) + True + >>> ir2tf(np.ones((2, 2)), (512, 512), is_real=False).shape == (512, 512) + True + + Notes + ----- + The input array can be composed of multiple-dimensional IR with + an arbitrary number of IR. The individual IR must be accessed + through the first axes. The last ``dim`` axes contain the space + definition. + """ + if not dim: + dim = imp_resp.ndim + # Zero padding and fill + irpadded_dtype = _supported_float_type(imp_resp.dtype) + irpadded = np.zeros(shape, dtype=irpadded_dtype) + irpadded[tuple([slice(0, s) for s in imp_resp.shape])] = imp_resp + # Roll for zero convention of the fft to avoid the phase + # problem. Work with odd and even size. + for axis, axis_size in enumerate(imp_resp.shape): + if axis >= imp_resp.ndim - dim: + irpadded = np.roll(irpadded, shift=-int(np.floor(axis_size / 2)), axis=axis) + + func = fft.rfftn if is_real else fft.fftn + out = func(irpadded, axes=(range(-dim, 0))) + + # TODO: remove .astype call once SciPy >= 1.4 is required + cplx_dtype = np.promote_types(irpadded_dtype, np.complex64) + return out.astype(cplx_dtype, copy=False) + + +def laplacian(ndim, shape, is_real=True): + """Return the transfer function of the Laplacian. + + Laplacian is the second order difference, on row and column. + + Parameters + ---------- + ndim : int + The dimension of the Laplacian. + shape : tuple + The support on which to compute the transfer function. + is_real : bool, optional + If True (default), imp_resp is assumed to be real-valued and + the Hermitian property is used with rfftn Fourier transform + to return the transfer function. + + Returns + ------- + tf : array_like, complex + The transfer function. + impr : array_like, real + The Laplacian. + + Examples + -------- + >>> tf, ir = laplacian(2, (32, 32)) + >>> np.all(ir == np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])) + True + >>> np.all(tf == ir2tf(ir, (32, 32))) + True + """ + impr = np.zeros([3] * ndim) + for dim in range(ndim): + idx = tuple( + [slice(1, 2)] * dim + [slice(None)] + [slice(1, 2)] * (ndim - dim - 1) + ) + impr[idx] = np.array([-1.0, 0.0, -1.0]).reshape( + [-1 if i == dim else 1 for i in range(ndim)] + ) + impr[(slice(1, 2),) * ndim] = 2.0 * ndim + return ir2tf(impr, shape, is_real=is_real), impr diff --git a/envs/kitoverlay/skimage/restoration/unwrap.py b/envs/kitoverlay/skimage/restoration/unwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..cb075d690a1178c9022700df33ac5674c04b3fee --- /dev/null +++ b/envs/kitoverlay/skimage/restoration/unwrap.py @@ -0,0 +1,116 @@ +import numpy as np + +from .._shared.utils import warn + +from ._unwrap_1d import unwrap_1d +from ._unwrap_2d import unwrap_2d +from ._unwrap_3d import unwrap_3d + + +def unwrap_phase(image, wrap_around=False, rng=None): + '''Recover the original from a wrapped phase image. + + From an image wrapped to lie in the interval [-pi, pi), recover the + original, unwrapped image. + + Parameters + ---------- + image : (M[, N[, P]]) ndarray or masked array of floats + The values should be in the range [-pi, pi). If a masked array is + provided, the masked entries will not be changed, and their values + will not be used to guide the unwrapping of neighboring, unmasked + values. Masked 1D arrays are not allowed, and will raise a + `ValueError`. + wrap_around : bool or sequence of bool, optional + When an element of the sequence is `True`, the unwrapping process + will regard the edges along the corresponding axis of the image to be + connected and use this connectivity to guide the phase unwrapping + process. If only a single boolean is given, it will apply to all axes. + Wrap around is not supported for 1D arrays. + 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. + + Unwrapping relies on a random initialization. This sets the + PRNG to use to achieve deterministic behavior. + + Returns + ------- + image_unwrapped : array_like, double + Unwrapped image of the same shape as the input. If the input `image` + was a masked array, the mask will be preserved. + + Raises + ------ + ValueError + If called with a masked 1D array or called with a 1D array and + ``wrap_around=True``. + + Examples + -------- + >>> c0, c1 = np.ogrid[-1:1:128j, -1:1:128j] + >>> image = 12 * np.pi * np.exp(-(c0**2 + c1**2)) + >>> image_wrapped = np.angle(np.exp(1j * image)) + >>> image_unwrapped = unwrap_phase(image_wrapped) + >>> np.std(image_unwrapped - image) < 1e-6 # A constant offset is normal + True + + References + ---------- + .. [1] Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, + and Munther A. Gdeisat, "Fast two-dimensional phase-unwrapping + algorithm based on sorting by reliability following a noncontinuous + path", Journal Applied Optics, Vol. 41, No. 35 (2002) 7437, + .. [2] Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., "Fast + three-dimensional phase-unwrapping algorithm based on sorting by + reliability following a non-continuous path. In W. Osten, + C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32--40, + International Society for Optics and Photonics. + ''' + if image.ndim not in (1, 2, 3): + raise ValueError('Image must be 1, 2, or 3 dimensional') + if isinstance(wrap_around, bool): + wrap_around = [wrap_around] * image.ndim + elif hasattr(wrap_around, '__getitem__') and not isinstance(wrap_around, str): + if len(wrap_around) != image.ndim: + raise ValueError( + 'Length of `wrap_around` must equal the ' 'dimensionality of image' + ) + wrap_around = [bool(wa) for wa in wrap_around] + else: + raise ValueError( + '`wrap_around` must be a bool or a sequence with ' + 'length equal to the dimensionality of image' + ) + if image.ndim == 1: + if np.ma.isMaskedArray(image): + raise ValueError('1D masked images cannot be unwrapped') + if wrap_around[0]: + raise ValueError('`wrap_around` is not supported for 1D images') + if image.ndim in (2, 3) and 1 in image.shape: + warn( + 'Image has a length 1 dimension. Consider using an ' + 'array of lower dimensionality to use a more efficient ' + 'algorithm' + ) + + if np.ma.isMaskedArray(image): + mask = np.require(np.ma.getmaskarray(image), np.uint8, ['C']) + else: + mask = np.zeros_like(image, dtype=np.uint8, order='C') + + image_not_masked = np.asarray(np.ma.getdata(image), dtype=np.float64, order='C') + image_unwrapped = np.empty_like(image, dtype=np.float64, order='C', subok=False) + + if image.ndim == 1: + unwrap_1d(image_not_masked, image_unwrapped) + elif image.ndim == 2: + unwrap_2d(image_not_masked, mask, image_unwrapped, wrap_around, rng) + elif image.ndim == 3: + unwrap_3d(image_not_masked, mask, image_unwrapped, wrap_around, rng) + + if np.ma.isMaskedArray(image): + return np.ma.array(image_unwrapped, mask=mask, fill_value=image.fill_value) + else: + return image_unwrapped diff --git a/envs/kitoverlay/skimage/segmentation/__init__.py b/envs/kitoverlay/skimage/segmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..875a3042e34af86bcae836eeba00f482ea6a74b6 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/__init__.py @@ -0,0 +1,5 @@ +"""Algorithms to partition images into meaningful regions or boundaries.""" + +import lazy_loader as lazy + +__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__) diff --git a/envs/kitoverlay/skimage/segmentation/__init__.pyi b/envs/kitoverlay/skimage/segmentation/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8199be71b15be6a51f3dacaa419f8dfb5d80c511 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/__init__.pyi @@ -0,0 +1,50 @@ +# 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__ = [ + 'expand_labels', + 'random_walker', + 'active_contour', + 'felzenszwalb', + 'slic', + 'quickshift', + 'find_boundaries', + 'mark_boundaries', + 'clear_border', + 'join_segmentations', + 'relabel_sequential', + 'watershed', + 'chan_vese', + 'morphological_geodesic_active_contour', + 'morphological_chan_vese', + 'inverse_gaussian_gradient', + 'disk_level_set', + 'checkerboard_level_set', + 'flood', + 'flood_fill', +] + +from ._expand_labels import expand_labels +from .random_walker_segmentation import random_walker +from .active_contour_model import active_contour +from ._felzenszwalb import felzenszwalb +from .slic_superpixels import slic +from ._quickshift import quickshift +from .boundaries import find_boundaries, mark_boundaries +from ._clear_border import clear_border +from ._join import join_segmentations, relabel_sequential +from ._watershed import watershed +from ._chan_vese import chan_vese +from .morphsnakes import ( + morphological_geodesic_active_contour, + morphological_chan_vese, + inverse_gaussian_gradient, + disk_level_set, + checkerboard_level_set, +) + +# We don't import flood and flood_fill from ..morphology +# because reaching into a parallel submodule is currently not supported by +# lazy_loader (see scientific-python/lazy-loader#52). +from ._watershed import flood, flood_fill diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/__init__.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dbbb6a297416eff3712cf2c4f33dde922b96ac2 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/__init__.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_chan_vese.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_chan_vese.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbfebda1634b1c67ff14ec8a494fa184d18e7f8 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_chan_vese.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_clear_border.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_clear_border.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37c222ad25029210e7d3b4f0d204be71adf68b99 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_clear_border.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_expand_labels.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_expand_labels.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..406e47b23dc9a4247663ae011c8fd95b90404a11 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_expand_labels.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_felzenszwalb.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_felzenszwalb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e278d5434959f9686e3398cb140100c59cba8264 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_felzenszwalb.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_join.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_join.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc974f8ce76b0dd76256ae53928ba76f6be3873 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_join.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_quickshift.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_quickshift.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8749384218b3b5ebd3aeb202f526d01dd95507c8 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_quickshift.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/_watershed.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/_watershed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98f7d1b6c7c7f95d3b2521376f79705f14ac9f9f Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/_watershed.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/active_contour_model.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/active_contour_model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b593bd19dd97bc2fad67794fe35df8c757630e22 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/active_contour_model.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/boundaries.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/boundaries.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a91cd4382fcb04403706937281d6e26f4c25fa Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/boundaries.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/morphsnakes.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/morphsnakes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c96f65648cf26a35c18ed8b7b4bf989573b9540 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/morphsnakes.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ef50fe60a200f14daf83783ca297849c62ca7a Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/__pycache__/slic_superpixels.cpython-311.pyc b/envs/kitoverlay/skimage/segmentation/__pycache__/slic_superpixels.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e37bc2b7bff13e09421185bee7e7989bf32f3717 Binary files /dev/null and b/envs/kitoverlay/skimage/segmentation/__pycache__/slic_superpixels.cpython-311.pyc differ diff --git a/envs/kitoverlay/skimage/segmentation/_clear_border.py b/envs/kitoverlay/skimage/segmentation/_clear_border.py new file mode 100644 index 0000000000000000000000000000000000000000..3ac598cde2e8b59f0b5576059d0232a536ac3358 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_clear_border.py @@ -0,0 +1,109 @@ +import numpy as np + +from ..measure import label + + +def clear_border(labels, buffer_size=0, bgval=0, mask=None, *, out=None): + """Clear objects connected to the label image border. + + Parameters + ---------- + labels : (M[, N[, ..., P]]) array of int or bool + Imaging data labels. + buffer_size : int, optional + The width of the border examined. By default, only objects + that touch the outside of the image are removed. + bgval : float or int, optional + Cleared objects are set to this value. + mask : ndarray of bool, same shape as `image`, optional. + Image data mask. Objects in labels image overlapping with + False pixels of mask will be removed. If defined, the + argument buffer_size will be ignored. + out : ndarray + Array of the same shape as `labels`, into which the + output is placed. By default, a new array is created. + + Returns + ------- + out : (M[, N[, ..., P]]) array + Imaging data labels with cleared borders + + Examples + -------- + >>> import numpy as np + >>> from skimage.segmentation import clear_border + >>> labels = np.array([[0, 0, 0, 0, 0, 0, 0, 1, 0], + ... [1, 1, 0, 0, 1, 0, 0, 1, 0], + ... [1, 1, 0, 1, 0, 1, 0, 0, 0], + ... [0, 0, 0, 1, 1, 1, 1, 0, 0], + ... [0, 1, 1, 1, 1, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> clear_border(labels) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> mask = np.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]]).astype(bool) + >>> clear_border(labels, mask=mask) + array([[0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + + """ + if any(buffer_size >= s for s in labels.shape) and mask is None: + # ignore buffer_size if mask + raise ValueError("buffer size may not be greater than labels size") + + if out is None: + out = labels.copy() + + if mask is not None: + err_msg = ( + f'labels and mask should have the same shape but ' + f'are {out.shape} and {mask.shape}' + ) + if out.shape != mask.shape: + raise (ValueError, err_msg) + if mask.dtype != bool: + raise TypeError("mask should be of type bool.") + borders = ~mask + else: + # create borders with buffer_size + borders = np.zeros_like(out, dtype=bool) + ext = buffer_size + 1 + slstart = slice(ext) + slend = slice(-ext, None) + slices = [slice(None) for _ in out.shape] + for d in range(out.ndim): + slices[d] = slstart + borders[tuple(slices)] = True + slices[d] = slend + borders[tuple(slices)] = True + slices[d] = slice(None) + + # Re-label, in case we are dealing with a binary out + # and to get consistent labeling + labels, number = label(out, background=0, return_num=True) + + # determine all objects that are connected to borders + borders_indices = np.unique(labels[borders]) + indices = np.arange(number + 1) + # mask all label indices that are connected to borders + label_mask = np.isin(indices, borders_indices) + # create mask for pixels to clear + mask = label_mask[labels.reshape(-1)].reshape(labels.shape) + + # clear border pixels + out[mask] = bgval + + return out diff --git a/envs/kitoverlay/skimage/segmentation/_expand_labels.py b/envs/kitoverlay/skimage/segmentation/_expand_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..47aaf1fc5e695728215e5151893c718d0f0471d1 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/_expand_labels.py @@ -0,0 +1,104 @@ +import numpy as np +from scipy.ndimage import distance_transform_edt + + +def expand_labels(label_image, distance=1, spacing=1): + """Expand labels in label image by ``distance`` pixels without overlapping. + + Given a label image, ``expand_labels`` grows label regions (connected components) + outwards by up to ``distance`` units without overflowing into neighboring regions. + More specifically, each background pixel that is within Euclidean distance + of <= ``distance`` pixels of a connected component is assigned the label of that + connected component. The `spacing` parameter can be used to specify the spacing + rate of the distance transform used to calculate the Euclidean distance for anisotropic + images. + Where multiple connected components are within ``distance`` pixels of a background + pixel, the label value of the closest connected component will be assigned (see + Notes for the case of multiple labels at equal distance). + + Parameters + ---------- + label_image : ndarray of dtype int + label image + distance : float + Euclidean distance in pixels by which to grow the labels. Default is one. + spacing : float, or sequence of float, optional + Spacing of elements along each dimension. If a sequence, must be of length + equal to the input rank; if a single number, this is used for all axes. If + not specified, a grid spacing of unity is implied. + + Returns + ------- + enlarged_labels : ndarray of dtype int + Labeled array, where all connected regions have been enlarged + + Notes + ----- + Where labels are spaced more than ``distance`` pixels are apart, this is + equivalent to a morphological dilation with a disc or hyperball of radius ``distance``. + However, in contrast to a morphological dilation, ``expand_labels`` will + not expand a label region into a neighboring region. + + This implementation of ``expand_labels`` is derived from CellProfiler [1]_, where + it is known as module "IdentifySecondaryObjects (Distance-N)" [2]_. + + There is an important edge case when a pixel has the same distance to + multiple regions, as it is not defined which region expands into that + space. Here, the exact behavior depends on the upstream implementation + of ``scipy.ndimage.distance_transform_edt``. + + See Also + -------- + :func:`skimage.measure.label`, :func:`skimage.segmentation.watershed`, :func:`skimage.morphology.dilation` + + References + ---------- + .. [1] https://cellprofiler.org + .. [2] https://github.com/CellProfiler/CellProfiler/blob/082930ea95add7b72243a4fa3d39ae5145995e9c/cellprofiler/modules/identifysecondaryobjects.py#L559 + + Examples + -------- + >>> labels = np.array([0, 1, 0, 0, 0, 0, 2]) + >>> expand_labels(labels, distance=1) + array([1, 1, 1, 0, 0, 2, 2]) + + Labels will not overwrite each other: + + >>> expand_labels(labels, distance=3) + array([1, 1, 1, 1, 2, 2, 2]) + + In case of ties, behavior is undefined, but currently resolves to the + label closest to ``(0,) * ndim`` in lexicographical order. + + >>> labels_tied = np.array([0, 1, 0, 2, 0]) + >>> expand_labels(labels_tied, 1) + array([1, 1, 1, 2, 2]) + >>> labels2d = np.array( + ... [[0, 1, 0, 0], + ... [2, 0, 0, 0], + ... [0, 3, 0, 0]] + ... ) + >>> expand_labels(labels2d, 1) + array([[2, 1, 1, 0], + [2, 2, 0, 0], + [2, 3, 3, 0]]) + >>> expand_labels(labels2d, 1, spacing=[1, 0.5]) + array([[1, 1, 1, 1], + [2, 2, 2, 0], + [3, 3, 3, 3]]) + """ + + distances, nearest_label_coords = distance_transform_edt( + label_image == 0, sampling=spacing, return_indices=True + ) + labels_out = np.zeros_like(label_image) + dilate_mask = distances <= distance + # build the coordinates to find nearest labels, + # in contrast to [1] this implementation supports label arrays + # of any dimension + masked_nearest_label_coords = [ + dimension_indices[dilate_mask] for dimension_indices in nearest_label_coords + ] + nearest_labels = label_image[tuple(masked_nearest_label_coords)] + labels_out[dilate_mask] = nearest_labels + return labels_out diff --git a/envs/kitoverlay/skimage/segmentation/active_contour_model.py b/envs/kitoverlay/skimage/segmentation/active_contour_model.py new file mode 100644 index 0000000000000000000000000000000000000000..52169619faa4fd1f75bd977141e5f3b5323d3ed0 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/active_contour_model.py @@ -0,0 +1,250 @@ +import numpy as np +from scipy.interpolate import RectBivariateSpline + +from .._shared.utils import _supported_float_type +from ..util import img_as_float +from ..filters import sobel + + +def active_contour( + image, + snake, + alpha=0.01, + beta=0.1, + w_line=0.0, + w_edge=1, + gamma=0.01, + max_px_move=1.0, + max_num_iter=2500, + convergence=0.1, + *, + boundary_condition='periodic', +): + """Active contour model. + + Active contours by fitting snakes to features of images. Supports single + and multichannel 2D images. Snakes can be periodic (for segmentation) or + have fixed and/or free ends. + The output snake has the same length as the input boundary. + As the number of points is constant, make sure that the initial snake + has enough points to capture the details of the final contour. + + Parameters + ---------- + image : (M, N) or (M, N, 3) ndarray + Input image. + snake : (K, 2) ndarray + Initial snake coordinates. For periodic boundary conditions, endpoints + must not be duplicated. + alpha : float, optional + Snake length shape parameter. Higher values makes snake contract + faster. + beta : float, optional + Snake smoothness shape parameter. Higher values makes snake smoother. + w_line : float, optional + Controls attraction to brightness. Use negative values to attract + toward dark regions. + w_edge : float, optional + Controls attraction to edges. Use negative values to repel snake from + edges. + gamma : float, optional + Explicit time stepping parameter. + max_px_move : float, optional + Maximum pixel distance to move per iteration. + max_num_iter : int, optional + Maximum iterations to optimize snake shape. + convergence : float, optional + Convergence criteria. + boundary_condition : str, optional + Boundary conditions for the contour. Can be one of 'periodic', + 'free', 'fixed', 'free-fixed', or 'fixed-free'. 'periodic' attaches + the two ends of the snake, 'fixed' holds the end-points in place, + and 'free' allows free movement of the ends. 'fixed' and 'free' can + be combined by parsing 'fixed-free', 'free-fixed'. Parsing + 'fixed-fixed' or 'free-free' yields same behaviour as 'fixed' and + 'free', respectively. + + Returns + ------- + snake : (K, 2) ndarray + Optimised snake, same shape as input parameter. + + References + ---------- + .. [1] Kass, M.; Witkin, A.; Terzopoulos, D. "Snakes: Active contour + models". International Journal of Computer Vision 1 (4): 321 + (1988). :DOI:`10.1007/BF00133570` + + Examples + -------- + >>> from skimage.draw import circle_perimeter + >>> from skimage.filters import gaussian + + Create and smooth image: + + >>> img = np.zeros((100, 100)) + >>> rr, cc = circle_perimeter(35, 45, 25) + >>> img[rr, cc] = 1 + >>> img = gaussian(img, sigma=2, preserve_range=False) + + Initialize spline: + + >>> s = np.linspace(0, 2*np.pi, 100) + >>> init = 50 * np.array([np.sin(s), np.cos(s)]).T + 50 + + Fit spline to image: + + >>> snake = active_contour(img, init, w_edge=0, w_line=1) # doctest: +SKIP + >>> dist = np.sqrt((45-snake[:, 0])**2 + (35-snake[:, 1])**2) # doctest: +SKIP + >>> int(np.mean(dist)) # doctest: +SKIP + 25 + + """ + max_num_iter = int(max_num_iter) + if max_num_iter <= 0: + raise ValueError("max_num_iter should be >0.") + convergence_order = 10 + valid_bcs = [ + 'periodic', + 'free', + 'fixed', + 'free-fixed', + 'fixed-free', + 'fixed-fixed', + 'free-free', + ] + if boundary_condition not in valid_bcs: + raise ValueError( + "Invalid boundary condition.\n" + + "Should be one of: " + + ", ".join(valid_bcs) + + '.' + ) + + img = img_as_float(image) + float_dtype = _supported_float_type(image.dtype) + img = img.astype(float_dtype, copy=False) + + RGB = img.ndim == 3 + + # Find edges using sobel: + if w_edge != 0: + if RGB: + edge = [sobel(img[:, :, 0]), sobel(img[:, :, 1]), sobel(img[:, :, 2])] + else: + edge = [sobel(img)] + else: + edge = [0] + + # Superimpose intensity and edge images: + if RGB: + img = w_line * np.sum(img, axis=2) + w_edge * sum(edge) + else: + img = w_line * img + w_edge * edge[0] + + # Interpolate for smoothness: + intp = RectBivariateSpline( + np.arange(img.shape[1]), np.arange(img.shape[0]), img.T, kx=2, ky=2, s=0 + ) + + snake_xy = snake[:, ::-1] + x = snake_xy[:, 0].astype(float_dtype) + y = snake_xy[:, 1].astype(float_dtype) + n = len(x) + xsave = np.empty((convergence_order, n), dtype=float_dtype) + ysave = np.empty((convergence_order, n), dtype=float_dtype) + + # Build snake shape matrix for Euler equation in double precision + eye_n = np.eye(n, dtype=float) + a = ( + np.roll(eye_n, -1, axis=0) + np.roll(eye_n, -1, axis=1) - 2 * eye_n + ) # second order derivative, central difference + b = ( + np.roll(eye_n, -2, axis=0) + + np.roll(eye_n, -2, axis=1) + - 4 * np.roll(eye_n, -1, axis=0) + - 4 * np.roll(eye_n, -1, axis=1) + + 6 * eye_n + ) # fourth order derivative, central difference + A = -alpha * a + beta * b + + # Impose boundary conditions different from periodic: + sfixed = False + if boundary_condition.startswith('fixed'): + A[0, :] = 0 + A[1, :] = 0 + A[1, :3] = [1, -2, 1] + sfixed = True + efixed = False + if boundary_condition.endswith('fixed'): + A[-1, :] = 0 + A[-2, :] = 0 + A[-2, -3:] = [1, -2, 1] + efixed = True + sfree = False + if boundary_condition.startswith('free'): + A[0, :] = 0 + A[0, :3] = [1, -2, 1] + A[1, :] = 0 + A[1, :4] = [-1, 3, -3, 1] + sfree = True + efree = False + if boundary_condition.endswith('free'): + A[-1, :] = 0 + A[-1, -3:] = [1, -2, 1] + A[-2, :] = 0 + A[-2, -4:] = [-1, 3, -3, 1] + efree = True + + # Only one inversion is needed for implicit spline energy minimization: + inv = np.linalg.inv(A + gamma * eye_n) + # can use float_dtype once we have computed the inverse in double precision + inv = inv.astype(float_dtype, copy=False) + + # Explicit time stepping for image energy minimization: + for i in range(max_num_iter): + # RectBivariateSpline always returns float64, so call astype here + fx = intp(x, y, dx=1, grid=False).astype(float_dtype, copy=False) + fy = intp(x, y, dy=1, grid=False).astype(float_dtype, copy=False) + + if sfixed: + fx[0] = 0 + fy[0] = 0 + if efixed: + fx[-1] = 0 + fy[-1] = 0 + if sfree: + fx[0] *= 2 + fy[0] *= 2 + if efree: + fx[-1] *= 2 + fy[-1] *= 2 + xn = inv @ (gamma * x + fx) + yn = inv @ (gamma * y + fy) + + # Movements are capped to max_px_move per iteration: + dx = max_px_move * np.tanh(xn - x) + dy = max_px_move * np.tanh(yn - y) + if sfixed: + dx[0] = 0 + dy[0] = 0 + if efixed: + dx[-1] = 0 + dy[-1] = 0 + x += dx + y += dy + + # Convergence criteria needs to compare to a number of previous + # configurations since oscillations can occur. + j = i % (convergence_order + 1) + if j < convergence_order: + xsave[j, :] = x + ysave[j, :] = y + else: + dist = np.min( + np.max(np.abs(xsave - x[None, :]) + np.abs(ysave - y[None, :]), 1) + ) + if dist < convergence: + break + + return np.stack([y, x], axis=1) diff --git a/envs/kitoverlay/skimage/segmentation/boundaries.py b/envs/kitoverlay/skimage/segmentation/boundaries.py new file mode 100644 index 0000000000000000000000000000000000000000..59de91aecad875af3d62d5f95c10889b21aec127 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/boundaries.py @@ -0,0 +1,240 @@ +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import _supported_float_type +from ..morphology import dilation, erosion, footprint_rectangle +from ..util import img_as_float, view_as_windows +from ..color import gray2rgb + + +def _find_boundaries_subpixel(label_img): + """See ``find_boundaries(..., mode='subpixel')``. + + Notes + ----- + This function puts in an empty row and column between each *actual* + row and column of the image, for a corresponding shape of ``2s - 1`` + for every image dimension of size ``s``. These "interstitial" rows + and columns are filled as ``True`` if they separate two labels in + `label_img`, ``False`` otherwise. + + I used ``view_as_windows`` to get the neighborhood of each pixel. + Then I check whether there are two labels or more in that + neighborhood. + """ + ndim = label_img.ndim + max_label = np.iinfo(label_img.dtype).max + + label_img_expanded = np.zeros( + [(2 * s - 1) for s in label_img.shape], label_img.dtype + ) + pixels = (slice(None, None, 2),) * ndim + label_img_expanded[pixels] = label_img + + edges = np.ones(label_img_expanded.shape, dtype=bool) + edges[pixels] = False + label_img_expanded[edges] = max_label + windows = view_as_windows(np.pad(label_img_expanded, 1, mode='edge'), (3,) * ndim) + + boundaries = np.zeros_like(edges) + for index in np.ndindex(label_img_expanded.shape): + if edges[index]: + values = np.unique(windows[index].ravel()) + if len(values) > 2: # single value and max_label + boundaries[index] = True + return boundaries + + +def find_boundaries(label_img, connectivity=1, mode='thick', background=0): + """Return bool array where boundaries between labeled regions are True. + + Parameters + ---------- + label_img : array of int or bool + An array in which different regions are labeled with either different + integers or boolean values. + connectivity : int in {1, ..., `label_img.ndim`}, optional + A pixel is considered a boundary pixel if any of its neighbors + has a different label. `connectivity` controls which pixels are + considered neighbors. A connectivity of 1 (default) means + pixels sharing an edge (in 2D) or a face (in 3D) will be + considered neighbors. A connectivity of `label_img.ndim` means + pixels sharing a corner will be considered neighbors. + mode : string in {'thick', 'inner', 'outer', 'subpixel'} + How to mark the boundaries: + + - thick: any pixel not completely surrounded by pixels of the + same label (defined by `connectivity`) is marked as a boundary. + This results in boundaries that are 2 pixels thick. + - inner: outline the pixels *just inside* of objects, leaving + background pixels untouched. + - outer: outline pixels in the background around object + boundaries. When two objects touch, their boundary is also + marked. + - subpixel: return a doubled image, with pixels *between* the + original pixels marked as boundary where appropriate. + background : int, optional + For modes 'inner' and 'outer', a definition of a background + label is required. See `mode` for descriptions of these two. + + Returns + ------- + boundaries : array of bool, same shape as `label_img` + A bool image where ``True`` represents a boundary pixel. For + `mode` equal to 'subpixel', ``boundaries.shape[i]`` is equal + to ``2 * label_img.shape[i] - 1`` for all ``i`` (a pixel is + inserted in between all other pairs of pixels). + + Examples + -------- + >>> labels = np.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, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], + ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) + >>> find_boundaries(labels, mode='thick').astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> find_boundaries(labels, mode='inner').astype(np.uint8) + 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, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 1, 0, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 1, 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, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> find_boundaries(labels, mode='outer').astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> labels_small = labels[::2, ::3] + >>> labels_small + array([[0, 0, 0, 0], + [0, 0, 5, 0], + [0, 1, 5, 0], + [0, 0, 5, 0], + [0, 0, 0, 0]], dtype=uint8) + >>> find_boundaries(labels_small, mode='subpixel').astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 0, 1, 0], + [0, 0, 0, 1, 0, 1, 0], + [0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> bool_image = np.array([[False, False, False, False, False], + ... [False, False, False, False, False], + ... [False, False, True, True, True], + ... [False, False, True, True, True], + ... [False, False, True, True, True]], + ... dtype=bool) + >>> find_boundaries(bool_image) + array([[False, False, False, False, False], + [False, False, True, True, True], + [False, True, True, True, True], + [False, True, True, False, False], + [False, True, True, False, False]]) + """ + if label_img.dtype == 'bool': + label_img = label_img.astype(np.uint8) + ndim = label_img.ndim + footprint = ndi.generate_binary_structure(ndim, connectivity) + if mode != 'subpixel': + boundaries = dilation(label_img, footprint) != erosion(label_img, footprint) + if mode == 'inner': + foreground_image = label_img != background + boundaries &= foreground_image + elif mode == 'outer': + max_label = np.iinfo(label_img.dtype).max + background_image = label_img == background + footprint = ndi.generate_binary_structure(ndim, ndim) + inverted_background = np.array(label_img, copy=True) + inverted_background[background_image] = max_label + adjacent_objects = ( + dilation(label_img, footprint) + != erosion(inverted_background, footprint) + ) & ~background_image + boundaries &= background_image | adjacent_objects + return boundaries + else: + boundaries = _find_boundaries_subpixel(label_img) + return boundaries + + +def mark_boundaries( + image, + label_img, + color=(1, 1, 0), + outline_color=None, + mode='outer', + background_label=0, +): + """Return image with boundaries between labeled regions highlighted. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + label_img : (M, N) array of int + Label array where regions are marked by different integer values. + color : length-3 sequence, optional + RGB color of boundaries in the output image. + outline_color : length-3 sequence, optional + RGB color surrounding boundaries in the output image. If None, no + outline is drawn. + mode : string in {'thick', 'inner', 'outer', 'subpixel'}, optional + The mode for finding boundaries. + background_label : int, optional + Which label to consider background (this is only useful for + modes ``inner`` and ``outer``). + + Returns + ------- + marked : (M, N, 3) array of float + An image in which the boundaries between labels are + superimposed on the original image. + + See Also + -------- + find_boundaries + """ + float_dtype = _supported_float_type(image.dtype) + marked = img_as_float(image, force_copy=True) + marked = marked.astype(float_dtype, copy=False) + if marked.ndim == 2: + marked = gray2rgb(marked) + if mode == 'subpixel': + # Here, we want to interpose an extra line of pixels between + # each original line - except for the last axis which holds + # the RGB information. ``ndi.zoom`` then performs the (cubic) + # interpolation, filling in the values of the interposed pixels + marked = ndi.zoom( + marked, [2 - 1 / s for s in marked.shape[:-1]] + [1], mode='mirror' + ) + boundaries = find_boundaries(label_img, mode=mode, background=background_label) + if outline_color is not None: + outlines = dilation(boundaries, footprint_rectangle((3, 3))) + marked[outlines] = outline_color + marked[boundaries] = color + return marked diff --git a/envs/kitoverlay/skimage/segmentation/morphsnakes.py b/envs/kitoverlay/skimage/segmentation/morphsnakes.py new file mode 100644 index 0000000000000000000000000000000000000000..c65349020b664be1a5e920eeef4623ff20db9894 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/morphsnakes.py @@ -0,0 +1,449 @@ +from itertools import cycle + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD + +__all__ = [ + 'morphological_chan_vese', + 'morphological_geodesic_active_contour', + 'inverse_gaussian_gradient', + 'disk_level_set', + 'checkerboard_level_set', +] + + +class _fcycle: + def __init__(self, iterable): + """Call functions from the iterable each time it is called.""" + self.funcs = cycle(iterable) + + def __call__(self, *args, **kwargs): + f = next(self.funcs) + return f(*args, **kwargs) + + +# SI and IS operators for 2D and 3D. +_P2 = [ + np.eye(3), + np.array([[0, 1, 0]] * 3), + np.flipud(np.eye(3)), + np.rot90([[0, 1, 0]] * 3), +] +_P3 = [np.zeros((3, 3, 3)) for i in range(9)] + +_P3[0][:, :, 1] = 1 +_P3[1][:, 1, :] = 1 +_P3[2][1, :, :] = 1 +_P3[3][:, [0, 1, 2], [0, 1, 2]] = 1 +_P3[4][:, [0, 1, 2], [2, 1, 0]] = 1 +_P3[5][[0, 1, 2], :, [0, 1, 2]] = 1 +_P3[6][[0, 1, 2], :, [2, 1, 0]] = 1 +_P3[7][[0, 1, 2], [0, 1, 2], :] = 1 +_P3[8][[0, 1, 2], [2, 1, 0], :] = 1 + + +def sup_inf(u): + """SI operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + erosions = [] + for P_i in P: + erosions.append(ndi.binary_erosion(u, P_i).astype(np.int8)) + + return np.stack(erosions, axis=0).max(0) + + +def inf_sup(u): + """IS operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + dilations = [] + for P_i in P: + dilations.append(ndi.binary_dilation(u, P_i).astype(np.int8)) + + return np.stack(dilations, axis=0).min(0) + + +_curvop = _fcycle( + [lambda u: sup_inf(inf_sup(u)), lambda u: inf_sup(sup_inf(u))] # SIoIS +) # ISoSI + + +def _check_input(image, init_level_set): + """Check that shapes of `image` and `init_level_set` match.""" + check_nD(image, [2, 3]) + + if len(image.shape) != len(init_level_set.shape): + raise ValueError( + "The dimensions of the initial level set do not " + "match the dimensions of the image." + ) + + +def _init_level_set(init_level_set, image_shape): + """Auxiliary function for initializing level sets with a string. + + If `init_level_set` is not a string, it is returned as is. + """ + if isinstance(init_level_set, str): + if init_level_set == 'checkerboard': + res = checkerboard_level_set(image_shape) + elif init_level_set == 'disk': + res = disk_level_set(image_shape) + else: + raise ValueError("`init_level_set` not in " "['checkerboard', 'disk']") + else: + res = init_level_set + return res + + +def disk_level_set(image_shape, *, center=None, radius=None): + """Create a disk level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image + center : tuple of positive integers, optional + Coordinates of the center of the disk given in (row, column). If not + given, it defaults to the center of the image. + radius : float, optional + Radius of the disk. If not given, it is set to the 75% of the + smallest image dimension. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the disk with the given `radius` and `center`. + + See Also + -------- + checkerboard_level_set + """ + + if center is None: + center = tuple(i // 2 for i in image_shape) + + if radius is None: + radius = min(image_shape) * 3.0 / 8.0 + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = (grid.T - center).T + phi = radius - np.sqrt(np.sum((grid) ** 2, 0)) + res = np.int8(phi > 0) + return res + + +def checkerboard_level_set(image_shape, square_size=5): + """Create a checkerboard level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image. + square_size : int, optional + Size of the squares of the checkerboard. It defaults to 5. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the checkerboard. + + See Also + -------- + disk_level_set + """ + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = grid // square_size + + # Alternate 0/1 for even/odd numbers. + grid = grid & 1 + + checkerboard = np.bitwise_xor.reduce(grid, axis=0) + res = np.int8(checkerboard) + return res + + +def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0): + """Inverse of gradient magnitude. + + Compute the magnitude of the gradients in the image and then inverts the + result in the range [0, 1]. Flat areas are assigned values close to 1, + while areas close to borders are assigned values close to 0. + + This function or a similar one defined by the user should be applied over + the image as a preprocessing step before calling + `morphological_geodesic_active_contour`. + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume. + alpha : float, optional + Controls the steepness of the inversion. A larger value will make the + transition between the flat areas and border areas steeper in the + resulting array. + sigma : float, optional + Standard deviation of the Gaussian filter applied over the image. + + Returns + ------- + gimage : (M, N) or (L, M, N) array + Preprocessed image (or volume) suitable for + `morphological_geodesic_active_contour`. + """ + gradnorm = ndi.gaussian_gradient_magnitude(image, sigma, mode='nearest') + return 1.0 / np.sqrt(1.0 + alpha * gradnorm) + + +def morphological_chan_vese( + image, + num_iter, + init_level_set='checkerboard', + smoothing=1, + lambda1=1, + lambda2=1, + iter_callback=lambda x: None, +): + """Morphological Active Contours without Edges (MorphACWE) + + Active contours without edges implemented with morphological operators. It + can be used to segment objects in images and volumes without well defined + borders. It is required that the inside of the object looks different on + average than the outside (i.e., the inner area of the object should be + darker or lighter than the outer area on average). + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume to be segmented. + num_iter : uint + Number of num_iter to run + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + lambda1 : float, optional + Weight parameter for the outer region. If `lambda1` is larger than + `lambda2`, the outer region will contain a larger range of values than + the inner region. + lambda2 : float, optional + Weight parameter for the inner region. If `lambda2` is larger than + `lambda1`, the inner region will contain a larger range of values than + the outer region. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Chan-Vese algorithm that uses morphological + operators instead of solving a partial differential equation (PDE) for the + evolution of the contour. The set of morphological operators used in this + algorithm are proved to be infinitesimally equivalent to the Chan-Vese PDE + (see [1]_). However, morphological operators are do not suffer from the + numerical stability issues typically found in PDEs (it is not necessary to + find the right time step for the evolution), and are computationally + faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # inside = u > 0 + # outside = u <= 0 + c0 = (image * (1 - u)).sum() / float((1 - u).sum() + 1e-8) + c1 = (image * u).sum() / float(u.sum() + 1e-8) + + # Image attachment + du = np.gradient(u) + abs_du = np.abs(du).sum(0) + aux = abs_du * (lambda1 * (image - c1) ** 2 - lambda2 * (image - c0) ** 2) + + u[aux < 0] = 1 + u[aux > 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u + + +def morphological_geodesic_active_contour( + gimage, + num_iter, + init_level_set='disk', + smoothing=1, + threshold='auto', + balloon=0, + iter_callback=lambda x: None, +): + """Morphological Geodesic Active Contours (MorphGAC). + + Geodesic active contours implemented with morphological operators. It can + be used to segment objects with visible but noisy, cluttered, broken + borders. + + Parameters + ---------- + gimage : (M, N) or (L, M, N) array + Preprocessed image or volume to be segmented. This is very rarely the + original image. Instead, this is usually a preprocessed version of the + original image that enhances and highlights the borders (or other + structures) of the object to segment. + :func:`morphological_geodesic_active_contour` will try to stop the contour + evolution in areas where `gimage` is small. See + :func:`inverse_gaussian_gradient` as an example function to + perform this preprocessing. Note that the quality of + :func:`morphological_geodesic_active_contour` might greatly depend on this + preprocessing. + num_iter : uint + Number of num_iter to run. + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + threshold : float, optional + Areas of the image with a value smaller than this threshold will be + considered borders. The evolution of the contour will stop in these + areas. + balloon : float, optional + Balloon force to guide the contour in non-informative areas of the + image, i.e., areas where the gradient of the image is too small to push + the contour towards a border. A negative value will shrink the contour, + while a positive value will expand the contour in these areas. Setting + this to zero will disable the balloon force. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + inverse_gaussian_gradient, disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Geodesic Active Contours (GAC) algorithm that uses + morphological operators instead of solving partial differential equations + (PDEs) for the evolution of the contour. The set of morphological operators + used in this algorithm are proved to be infinitesimally equivalent to the + GAC PDEs (see [1]_). However, morphological operators are do not suffer + from the numerical stability issues typically found in PDEs (e.g., it is + not necessary to find the right time step for the evolution), and are + computationally faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + image = gimage + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + if threshold == 'auto': + threshold = np.percentile(image, 40) + + structure = np.ones((3,) * len(image.shape), dtype=np.int8) + dimage = np.gradient(image) + # threshold_mask = image > threshold + if balloon != 0: + threshold_mask_balloon = image > threshold / np.abs(balloon) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # Balloon + if balloon > 0: + aux = ndi.binary_dilation(u, structure) + elif balloon < 0: + aux = ndi.binary_erosion(u, structure) + if balloon != 0: + u[threshold_mask_balloon] = aux[threshold_mask_balloon] + + # Image attachment + aux = np.zeros_like(image) + du = np.gradient(u) + for el1, el2 in zip(dimage, du): + aux += el1 * el2 + u[aux > 0] = 1 + u[aux < 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u diff --git a/envs/kitoverlay/skimage/segmentation/slic_superpixels.py b/envs/kitoverlay/skimage/segmentation/slic_superpixels.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa6ef1bf90c62200309e4be514e3e0aa2129c46 --- /dev/null +++ b/envs/kitoverlay/skimage/segmentation/slic_superpixels.py @@ -0,0 +1,449 @@ +import math +from collections.abc import Iterable +from warnings import warn + +import numpy as np +from numpy import random +from scipy.cluster.vq import kmeans2 +from scipy.spatial.distance import pdist, squareform + +from .._shared import utils +from .._shared.filters import gaussian +from ..color import rgb2lab +from ..util import img_as_float, regular_grid +from ._slic import _enforce_label_connectivity_cython, _slic_cython + + +def _get_mask_centroids(mask, n_centroids, multichannel): + """Find regularly spaced centroids on a mask. + + Parameters + ---------- + mask : 3D ndarray + The mask within which the centroids must be positioned. + n_centroids : int + The number of centroids to be returned. + + Returns + ------- + centroids : 2D ndarray + The coordinates of the centroids with shape (n_centroids, 3). + steps : 1D ndarray + The approximate distance between two seeds in all dimensions. + + """ + + # Get tight ROI around the mask to optimize + coord = np.array(np.nonzero(mask), dtype=float).T + # Fix random seed to ensure repeatability + # Keep old-style RandomState here as expected results in tests depend on it + rng = random.RandomState(123) + + # select n_centroids randomly distributed points from within the mask + idx_full = np.arange(len(coord), dtype=int) + idx = np.sort(rng.choice(idx_full, min(n_centroids, len(coord)), replace=False)) + + # To save time, when n_centroids << len(coords), use only a subset of the + # coordinates when calling k-means. Rather than the full set of coords, + # we will use a substantially larger subset than n_centroids. Here we + # somewhat arbitrarily choose dense_factor=10 to make the samples + # 10 times closer together along each axis than the n_centroids samples. + dense_factor = 10 + ndim_spatial = mask.ndim - 1 if multichannel else mask.ndim + n_dense = int((dense_factor**ndim_spatial) * n_centroids) + if len(coord) > n_dense: + # subset of points to use for the k-means calculation + # (much denser than idx, but less than the full set) + idx_dense = np.sort(rng.choice(idx_full, n_dense, replace=False)) + else: + idx_dense = Ellipsis + centroids, _ = kmeans2(coord[idx_dense], coord[idx], iter=5) + + # Compute the minimum distance of each centroid to the others + dist = squareform(pdist(centroids)) + np.fill_diagonal(dist, np.inf) + closest_pts = dist.argmin(-1) + steps = abs(centroids - centroids[closest_pts, :]).mean(0) + + return centroids, steps + + +def _get_grid_centroids(image, n_centroids): + """Find regularly spaced centroids on the image. + + Parameters + ---------- + image : 2D, 3D or 4D ndarray + Input image, which can be 2D or 3D, and grayscale or + multichannel. + n_centroids : int + The (approximate) number of centroids to be returned. + + Returns + ------- + centroids : 2D ndarray + The coordinates of the centroids with shape (~n_centroids, 3). + steps : 1D ndarray + The approximate distance between two seeds in all dimensions. + + """ + d, h, w = image.shape[:3] + + grid_z, grid_y, grid_x = np.mgrid[:d, :h, :w] + slices = regular_grid(image.shape[:3], n_centroids) + + centroids_z = grid_z[slices].ravel()[..., np.newaxis] + centroids_y = grid_y[slices].ravel()[..., np.newaxis] + centroids_x = grid_x[slices].ravel()[..., np.newaxis] + + centroids = np.concatenate([centroids_z, centroids_y, centroids_x], axis=-1) + + steps = np.asarray([float(s.step) if s.step is not None else 1.0 for s in slices]) + return centroids, steps + + +@utils.channel_as_last_axis(multichannel_output=False) +def slic( + image, + n_segments=100, + compactness=10.0, + max_num_iter=10, + sigma=0, + spacing=None, + convert2lab=None, + enforce_connectivity=True, + min_size_factor=0.5, + max_size_factor=3, + slic_zero=False, + start_label=1, + mask=None, + *, + channel_axis=-1, +): + """Segments image using k-means clustering in Color-(x,y,z) space. + + Parameters + ---------- + image : (M, N[, P][, C]) ndarray + Input image. Can be 2D or 3D, and grayscale or multichannel + (see `channel_axis` parameter). + Input image must either be NaN-free or the NaN's must be masked out. + n_segments : int, optional + The (approximate) number of labels in the segmented output image. + compactness : float, optional + Balances color proximity and space proximity. Higher values give + more weight to space proximity, making superpixel shapes more + square/cubic. In SLICO mode, this is the initial compactness. + This parameter depends strongly on image contrast and on the + shapes of objects in the image. We recommend exploring possible + values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before + refining around a chosen value. + max_num_iter : int, optional + Maximum number of iterations of k-means. + sigma : float or array-like of floats, optional + Width of Gaussian smoothing kernel for pre-processing for each + dimension of the image. The same sigma is applied to each dimension in + case of a scalar value. Zero means no smoothing. + Note that `sigma` is automatically scaled if it is scalar and + if a manual voxel spacing is provided (see Notes section). If + sigma is array-like, its size must match ``image``'s number + of spatial dimensions. + spacing : array-like of floats, optional + The voxel spacing along each spatial dimension. By default, + `slic` assumes uniform spacing (same voxel resolution along + each spatial dimension). + This parameter controls the weights of the distances along the + spatial dimensions during k-means clustering. + convert2lab : bool, optional + Whether the input should be converted to Lab colorspace prior to + segmentation. The input image *must* be RGB. Highly recommended. + This option defaults to ``True`` when ``channel_axis` is not None *and* + ``image.shape[-1] == 3``. + enforce_connectivity : bool, optional + Whether the generated segments are connected or not + min_size_factor : float, optional + Proportion of the minimum segment size to be removed with respect + to the supposed segment size ```depth*width*height/n_segments``` + max_size_factor : float, optional + Proportion of the maximum connected segment size. A value of 3 works + in most of the cases. + slic_zero : bool, optional + Run SLIC-zero, the zero-parameter mode of SLIC. [2]_ + start_label : int, optional + The labels' index start. Should be 0 or 1. + + .. versionadded:: 0.17 + ``start_label`` was introduced in 0.17 + mask : ndarray, optional + If provided, superpixels are computed only where mask is True, + and seed points are homogeneously distributed over the mask + using a k-means clustering strategy. Mask number of dimensions + must be equal to image number of spatial dimensions. + + .. versionadded:: 0.17 + ``mask`` was introduced in 0.17 + 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 + ------- + labels : 2D or 3D array + Integer mask indicating segment labels. + + Raises + ------ + ValueError + If ``convert2lab`` is set to ``True`` but the last array + dimension is not of length 3. + ValueError + If ``start_label`` is not 0 or 1. + ValueError + If ``image`` contains unmasked NaN values. + ValueError + If ``image`` contains unmasked infinite values. + ValueError + If ``image`` is 2D but ``channel_axis`` is -1 (the default). + + Notes + ----- + * If `sigma > 0`, the image is smoothed using a Gaussian kernel prior to + segmentation. + + * If `sigma` is scalar and `spacing` is provided, the kernel width is + divided along each dimension by the spacing. For example, if ``sigma=1`` + and ``spacing=[5, 1, 1]``, the effective `sigma` is ``[0.2, 1, 1]``. This + ensures sensible smoothing for anisotropic images. + + * The image is rescaled to be in [0, 1] prior to processing (masked + values are ignored). + + * Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To + interpret them as 3D with the last dimension having length 3, use + `channel_axis=None`. + + * `start_label` is introduced to handle the issue [4]_. Label indexing + starts at 1 by default. + + References + ---------- + .. [1] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi, + Pascal Fua, and Sabine Süsstrunk, SLIC Superpixels Compared to + State-of-the-art Superpixel Methods, TPAMI, May 2012. + :DOI:`10.1109/TPAMI.2012.120` + .. [2] https://www.epfl.ch/labs/ivrl/research/slic-superpixels/#SLICO + .. [3] Irving, Benjamin. "maskSLIC: regional superpixel generation with + application to local pathology characterisation in medical images.", + 2016, :arXiv:`1606.09518` + .. [4] https://github.com/scikit-image/scikit-image/issues/3722 + + Examples + -------- + >>> from skimage.segmentation import slic + >>> from skimage.data import astronaut + >>> img = astronaut() + >>> segments = slic(img, n_segments=100, compactness=10) + + Increasing the compactness parameter yields more square regions: + + >>> segments = slic(img, n_segments=100, compactness=20) + + """ + if image.ndim == 2 and channel_axis is not None: + raise ValueError( + f"channel_axis={channel_axis} indicates multichannel, which is not " + "supported for a two-dimensional image; use channel_axis=None if " + "the image is grayscale" + ) + + image = img_as_float(image) + float_dtype = utils._supported_float_type(image.dtype) + # copy=True so subsequent in-place operations do not modify the + # function input + image = image.astype(float_dtype, copy=True) + + if mask is not None: + # Create masked_image to rescale while ignoring masked values + mask = np.ascontiguousarray(mask, dtype=bool) + if channel_axis is not None: + mask_ = np.expand_dims(mask, axis=channel_axis) + mask_ = np.broadcast_to(mask_, image.shape) + else: + mask_ = mask + image_values = image[mask_] + else: + image_values = image + + # Rescale image to [0, 1] to make choice of compactness insensitive to + # input image scale. + imin = image_values.min() + imax = image_values.max() + if np.isnan(imin): + raise ValueError("unmasked NaN values in image are not supported") + if np.isinf(imin) or np.isinf(imax): + raise ValueError("unmasked infinite values in image are not supported") + image -= imin + if imax != imin: + image /= imax - imin + + use_mask = mask is not None + dtype = image.dtype + + is_2d = False + + multichannel = channel_axis is not None + if image.ndim == 2: + # 2D grayscale image + image = image[np.newaxis, ..., np.newaxis] + is_2d = True + elif image.ndim == 3 and multichannel: + # Make 2D multichannel image 3D with depth = 1 + image = image[np.newaxis, ...] + is_2d = True + elif image.ndim == 3 and not multichannel: + # Add channel as single last dimension + image = image[..., np.newaxis] + + if multichannel and (convert2lab or convert2lab is None): + if image.shape[channel_axis] != 3 and convert2lab: + raise ValueError("Lab colorspace conversion requires a RGB image.") + elif image.shape[channel_axis] == 3: + image = rgb2lab(image) + + if start_label not in [0, 1]: + raise ValueError("start_label should be 0 or 1.") + + # initialize cluster centroids for desired number of segments + update_centroids = False + if use_mask: + mask = mask.view('uint8') + if mask.ndim == 2: + mask = np.ascontiguousarray(mask[np.newaxis, ...]) + if mask.shape != image.shape[:3]: + raise ValueError("image and mask should have the same shape.") + centroids, steps = _get_mask_centroids(mask, n_segments, multichannel) + update_centroids = True + else: + centroids, steps = _get_grid_centroids(image, n_segments) + + if spacing is None: + spacing = np.ones(3, dtype=dtype) + elif isinstance(spacing, Iterable): + spacing = np.asarray(spacing, dtype=dtype) + if is_2d: + if spacing.size != 2: + if spacing.size == 3: + warn( + "Input image is 2D: spacing number of " + "elements must be 2. In the future, a ValueError " + "will be raised.", + FutureWarning, + stacklevel=2, + ) + else: + raise ValueError( + f"Input image is 2D, but spacing has " + f"{spacing.size} elements (expected 2)." + ) + else: + spacing = np.insert(spacing, 0, 1) + elif spacing.size != 3: + raise ValueError( + f"Input image is 3D, but spacing has " + f"{spacing.size} elements (expected 3)." + ) + spacing = np.ascontiguousarray(spacing, dtype=dtype) + else: + raise TypeError("spacing must be None or iterable.") + + if np.isscalar(sigma): + sigma = np.array([sigma, sigma, sigma], dtype=dtype) + sigma /= spacing + elif isinstance(sigma, Iterable): + sigma = np.asarray(sigma, dtype=dtype) + if is_2d: + if sigma.size != 2: + if spacing.size == 3: + warn( + "Input image is 2D: sigma number of " + "elements must be 2. In the future, a ValueError " + "will be raised.", + FutureWarning, + stacklevel=2, + ) + else: + raise ValueError( + f"Input image is 2D, but sigma has " + f"{sigma.size} elements (expected 2)." + ) + else: + sigma = np.insert(sigma, 0, 0) + elif sigma.size != 3: + raise ValueError( + f"Input image is 3D, but sigma has " + f"{sigma.size} elements (expected 3)." + ) + + if (sigma > 0).any(): + # add zero smoothing for channel dimension + sigma = list(sigma) + [0] + image = gaussian(image, sigma=sigma, mode='reflect') + + n_centroids = centroids.shape[0] + segments = np.ascontiguousarray( + np.concatenate([centroids, np.zeros((n_centroids, image.shape[3]))], axis=-1), + dtype=dtype, + ) + + # Scaling of ratio in the same way as in the SLIC paper so the + # values have the same meaning + step = max(steps) + ratio = 1.0 / compactness + + image = np.ascontiguousarray(image * ratio, dtype=dtype) + + if update_centroids: + # Step 2 of the algorithm [3]_ + _slic_cython( + image, + mask, + segments, + step, + max_num_iter, + spacing, + slic_zero, + ignore_color=True, + start_label=start_label, + ) + + labels = _slic_cython( + image, + mask, + segments, + step, + max_num_iter, + spacing, + slic_zero, + ignore_color=False, + start_label=start_label, + ) + + if enforce_connectivity: + if use_mask: + segment_size = mask.sum() / n_centroids + else: + segment_size = math.prod(image.shape[:3]) / n_centroids + min_size = int(min_size_factor * segment_size) + max_size = int(max_size_factor * segment_size) + labels = _enforce_label_connectivity_cython( + labels, min_size, max_size, start_label=start_label + ) + + if is_2d: + labels = labels[0] + + return labels diff --git a/envs/kitoverlay/skimage/transform/__pycache__/_thin_plate_splines.cpython-311.pyc b/envs/kitoverlay/skimage/transform/__pycache__/_thin_plate_splines.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..027f98561f7f7688fba2984628378a9ba0ece38b Binary files /dev/null and b/envs/kitoverlay/skimage/transform/__pycache__/_thin_plate_splines.cpython-311.pyc differ