1"""Standard test images.
2
3For more images, see
4
5 - http://sipi.usc.edu/database/database.php
6
7"""
8import numpy as np
9import shutil
10from packaging import version
11
12from ..util.dtype import img_as_bool
13from ._binary_blobs import binary_blobs
14from ._registry import registry, legacy_registry, registry_urls
15
16from .. import __version__
17
18import os.path as osp
19import os
20
21legacy_data_dir = osp.abspath(osp.dirname(__file__))
22skimage_distribution_dir = osp.join(legacy_data_dir, '..')
23
24try:
25    from pooch import file_hash
26except ModuleNotFoundError:
27    # Function taken from
28    # https://github.com/fatiando/pooch/blob/master/pooch/utils.py
29    def file_hash(fname, alg="sha256"):
30        """
31        Calculate the hash of a given file.
32        Useful for checking if a file has changed or been corrupted.
33        Parameters
34        ----------
35        fname : str
36            The name of the file.
37        alg : str
38            The type of the hashing algorithm
39        Returns
40        -------
41        hash : str
42            The hash of the file.
43        Examples
44        --------
45        >>> fname = "test-file-for-hash.txt"
46        >>> with open(fname, "w") as f:
47        ...     __ = f.write("content of the file")
48        >>> print(file_hash(fname))
49        0fc74468e6a9a829f103d069aeb2bb4f8646bad58bf146bb0e3379b759ec4a00
50        >>> import os
51        >>> os.remove(fname)
52        """
53        import hashlib
54        if alg not in hashlib.algorithms_available:
55            raise ValueError(f'Algorithm \'{alg}\' not available in hashlib')
56        # Calculate the hash in chunks to avoid overloading the memory
57        chunksize = 65536
58        hasher = hashlib.new(alg)
59        with open(fname, "rb") as fin:
60            buff = fin.read(chunksize)
61            while buff:
62                hasher.update(buff)
63                buff = fin.read(chunksize)
64        return hasher.hexdigest()
65
66
67def _has_hash(path, expected_hash):
68    """Check if the provided path has the expected hash."""
69    if not osp.exists(path):
70        return False
71    return file_hash(path) == expected_hash
72
73
74def create_image_fetcher():
75    try:
76        import pooch
77        # older versions of Pooch don't have a __version__ attribute
78        if not hasattr(pooch, '__version__'):
79            retry = {}
80        else:
81            pooch_version = pooch.__version__.lstrip('v')
82            retry = {'retry_if_failed': 3}
83            # Keep version check in synch with
84            # scikit-image/requirements/optional.txt
85            if version.parse(pooch_version) < version.parse('1.3.0'):
86                # we need a more recent version of pooch to retry
87                retry = {}
88    except ImportError:
89        # Without pooch, fallback on the standard data directory
90        # which for now, includes a few limited data samples
91        return None, legacy_data_dir
92
93    # Pooch expects a `+` to exist in development versions.
94    # Since scikit-image doesn't follow that convention, we have to manually
95    # remove `.dev` with a `+` if it exists.
96    # This helps pooch understand that it should look in master
97    # to find the required files
98    if '+git' in __version__:
99        skimage_version_for_pooch = __version__.replace('.dev0+git', '+git')
100    else:
101        skimage_version_for_pooch = __version__.replace('.dev', '+')
102
103    if '+' in skimage_version_for_pooch:
104        url = ("https://github.com/scikit-image/scikit-image/raw/"
105               "{version}/skimage/")
106    else:
107        url = ("https://github.com/scikit-image/scikit-image/raw/"
108               "v{version}/skimage/")
109
110    # Create a new friend to manage your sample data storage
111    image_fetcher = pooch.create(
112        # Pooch uses appdirs to select an appropriate directory for the cache
113        # on each platform.
114        # https://github.com/ActiveState/appdirs
115        # On linux this converges to
116        # '$HOME/.cache/scikit-image'
117        # With a version qualifier
118        path=pooch.os_cache("scikit-image"),
119        base_url=url,
120        version=skimage_version_for_pooch,
121        version_dev="v0.19.x",
122        env="SKIMAGE_DATADIR",
123        registry=registry,
124        urls=registry_urls,
125        # Note: this should read `retry_if_failed=3,`, but we generate that
126        # dynamically at import time above, in case installed pooch is a less
127        # recent version
128        **retry,
129    )
130
131    data_dir = osp.join(str(image_fetcher.abspath), 'data')
132    return image_fetcher, data_dir
133
134
135image_fetcher, data_dir = create_image_fetcher()
136
137if image_fetcher is None:
138    has_pooch = False
139else:
140    has_pooch = True
141
142
143def _fetch(data_filename):
144    """Fetch a given data file from either the local cache or the repository.
145
146    This function provides the path location of the data file given
147    its name in the scikit-image repository.
148
149    Parameters
150    ----------
151    data_filename:
152        Name of the file in the scikit-image repository. e.g.
153        'restoration/tess/camera_rl.npy'.
154
155    Returns
156    -------
157    Path of the local file as a python string.
158
159    Raises
160    ------
161    KeyError:
162        If the filename is not known to the scikit-image distribution.
163
164    ModuleNotFoundError:
165        If the filename is known to the scikit-image distribution but pooch
166        is not installed.
167
168    ConnectionError:
169        If scikit-image is unable to connect to the internet but the
170        dataset has not been downloaded yet.
171    """
172    resolved_path = osp.join(data_dir, '..', data_filename)
173    expected_hash = registry[data_filename]
174
175    # Case 1:
176    # The file may already be in the data_dir.
177    # We may have decided to ship it in the scikit-image distribution.
178    if _has_hash(resolved_path, expected_hash):
179        # Nothing to be done, file is where it is expected to be
180        return resolved_path
181
182    # Case 2:
183    # The user is using a cloned version of the github repo, which
184    # contains both the publicly shipped data, and test data.
185    # In this case, the file would be located relative to the
186    # skimage_distribution_dir
187    gh_repository_path = osp.join(skimage_distribution_dir, data_filename)
188    if _has_hash(gh_repository_path, expected_hash):
189        parent = osp.dirname(resolved_path)
190        os.makedirs(parent, exist_ok=True)
191        shutil.copy2(gh_repository_path, resolved_path)
192        return resolved_path
193
194    # Case 3:
195    # Pooch not found.
196    if image_fetcher is None:
197        raise ModuleNotFoundError(
198            "The requested file is part of the scikit-image distribution, "
199            "but requires the installation of an optional dependency, pooch. "
200            "To install pooch, use your preferred python package manager. "
201            "Follow installation instruction found at "
202            "https://scikit-image.org/docs/stable/install.html"
203        )
204
205    # Case 4:
206    # Pooch needs to download the data. Let the image fetcher to search for
207    # our data. A ConnectionError is raised if no internet connection is
208    # available.
209    try:
210        resolved_path = image_fetcher.fetch(data_filename)
211    except ConnectionError as err:
212        # If we decide in the future to suppress the underlying 'requests'
213        # error, change this to `raise ... from None`. See PEP 3134.
214        raise ConnectionError(
215            'Tried to download a scikit-image dataset, but no internet '
216            'connection is available. To avoid this message in the '
217            'future, try `skimage.data.download_all()` when you are '
218            'connected to the internet.'
219        ) from err
220    return resolved_path
221
222
223def _init_pooch():
224    os.makedirs(data_dir, exist_ok=True)
225
226    # Copy in the README.txt if it doesn't already exist.
227    # If the file was originally copied to the data cache directory read-only
228    # then we cannot overwrite it, nor do we need to copy on every init.
229    # In general, as the data cache directory contains the scikit-image version
230    # it should not be necessary to overwrite this file as it should not
231    # change.
232    dest_path = osp.join(data_dir, 'README.txt')
233    if not os.path.isfile(dest_path):
234        shutil.copy2(osp.join(skimage_distribution_dir, 'data', 'README.txt'),
235                     dest_path)
236
237    # Fetch all legacy data so that it is available by default
238    for filename in legacy_registry:
239        _fetch(filename)
240
241
242# This function creates directories, and has been the source of issues for
243# downstream users, see
244# https://github.com/scikit-image/scikit-image/issues/4660
245# https://github.com/scikit-image/scikit-image/issues/4664
246if has_pooch:
247    _init_pooch()
248
249
250def download_all(directory=None):
251    """Download all datasets for use with scikit-image offline.
252
253    Scikit-image datasets are no longer shipped with the library by default.
254    This allows us to use higher quality datasets, while keeping the
255    library download size small.
256
257    This function requires the installation of an optional dependency, pooch,
258    to download the full dataset. Follow installation instruction found at
259
260        https://scikit-image.org/docs/stable/install.html
261
262    Call this function to download all sample images making them available
263    offline on your machine.
264
265    Parameters
266    ----------
267    directory: path-like, optional
268        The directory where the dataset should be stored.
269
270    Raises
271    ------
272    ModuleNotFoundError:
273        If pooch is not install, this error will be raised.
274
275    Notes
276    -----
277    scikit-image will only search for images stored in the default directory.
278    Only specify the directory if you wish to download the images to your own
279    folder for a particular reason. You can access the location of the default
280    data directory by inspecting the variable `skimage.data.data_dir`.
281    """
282
283    if image_fetcher is None:
284        raise ModuleNotFoundError(
285            "To download all package data, scikit-image needs an optional "
286            "dependency, pooch."
287            "To install pooch, follow our installation instructions found at "
288            "https://scikit-image.org/docs/stable/install.html"
289        )
290    # Consider moving this kind of logic to Pooch
291    old_dir = image_fetcher.path
292    try:
293        if directory is not None:
294            image_fetcher.path = directory
295
296        for filename in image_fetcher.registry:
297            _fetch(filename)
298    finally:
299        image_fetcher.path = old_dir
300
301
302def lbp_frontal_face_cascade_filename():
303    """Return the path to the XML file containing the weak classifier cascade.
304
305    These classifiers were trained using LBP features. The file is part
306    of the OpenCV repository [1]_.
307
308    References
309    ----------
310    .. [1] OpenCV lbpcascade trained files
311           https://github.com/opencv/opencv/tree/master/data/lbpcascades
312    """
313
314    return _fetch('data/lbpcascade_frontalface_opencv.xml')
315
316
317def _load(f, as_gray=False):
318    """Load an image file located in the data directory.
319
320    Parameters
321    ----------
322    f : string
323        File name.
324    as_gray : bool, optional
325        Whether to convert the image to grayscale.
326
327    Returns
328    -------
329    img : ndarray
330        Image loaded from ``skimage.data_dir``.
331    """
332    # importing io is quite slow since it scans all the backends
333    # we lazy import it here
334    from ..io import imread
335    return imread(_fetch(f), as_gray=as_gray)
336
337
338def camera():
339    """Gray-level "camera" image.
340
341    Can be used for segmentation and denoising examples.
342
343    Returns
344    -------
345    camera : (512, 512) uint8 ndarray
346        Camera image.
347
348    Notes
349    -----
350    No copyright restrictions. CC0 by the photographer (Lav Varshney).
351
352    .. versionchanged:: 0.18
353        This image was replaced due to copyright restrictions. For more
354        information, please see [1]_.
355
356    References
357    ----------
358    .. [1] https://github.com/scikit-image/scikit-image/issues/3927
359    """
360    return _load("data/camera.png")
361
362
363def eagle():
364    """A golden eagle.
365
366    Suitable for examples on segmentation, Hough transforms, and corner
367    detection.
368
369    Notes
370    -----
371    No copyright restrictions. CC0 by the photographer (Dayane Machado).
372
373    Returns
374    -------
375    eagle : (2019, 1826) uint8 ndarray
376        Eagle image.
377    """
378    return _load("data/eagle.png")
379
380
381def astronaut():
382    """Color image of the astronaut Eileen Collins.
383
384    Photograph of Eileen Collins, an American astronaut. She was selected
385    as an astronaut in 1992 and first piloted the space shuttle STS-63 in
386    1995. She retired in 2006 after spending a total of 38 days, 8 hours
387    and 10 minutes in outer space.
388
389    This image was downloaded from the NASA Great Images database
390    <https://flic.kr/p/r9qvLn>`__.
391
392    No known copyright restrictions, released into the public domain.
393
394    Returns
395    -------
396    astronaut : (512, 512, 3) uint8 ndarray
397        Astronaut image.
398    """
399
400    return _load("data/astronaut.png")
401
402
403def brick():
404    """Brick wall.
405
406    Returns
407    -------
408    brick : (512, 512) uint8 image
409        A small section of a brick wall.
410
411    Notes
412    -----
413    The original image was downloaded from
414    `CC0Textures <https://cc0textures.com/view.php?tex=Bricks25>`_ and licensed
415    under the Creative Commons CC0 License.
416
417    A perspective transform was then applied to the image, prior to
418    rotating it by 90 degrees, cropping and scaling it to obtain the final
419    image.
420    """
421
422    """
423    The following code was used to obtain the final image.
424
425    >>> import sys; print(sys.version)
426    >>> import platform; print(platform.platform())
427    >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
428    >>> import numpy; print(f'numpy version: {numpy.__version__}')
429    >>> import imageio; print(f'imageio version {imageio.__version__}')
430    3.7.3 | packaged by conda-forge | (default, Jul  1 2019, 21:52:21)
431    [GCC 7.3.0]
432    Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
433    scikit-image version: 0.16.dev0
434    numpy version: 1.16.4
435    imageio version 2.4.1
436
437    >>> import requests
438    >>> import zipfile
439    >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Bricks25/%5B2K%5DBricks25.zip'
440    >>> r = requests.get(url)
441    >>> with open('[2K]Bricks25.zip', 'bw') as f:
442    ...     f.write(r.content)
443    >>> with zipfile.ZipFile('[2K]Bricks25.zip') as z:
444    ... z.extract('Bricks25_col.jpg')
445
446    >>> from numpy.linalg import inv
447    >>> from skimage.transform import rescale, warp, rotate
448    >>> from skimage.color import rgb2gray
449    >>> from imageio import imread, imwrite
450    >>> from skimage import img_as_ubyte
451    >>> import numpy as np
452
453
454    >>> # Obtained playing around with GIMP 2.10 with their perspective tool
455    >>> H = inv(np.asarray([[ 0.54764, -0.00219, 0],
456    ...                     [-0.12822,  0.54688, 0],
457    ...                     [-0.00022,        0, 1]]))
458
459
460    >>> brick_orig = imread('Bricks25_col.jpg')
461    >>> brick = warp(brick_orig, H)
462    >>> brick = rescale(brick[:1024, :1024], (0.5, 0.5, 1))
463    >>> brick = rotate(brick, -90)
464    >>> imwrite('brick.png', img_as_ubyte(rgb2gray(brick)))
465    """
466    return _load("data/brick.png", as_gray=True)
467
468
469def grass():
470    """Grass.
471
472    Returns
473    -------
474    grass : (512, 512) uint8 image
475        Some grass.
476
477    Notes
478    -----
479    The original image was downloaded from
480    `DeviantArt <https://www.deviantart.com/linolafett/art/Grass-01-434853879>`__
481    and licensed under the Creative Commons CC0 License.
482
483    The downloaded image was cropped to include a region of ``(512, 512)``
484    pixels around the top left corner, converted to grayscale, then to uint8
485    prior to saving the result in PNG format.
486
487    """
488
489    """
490    The following code was used to obtain the final image.
491
492    >>> import sys; print(sys.version)
493    >>> import platform; print(platform.platform())
494    >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
495    >>> import numpy; print(f'numpy version: {numpy.__version__}')
496    >>> import imageio; print(f'imageio version {imageio.__version__}')
497    3.7.3 | packaged by conda-forge | (default, Jul  1 2019, 21:52:21)
498    [GCC 7.3.0]
499    Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
500    scikit-image version: 0.16.dev0
501    numpy version: 1.16.4
502    imageio version 2.4.1
503
504    >>> import requests
505    >>> import zipfile
506    >>> url = 'https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a407467e-4ff0-49f1-923f-c9e388e84612/d76wfef-2878b78d-5dce-43f9-be36-26ec9bc0df3b.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E0MDc0NjdlLTRmZjAtNDlmMS05MjNmLWM5ZTM4OGU4NDYxMlwvZDc2d2ZlZi0yODc4Yjc4ZC01ZGNlLTQzZjktYmUzNi0yNmVjOWJjMGRmM2IuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.98hIcOTCqXWQ67Ec5bM5eovKEn2p91mWB3uedH61ynI'
507    >>> r = requests.get(url)
508    >>> with open('grass_orig.jpg', 'bw') as f:
509    ...     f.write(r.content)
510    >>> grass_orig = imageio.imread('grass_orig.jpg')
511    >>> grass = skimage.img_as_ubyte(skimage.color.rgb2gray(grass_orig[:512, :512]))
512    >>> imageio.imwrite('grass.png', grass)
513    """
514    return _load("data/grass.png", as_gray=True)
515
516
517def gravel():
518    """Gravel
519
520    Returns
521    -------
522    gravel : (512, 512) uint8 image
523        Grayscale gravel sample.
524
525    Notes
526    -----
527    The original image was downloaded from
528    `CC0Textures <https://cc0textures.com/view.php?tex=Gravel04>`__ and
529    licensed under the Creative Commons CC0 License.
530
531    The downloaded image was then rescaled to ``(1024, 1024)``, then the
532    top left ``(512, 512)`` pixel region  was cropped prior to converting the
533    image to grayscale and uint8 data type. The result was saved using the
534    PNG format.
535    """
536
537    """
538    The following code was used to obtain the final image.
539
540    >>> import sys; print(sys.version)
541    >>> import platform; print(platform.platform())
542    >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
543    >>> import numpy; print(f'numpy version: {numpy.__version__}')
544    >>> import imageio; print(f'imageio version {imageio.__version__}')
545    3.7.3 | packaged by conda-forge | (default, Jul  1 2019, 21:52:21)
546    [GCC 7.3.0]
547    Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
548    scikit-image version: 0.16.dev0
549    numpy version: 1.16.4
550    imageio version 2.4.1
551
552    >>> import requests
553    >>> import zipfile
554
555    >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Gravel04/%5B2K%5DGravel04.zip'
556    >>> r = requests.get(url)
557    >>> with open('[2K]Gravel04.zip', 'bw') as f:
558    ...     f.write(r.content)
559
560    >>> with zipfile.ZipFile('[2K]Gravel04.zip') as z:
561    ...     z.extract('Gravel04_col.jpg')
562
563    >>> from skimage.transform import resize
564    >>> gravel_orig = imageio.imread('Gravel04_col.jpg')
565    >>> gravel = resize(gravel_orig, (1024, 1024))
566    >>> gravel = skimage.img_as_ubyte(skimage.color.rgb2gray(gravel[:512, :512]))
567    >>> imageio.imwrite('gravel.png', gravel)
568    """
569    return _load("data/gravel.png", as_gray=True)
570
571
572def text():
573    """Gray-level "text" image used for corner detection.
574
575    Notes
576    -----
577    This image was downloaded from Wikipedia
578    <https://en.wikipedia.org/wiki/File:Corner.png>`__.
579
580    No known copyright restrictions, released into the public domain.
581
582    Returns
583    -------
584    text : (172, 448) uint8 ndarray
585        Text image.
586    """
587
588    return _load("data/text.png")
589
590
591def checkerboard():
592    """Checkerboard image.
593
594    Checkerboards are often used in image calibration, since the
595    corner-points are easy to locate.  Because of the many parallel
596    edges, they also visualise distortions particularly well.
597
598    Returns
599    -------
600    checkerboard : (200, 200) uint8 ndarray
601        Checkerboard image.
602    """
603    return _load("data/chessboard_GRAY.png")
604
605
606def cells3d():
607    """3D fluorescence microscopy image of cells.
608
609    The returned data is a 3D multichannel array with dimensions provided in
610    ``(z, c, y, x)`` order. Each voxel has a size of ``(0.29 0.26 0.26)``
611    micrometer. Channel 0 contains cell membranes, channel 1 contains nuclei.
612
613    Returns
614    -------
615    cells3d: (60, 2, 256, 256) uint16 ndarray
616        The volumetric images of cells taken with an optical microscope.
617
618    Notes
619    -----
620    The data for this was provided by the Allen Institute for Cell Science.
621
622    It has been downsampled by a factor of 4 in the row and column dimensions
623    to reduce computational time.
624
625    The microscope reports the following voxel spacing in microns:
626
627        * Original voxel size is ``(0.290, 0.065, 0.065)``.
628        * Scaling factor is ``(1, 4, 4)`` in each dimension.
629        * After rescaling the voxel size is ``(0.29 0.26 0.26)``.
630    """
631
632    return _load("data/cells3d.tif")
633
634
635def human_mitosis():
636    """Image of human cells undergoing mitosis.
637
638    Returns
639    -------
640    human_mitosis: (512, 512) uint8 ndimage
641        Data of human cells undergoing mitosis taken during the preperation
642        of the manuscript in [1]_.
643
644    Notes
645    -----
646    Copyright David Root. Licensed under CC-0 [2]_.
647
648    References
649    ----------
650    .. [1] Moffat J, Grueneberg DA, Yang X, Kim SY, Kloepfer AM, Hinkle G,
651           Piqani B, Eisenhaure TM, Luo B, Grenier JK, Carpenter AE, Foo SY,
652           Stewart SA, Stockwell BR, Hacohen N, Hahn WC, Lander ES,
653           Sabatini DM, Root DE (2006) A lentiviral RNAi library for human and
654           mouse genes applied to an arrayed viral high-content screen. Cell,
655           124(6):1283-98 / :DOI: `10.1016/j.cell.2006.01.040` PMID 16564017
656
657    .. [2] GitHub licensing discussion
658           https://github.com/CellProfiler/examples/issues/41
659
660    """
661    return _load('data/mitosis.tif')
662
663
664def cell():
665    """Cell floating in saline.
666
667    This is a quantitative phase image retrieved from a digital hologram using
668    the Python library ``qpformat``. The image shows a cell with high phase
669    value, above the background phase.
670
671    Because of a banding pattern artifact in the background, this image is a
672    good test of thresholding algorithms. The pixel spacing is 0.107 µm.
673
674    These data were part of a comparison between several refractive index
675    retrieval techniques for spherical objects as part of [1]_.
676
677    This image is CC0, dedicated to the public domain. You may copy, modify, or
678    distribute it without asking permission.
679
680    Returns
681    -------
682    cell : (660, 550) uint8 array
683        Image of a cell.
684
685    References
686    ----------
687    .. [1] Paul Müller, Mirjam Schürmann, Salvatore Girardo, Gheorghe Cojoc,
688           and Jochen Guck. "Accurate evaluation of size and refractive index
689           for spherical objects in quantitative phase imaging." Optics Express
690           26(8): 10729-10743 (2018). :DOI:`10.1364/OE.26.010729`
691    """
692    return _load('data/cell.png')
693
694
695def coins():
696    """Greek coins from Pompeii.
697
698    This image shows several coins outlined against a gray background.
699    It is especially useful in, e.g. segmentation tests, where
700    individual objects need to be identified against a background.
701    The background shares enough grey levels with the coins that a
702    simple segmentation is not sufficient.
703
704    Notes
705    -----
706    This image was downloaded from the
707    `Brooklyn Museum Collection
708    <https://www.brooklynmuseum.org/opencollection/archives/image/51611>`__.
709
710    No known copyright restrictions.
711
712    Returns
713    -------
714    coins : (303, 384) uint8 ndarray
715        Coins image.
716    """
717    return _load("data/coins.png")
718
719
720def kidney():
721    """Mouse kidney tissue.
722
723    This biological tissue on a pre-prepared slide was imaged with confocal
724    fluorescence microscopy (Nikon C1 inverted microscope).
725    Image shape is (16, 512, 512, 3). That is 512x512 pixels in X-Y,
726    16 image slices in Z, and 3 color channels
727    (emission wavelengths 450nm, 515nm, and 605nm, respectively).
728    Real-space voxel size is 1.24 microns in X-Y, and 1.25 microns in Z.
729    Data type is unsigned 16-bit integers.
730
731    Notes
732    -----
733    This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in
734    2018.
735    License: CC0
736
737    Returns
738    -------
739    kidney : (16, 512, 512, 3) uint16 ndarray
740        Kidney 3D multichannel image.
741    """
742    return _load("data/kidney.tif")
743
744
745def lily():
746    """Lily of the valley plant stem.
747
748    This plant stem on a pre-prepared slide was imaged with confocal
749    fluorescence microscopy (Nikon C1 inverted microscope).
750    Image shape is (922, 922, 4). That is 922x922 pixels in X-Y,
751    with 4 color channels.
752    Real-space voxel size is 1.24 microns in X-Y.
753    Data type is unsigned 16-bit integers.
754
755    Notes
756    -----
757    This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in
758    2018.
759    License: CC0
760
761    Returns
762    -------
763    lily : (922, 922, 4) uint16 ndarray
764        Lily 2D multichannel image.
765    """
766    return _load("data/lily.tif")
767
768
769def logo():
770    """Scikit-image logo, a RGBA image.
771
772    Returns
773    -------
774    logo : (500, 500, 4) uint8 ndarray
775        Logo image.
776    """
777    return _load("data/logo.png")
778
779
780def microaneurysms():
781    """Gray-level "microaneurysms" image.
782
783    Detail from an image of the retina (green channel).
784    The image is a crop of image 07_dr.JPG from the
785    High-Resolution Fundus (HRF) Image Database:
786    https://www5.cs.fau.de/research/data/fundus-images/
787
788    Notes
789    -----
790    No copyright restrictions. CC0 given by owner (Andreas Maier).
791
792    Returns
793    -------
794    microaneurysms : (102, 102) uint8 ndarray
795        Retina image with lesions.
796
797    References
798    ----------
799    .. [1] Budai, A., Bock, R, Maier, A., Hornegger, J.,
800           Michelson, G. (2013).  Robust Vessel Segmentation in Fundus
801           Images. International Journal of Biomedical Imaging, vol. 2013,
802           2013.
803           :DOI:`10.1155/2013/154860`
804    """
805    return _load("data/microaneurysms.png")
806
807
808def moon():
809    """Surface of the moon.
810
811    This low-contrast image of the surface of the moon is useful for
812    illustrating histogram equalization and contrast stretching.
813
814    Returns
815    -------
816    moon : (512, 512) uint8 ndarray
817        Moon image.
818    """
819    return _load("data/moon.png")
820
821
822def page():
823    """Scanned page.
824
825    This image of printed text is useful for demonstrations requiring uneven
826    background illumination.
827
828    Returns
829    -------
830    page : (191, 384) uint8 ndarray
831        Page image.
832    """
833    return _load("data/page.png")
834
835
836def horse():
837    """Black and white silhouette of a horse.
838
839    This image was downloaded from
840    `openclipart <http://openclipart.org/detail/158377/horse-by-marauder>`
841
842    No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)).
843
844    Returns
845    -------
846    horse : (328, 400) bool ndarray
847        Horse image.
848    """
849    return img_as_bool(_load("data/horse.png", as_gray=True))
850
851
852def clock():
853    """Motion blurred clock.
854
855    This photograph of a wall clock was taken while moving the camera in an
856    aproximately horizontal direction.  It may be used to illustrate
857    inverse filters and deconvolution.
858
859    Released into the public domain by the photographer (Stefan van der Walt).
860
861    Returns
862    -------
863    clock : (300, 400) uint8 ndarray
864        Clock image.
865    """
866    return _load("data/clock_motion.png")
867
868
869def immunohistochemistry():
870    """Immunohistochemical (IHC) staining with hematoxylin counterstaining.
871
872    This picture shows colonic glands where the IHC expression of FHL2 protein
873    is revealed with DAB. Hematoxylin counterstaining is applied to enhance the
874    negative parts of the tissue.
875
876    This image was acquired at the Center for Microscopy And Molecular Imaging
877    (CMMI).
878
879    No known copyright restrictions.
880
881    Returns
882    -------
883    immunohistochemistry : (512, 512, 3) uint8 ndarray
884        Immunohistochemistry image.
885    """
886    return _load("data/ihc.png")
887
888
889def chelsea():
890    """Chelsea the cat.
891
892    An example with texture, prominent edges in horizontal and diagonal
893    directions, as well as features of differing scales.
894
895    Notes
896    -----
897    No copyright restrictions.  CC0 by the photographer (Stefan van der Walt).
898
899    Returns
900    -------
901    chelsea : (300, 451, 3) uint8 ndarray
902        Chelsea image.
903    """
904    return _load("data/chelsea.png")
905
906
907# Define an alias for chelsea that is more descriptive.
908cat = chelsea
909
910
911def coffee():
912    """Coffee cup.
913
914    This photograph is courtesy of Pikolo Espresso Bar.
915    It contains several elliptical shapes as well as varying texture (smooth
916    porcelain to course wood grain).
917
918    Notes
919    -----
920    No copyright restrictions.  CC0 by the photographer (Rachel Michetti).
921
922    Returns
923    -------
924    coffee : (400, 600, 3) uint8 ndarray
925        Coffee image.
926    """
927    return _load("data/coffee.png")
928
929
930def hubble_deep_field():
931    """Hubble eXtreme Deep Field.
932
933    This photograph contains the Hubble Telescope's farthest ever view of
934    the universe. It can be useful as an example for multi-scale
935    detection.
936
937    Notes
938    -----
939    This image was downloaded from
940    `HubbleSite
941    <http://hubblesite.org/newscenter/archive/releases/2012/37/image/a/>`__.
942
943    The image was captured by NASA and `may be freely used in the public domain
944    <http://www.nasa.gov/audience/formedia/features/MP_Photo_Guidelines.html>`_.
945
946    Returns
947    -------
948    hubble_deep_field : (872, 1000, 3) uint8 ndarray
949        Hubble deep field image.
950    """
951    return _load("data/hubble_deep_field.jpg")
952
953
954def retina():
955    """Human retina.
956
957    This image of a retina is useful for demonstrations requiring circular
958    images.
959
960    Notes
961    -----
962    This image was downloaded from
963    `wikimedia <https://commons.wikimedia.org/wiki/File:Fundus_photograph_of_normal_left_eye.jpg>`.
964    This file is made available under the Creative Commons CC0 1.0 Universal
965    Public Domain Dedication.
966
967    References
968    ----------
969    .. [1] Häggström, Mikael (2014). "Medical gallery of Mikael Häggström 2014".
970           WikiJournal of Medicine 1 (2). :DOI:`10.15347/wjm/2014.008`.
971           ISSN 2002-4436. Public Domain
972
973    Returns
974    -------
975    retina : (1411, 1411, 3) uint8 ndarray
976        Retina image in RGB.
977    """
978    return _load("data/retina.jpg")
979
980
981def shepp_logan_phantom():
982    """Shepp Logan Phantom.
983
984    References
985    ----------
986    .. [1] L. A. Shepp and B. F. Logan, "The Fourier reconstruction of a head
987           section," in IEEE Transactions on Nuclear Science, vol. 21,
988           no. 3, pp. 21-43, June 1974. :DOI:`10.1109/TNS.1974.6499235`
989
990    Returns
991    -------
992    phantom : (400, 400) float64 image
993        Image of the Shepp-Logan phantom in grayscale.
994    """
995    return _load("data/phantom.png", as_gray=True)
996
997
998def colorwheel():
999    """Color Wheel.
1000
1001    Returns
1002    -------
1003    colorwheel : (370, 371, 3) uint8 image
1004        A colorwheel.
1005    """
1006    return _load("data/color.png")
1007
1008
1009def rocket():
1010    """Launch photo of DSCOVR on Falcon 9 by SpaceX.
1011
1012    This is the launch photo of Falcon 9 carrying DSCOVR lifted off from
1013    SpaceX's Launch Complex 40 at Cape Canaveral Air Force Station, FL.
1014
1015    Notes
1016    -----
1017    This image was downloaded from
1018    `SpaceX Photos
1019    <https://www.flickr.com/photos/spacexphotos/16511594820/in/photostream/>`__.
1020
1021    The image was captured by SpaceX and `released in the public domain
1022    <http://arstechnica.com/tech-policy/2015/03/elon-musk-puts-spacex-photos-into-the-public-domain/>`_.
1023
1024    Returns
1025    -------
1026    rocket : (427, 640, 3) uint8 ndarray
1027        Rocket image.
1028    """
1029    return _load("data/rocket.jpg")
1030
1031
1032def stereo_motorcycle():
1033    """Rectified stereo image pair with ground-truth disparities.
1034
1035    The two images are rectified such that every pixel in the left image has
1036    its corresponding pixel on the same scanline in the right image. That means
1037    that both images are warped such that they have the same orientation but a
1038    horizontal spatial offset (baseline). The ground-truth pixel offset in
1039    column direction is specified by the included disparity map.
1040
1041    The two images are part of the Middlebury 2014 stereo benchmark. The
1042    dataset was created by Nera Nesic, Porter Westling, Xi Wang, York Kitajima,
1043    Greg Krathwohl, and Daniel Scharstein at Middlebury College. A detailed
1044    description of the acquisition process can be found in [1]_.
1045
1046    The images included here are down-sampled versions of the default exposure
1047    images in the benchmark. The images are down-sampled by a factor of 4 using
1048    the function `skimage.transform.downscale_local_mean`. The calibration data
1049    in the following and the included ground-truth disparity map are valid for
1050    the down-sampled images::
1051
1052        Focal length:           994.978px
1053        Principal point x:      311.193px
1054        Principal point y:      254.877px
1055        Principal point dx:      31.086px
1056        Baseline:               193.001mm
1057
1058    Returns
1059    -------
1060    img_left : (500, 741, 3) uint8 ndarray
1061        Left stereo image.
1062    img_right : (500, 741, 3) uint8 ndarray
1063        Right stereo image.
1064    disp : (500, 741, 3) float ndarray
1065        Ground-truth disparity map, where each value describes the offset in
1066        column direction between corresponding pixels in the left and the right
1067        stereo images. E.g. the corresponding pixel of
1068        ``img_left[10, 10 + disp[10, 10]]`` is ``img_right[10, 10]``.
1069        NaNs denote pixels in the left image that do not have ground-truth.
1070
1071    Notes
1072    -----
1073    The original resolution images, images with different exposure and
1074    lighting, and ground-truth depth maps can be found at the Middlebury
1075    website [2]_.
1076
1077    References
1078    ----------
1079    .. [1] D. Scharstein, H. Hirschmueller, Y. Kitajima, G. Krathwohl, N.
1080           Nesic, X. Wang, and P. Westling. High-resolution stereo datasets
1081           with subpixel-accurate ground truth. In German Conference on Pattern
1082           Recognition (GCPR 2014), Muenster, Germany, September 2014.
1083    .. [2] http://vision.middlebury.edu/stereo/data/scenes2014/
1084
1085    """
1086    filename = _fetch("data/motorcycle_disp.npz")
1087    disp = np.load(filename)['arr_0']
1088    return (_load("data/motorcycle_left.png"),
1089            _load("data/motorcycle_right.png"),
1090            disp)
1091
1092
1093def lfw_subset():
1094    """Subset of data from the LFW dataset.
1095
1096    This database is a subset of the LFW database containing:
1097
1098    * 100 faces
1099    * 100 non-faces
1100
1101    The full dataset is available at [2]_.
1102
1103    Returns
1104    -------
1105    images : (200, 25, 25) uint8 ndarray
1106        100 first images are faces and subsequent 100 are non-faces.
1107
1108    Notes
1109    -----
1110    The faces were randomly selected from the LFW dataset and the non-faces
1111    were extracted from the background of the same dataset. The cropped ROIs
1112    have been resized to a 25 x 25 pixels.
1113
1114    References
1115    ----------
1116    .. [1] Huang, G., Mattar, M., Lee, H., & Learned-Miller, E. G. (2012).
1117           Learning to align from scratch. In Advances in Neural Information
1118           Processing Systems (pp. 764-772).
1119    .. [2] http://vis-www.cs.umass.edu/lfw/
1120
1121    """
1122    return np.load(_fetch('data/lfw_subset.npy'))
1123
1124
1125def skin():
1126    """Microscopy image of dermis and epidermis (skin layers).
1127
1128    Hematoxylin and eosin stained slide at 10x of normal epidermis and dermis
1129    with a benign intradermal nevus.
1130
1131    Notes
1132    -----
1133    This image requires an Internet connection the first time it is called,
1134    and to have the ``pooch`` package installed, in order to fetch the image
1135    file from the scikit-image datasets repository.
1136
1137    The source of this image is
1138    https://en.wikipedia.org/wiki/File:Normal_Epidermis_and_Dermis_with_Intradermal_Nevus_10x.JPG
1139
1140    The image was released in the public domain by its author Kilbad.
1141
1142    Returns
1143    -------
1144    skin : (960, 1280, 3) RGB image of uint8
1145    """
1146    return _load('data/skin.jpg')
1147
1148
1149def brain():
1150    """Subset of data from the University of North Carolina Volume Rendering
1151    Test Data Set.
1152
1153    The full dataset is available at [1]_.
1154
1155    Returns
1156    -------
1157    image : (10, 256, 256) uint16 ndarray
1158
1159    Notes
1160    -----
1161    The 3D volume consists of 10 layers from the larger volume.
1162
1163    References
1164    ----------
1165    .. [1] https://graphics.stanford.edu/data/voldata/
1166
1167    """
1168    return _load("data/brain.tiff")
1169
1170
1171def vortex():
1172    """Case B1 image pair from the first PIV challenge.
1173
1174    Returns
1175    -------
1176    image0, image1 : (512, 512) grayscale images
1177        A pair of images featuring synthetic moving particles.
1178
1179    Notes
1180    -----
1181    This image was licensed as CC0 by its author, Prof. Koji Okamoto, with
1182    thanks to Prof. Jun Sakakibara, who maintains the PIV Challenge site.
1183
1184    References
1185    ----------
1186    .. [1] Particle Image Velocimetry (PIV) Challenge site
1187           http://pivchallenge.org
1188    .. [2] 1st PIV challenge Case B: http://pivchallenge.org/pub/index.html#b
1189    """
1190    return (_load('data/pivchallenge-B-B001_1.tif'),
1191            _load('data/pivchallenge-B-B001_2.tif'))
1192