scikit-image API Reference
Full documentation for scikit-image (0.25.2)
scikit-image.color
Python Library Documentation: package skimage.color in skimage
NAME
skimage.color - Color space conversion.
PACKAGE CONTENTS
adapt_rgb
colorconv
colorlabel
delta_e
rgb_colors
tests (package)
FUNCTIONS
combine_stains(stains, conv_matrix, *, channel_axis=-1)
Stain to RGB color space conversion.
Parameters
----------
stains : (..., C=3, ...) array_like
The image in stain color space. By default, the final dimension denotes
channels.
conv_matrix: ndarray
The stain separation matrix as described by G. Landini [1]_.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `stains` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Stain combination matrices available in the ``color`` module and their
respective colorspace:
* ``rgb_from_hed``: Hematoxylin + Eosin + DAB
* ``rgb_from_hdx``: Hematoxylin + DAB
* ``rgb_from_fgx``: Feulgen + Light Green
* ``rgb_from_bex``: Giemsa stain : Methyl Blue + Eosin
* ``rgb_from_rbd``: FastRed + FastBlue + DAB
* ``rgb_from_gdx``: Methyl Green + DAB
* ``rgb_from_hax``: Hematoxylin + AEC
* ``rgb_from_bro``: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G
* ``rgb_from_bpx``: Methyl Blue + Ponceau Fuchsin
* ``rgb_from_ahx``: Alcian Blue + Hematoxylin
* ``rgb_from_hpx``: Hematoxylin + PAS
References
----------
.. [1] https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html
.. [2] A. C. Ruifrok and D. A. Johnston, “Quantification of histochemical
staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol.
23, no. 4, pp. 291–299, Aug. 2001.
Examples
--------
>>> from skimage import data
>>> from skimage.color import (separate_stains, combine_stains,
... hdx_from_rgb, rgb_from_hdx)
>>> ihc = data.immunohistochemistry()
>>> ihc_hdx = separate_stains(ihc, hdx_from_rgb)
>>> ihc_rgb = combine_stains(ihc_hdx, rgb_from_hdx)
convert_colorspace(arr, fromspace, tospace, *, channel_axis=-1)
Convert an image array to a new color space.
Valid color spaces are:
'RGB', 'HSV', 'RGB CIE', 'XYZ', 'YUV', 'YIQ', 'YPbPr', 'YCbCr', 'YDbDr'
Parameters
----------
arr : (..., C=3, ...) array_like
The image to convert. By default, the final dimension denotes
channels.
fromspace : str
The color space to convert from. Can be specified in lower case.
tospace : str
The color space to convert to. Can be specified in lower case.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The converted image. Same dimensions as input.
Raises
------
ValueError
If fromspace is not a valid color space
ValueError
If tospace is not a valid color space
Notes
-----
Conversion is performed through the "central" RGB color space,
i.e. conversion from XYZ to HSV is implemented as ``XYZ -> RGB -> HSV``
instead of directly.
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = convert_colorspace(img, 'RGB', 'HSV')
deltaE_cie76(lab1, lab2, channel_axis=-1)
Euclidean distance between two points in Lab color space
Parameters
----------
lab1 : array_like
reference color (Lab colorspace)
lab2 : array_like
comparison color (Lab colorspace)
channel_axis : int, optional
This parameter indicates which axis of the arrays corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
dE : array_like
distance between colors `lab1` and `lab2`
References
----------
.. [1] https://en.wikipedia.org/wiki/Color_difference
.. [2] A. R. Robertson, "The CIE 1976 color-difference formulae,"
Color Res. Appl. 2, 7-11 (1977).
deltaE_ciede2000(lab1, lab2, kL=1, kC=1, kH=1, *, channel_axis=-1)
Color difference as given by the CIEDE 2000 standard.
CIEDE 2000 is a major revision of CIDE94. The perceptual calibration is
largely based on experience with automotive paint on smooth surfaces.
Parameters
----------
lab1 : array_like
reference color (Lab colorspace)
lab2 : array_like
comparison color (Lab colorspace)
kL : float (range), optional
lightness scale factor, 1 for "acceptably close"; 2 for "imperceptible"
see deltaE_cmc
kC : float (range), optional
chroma scale factor, usually 1
kH : float (range), optional
hue scale factor, usually 1
channel_axis : int, optional
This parameter indicates which axis of the arrays corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
deltaE : array_like
The distance between `lab1` and `lab2`
Notes
-----
CIEDE 2000 assumes parametric weighting factors for the lightness, chroma,
and hue (`kL`, `kC`, `kH` respectively). These default to 1.
References
----------
.. [1] https://en.wikipedia.org/wiki/Color_difference
.. [2] http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf
:DOI:`10.1364/AO.33.008069`
.. [3] M. Melgosa, J. Quesada, and E. Hita, "Uniformity of some recent
color metrics tested with an accurate color-difference tolerance
dataset," Appl. Opt. 33, 8069-8077 (1994).
deltaE_ciede94(lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015, *, channel_axis=-1)
Color difference according to CIEDE 94 standard
Accommodates perceptual non-uniformities through the use of application
specific scale factors (`kH`, `kC`, `kL`, `k1`, and `k2`).
Parameters
----------
lab1 : array_like
reference color (Lab colorspace)
lab2 : array_like
comparison color (Lab colorspace)
kH : float, optional
Hue scale
kC : float, optional
Chroma scale
kL : float, optional
Lightness scale
k1 : float, optional
first scale parameter
k2 : float, optional
second scale parameter
channel_axis : int, optional
This parameter indicates which axis of the arrays corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
dE : array_like
color difference between `lab1` and `lab2`
Notes
-----
deltaE_ciede94 is not symmetric with respect to lab1 and lab2. CIEDE94
defines the scales for the lightness, hue, and chroma in terms of the first
color. Consequently, the first color should be regarded as the "reference"
color.
`kL`, `k1`, `k2` depend on the application and default to the values
suggested for graphic arts
========== ============== ==========
Parameter Graphic Arts Textiles
========== ============== ==========
`kL` 1.000 2.000
`k1` 0.045 0.048
`k2` 0.015 0.014
========== ============== ==========
References
----------
.. [1] https://en.wikipedia.org/wiki/Color_difference
.. [2] http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
deltaE_cmc(lab1, lab2, kL=1, kC=1, *, channel_axis=-1)
Color difference from the CMC l:c standard.
This color difference was developed by the Colour Measurement Committee
(CMC) of the Society of Dyers and Colourists (United Kingdom). It is
intended for use in the textile industry.
The scale factors `kL`, `kC` set the weight given to differences in
lightness and chroma relative to differences in hue. The usual values are
``kL=2``, ``kC=1`` for "acceptability" and ``kL=1``, ``kC=1`` for
"imperceptibility". Colors with ``dE > 1`` are "different" for the given
scale factors.
Parameters
----------
lab1 : array_like
reference color (Lab colorspace)
lab2 : array_like
comparison color (Lab colorspace)
channel_axis : int, optional
This parameter indicates which axis of the arrays corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
dE : array_like
distance between colors `lab1` and `lab2`
Notes
-----
deltaE_cmc the defines the scales for the lightness, hue, and chroma
in terms of the first color. Consequently
``deltaE_cmc(lab1, lab2) != deltaE_cmc(lab2, lab1)``
References
----------
.. [1] https://en.wikipedia.org/wiki/Color_difference
.. [2] http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
.. [3] F. J. J. Clarke, R. McDonald, and B. Rigg, "Modification to the
JPC79 colour-difference formula," J. Soc. Dyers Colour. 100, 128-132
(1984).
gray2rgb(image, *, channel_axis=-1)
Create an RGB representation of a gray-level image.
Parameters
----------
image : array_like
Input image.
channel_axis : int, optional
This parameter indicates which axis of the output array will correspond
to channels.
Returns
-------
rgb : (..., C=3, ...) ndarray
RGB image. A new dimension of length 3 is added to input image.
Notes
-----
If the input is a 1-dimensional image of shape ``(M,)``, the output
will be shape ``(M, C=3)``.
gray2rgba(image, alpha=None, *, channel_axis=-1)
Create a RGBA representation of a gray-level image.
Parameters
----------
image : array_like
Input image.
alpha : array_like, optional
Alpha channel of the output image. It may be a scalar or an
array that can be broadcast to ``image``. If not specified it is
set to the maximum limit corresponding to the ``image`` dtype.
channel_axis : int, optional
This parameter indicates which axis of the output array will correspond
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
rgba : ndarray
RGBA image. A new dimension of length 4 is added to input
image shape.
hed2rgb(hed, *, channel_axis=-1)
Haematoxylin-Eosin-DAB (HED) to RGB color space conversion.
Parameters
----------
hed : (..., C=3, ...) array_like
The image in the HED color space. By default, the final dimension
denotes channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB. Same dimensions as input.
Raises
------
ValueError
If `hed` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] A. C. Ruifrok and D. A. Johnston, "Quantification of histochemical
staining by color deconvolution.," Analytical and quantitative
cytology and histology / the International Academy of Cytology [and]
American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001.
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2hed, hed2rgb
>>> ihc = data.immunohistochemistry()
>>> ihc_hed = rgb2hed(ihc)
>>> ihc_rgb = hed2rgb(ihc_hed)
hsv2rgb(hsv, *, channel_axis=-1)
HSV to RGB color space conversion.
Parameters
----------
hsv : (..., C=3, ...) array_like
The image in HSV format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `hsv` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Conversion between RGB and HSV color spaces results in some loss of
precision, due to integer arithmetic and rounding [1]_.
References
----------
.. [1] https://en.wikipedia.org/wiki/HSL_and_HSV
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = rgb2hsv(img)
>>> img_rgb = hsv2rgb(img_hsv)
lab2lch(lab, *, channel_axis=-1)
Convert image in CIE-LAB to CIE-LCh color space.
CIE-LCh is the cylindrical representation of the CIE-LAB (Cartesian) color
space.
Parameters
----------
lab : (..., C=3, ...) array_like
The input image in CIE-LAB color space.
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
channels.
The L* values range from 0 to 100;
the a* and b* values range from -128 to 127.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in CIE-LCh color space, of same shape as input.
Raises
------
ValueError
If `lab` does not have at least 3 channels (i.e., L*, a*, and b*).
Notes
-----
The h channel (i.e., hue) is expressed as an angle in range ``(0, 2*pi)``.
See Also
--------
lch2lab
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELAB_color_space
.. [3] https://en.wikipedia.org/wiki/HCL_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2lab, lab2lch
>>> img = data.astronaut()
>>> img_lab = rgb2lab(img)
>>> img_lch = lab2lch(img_lab)
lab2rgb(lab, illuminant='D65', observer='2', *, channel_axis=-1)
Convert image in CIE-LAB to sRGB color space.
Parameters
----------
lab : (..., C=3, ...) array_like
The input image in CIE-LAB color space.
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
channels.
The L* values range from 0 to 100;
the a* and b* values range from -128 to 127.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
The aperture angle of the observer.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in sRGB color space, of same shape as input.
Raises
------
ValueError
If `lab` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
This function uses :func:`~.lab2xyz` and :func:`~.xyz2rgb`.
The CIE XYZ tristimulus values are x_ref = 95.047, y_ref = 100., and
z_ref = 108.883. See function :func:`~.xyz_tristimulus_values` for a list of
supported illuminants.
See Also
--------
rgb2lab
References
----------
.. [1] https://en.wikipedia.org/wiki/Standard_illuminant
.. [2] https://en.wikipedia.org/wiki/CIELAB_color_space
lab2xyz(lab, illuminant='D65', observer='2', *, channel_axis=-1)
Convert image in CIE-LAB to XYZ color space.
Parameters
----------
lab : (..., C=3, ...) array_like
The input image in CIE-LAB color space.
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
channels.
The L* values range from 0 to 100;
the a* and b* values range from -128 to 127.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
The aperture angle of the observer.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in XYZ color space, of same shape as input.
Raises
------
ValueError
If `lab` is not at least 2-D with shape (..., C=3, ...).
ValueError
If either the illuminant or the observer angle are not supported or
unknown.
UserWarning
If any of the pixels are invalid (Z < 0).
Notes
-----
The CIE XYZ tristimulus values are x_ref = 95.047, y_ref = 100., and
z_ref = 108.883. See function :func:`~.xyz_tristimulus_values` for a list of
supported illuminants.
See Also
--------
xyz2lab
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELAB_color_space
label2rgb(label, image=None, colors=None, alpha=0.3, bg_label=0, bg_color=(0, 0, 0), image_alpha=1, kind='overlay', *, saturation=0, channel_axis=-1)
Return an RGB image where color-coded labels are painted over the image.
Parameters
----------
label : ndarray
Integer array of labels with the same shape as `image`.
image : ndarray, optional
Image used as underlay for labels. It should have the same shape as
`labels`, optionally with an additional RGB (channels) axis. If `image`
is an RGB image, it is converted to grayscale before coloring.
colors : list, optional
List of colors. If the number of labels exceeds the number of colors,
then the colors are cycled.
alpha : float [0, 1], optional
Opacity of colorized labels. Ignored if image is `None`.
bg_label : int, optional
Label that's treated as the background. If `bg_label` is specified,
`bg_color` is `None`, and `kind` is `overlay`,
background is not painted by any colors.
bg_color : str or array, optional
Background color. Must be a name in ``skimage.color.color_dict`` or RGB float
values between [0, 1].
image_alpha : float [0, 1], optional
Opacity of the image.
kind : string, one of {'overlay', 'avg'}
The kind of color image desired. 'overlay' cycles over defined colors
and overlays the colored labels over the original image. 'avg' replaces
each labeled segment with its average color, for a stained-class or
pastel painting appearance.
saturation : float [0, 1], optional
Parameter to control the saturation applied to the original image
between fully saturated (original RGB, `saturation=1`) and fully
unsaturated (grayscale, `saturation=0`). Only applies when
`kind='overlay'`.
channel_axis : int, optional
This parameter indicates which axis of the output array will correspond
to channels. If `image` is provided, this must also match the axis of
`image` that corresponds to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
result : ndarray of float, same shape as `image`
The result of blending a cycling colormap (`colors`) for each distinct
value in `label` with the image, at a certain alpha value.
lch2lab(lch, *, channel_axis=-1)
Convert image in CIE-LCh to CIE-LAB color space.
CIE-LCh is the cylindrical representation of the CIE-LAB (Cartesian) color
space.
Parameters
----------
lch : (..., C=3, ...) array_like
The input image in CIE-LCh color space.
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
channels.
The L* values range from 0 to 100;
the C values range from 0 to 100;
the h values range from 0 to ``2*pi``.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in CIE-LAB format, of same shape as input.
Raises
------
ValueError
If `lch` does not have at least 3 channels (i.e., L*, C, and h).
Notes
-----
The h channel (i.e., hue) is expressed as an angle in range ``(0, 2*pi)``.
See Also
--------
lab2lch
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/HCL_color_space
.. [3] https://en.wikipedia.org/wiki/CIELAB_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2lab, lch2lab, lab2lch
>>> img = data.astronaut()
>>> img_lab = rgb2lab(img)
>>> img_lch = lab2lch(img_lab)
>>> img_lab2 = lch2lab(img_lch)
luv2rgb(luv, *, channel_axis=-1)
Luv to RGB color space conversion.
Parameters
----------
luv : (..., C=3, ...) array_like
The image in CIE Luv format. By default, the final dimension denotes
channels.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `luv` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
This function uses luv2xyz and xyz2rgb.
luv2xyz(luv, illuminant='D65', observer='2', *, channel_axis=-1)
CIE-Luv to XYZ color space conversion.
Parameters
----------
luv : (..., C=3, ...) array_like
The image in CIE-Luv format. By default, the final dimension denotes
channels.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
The aperture angle of the observer.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in XYZ format. Same dimensions as input.
Raises
------
ValueError
If `luv` is not at least 2-D with shape (..., C=3, ...).
ValueError
If either the illuminant or the observer angle are not supported or
unknown.
Notes
-----
XYZ conversion weights use observer=2A. Reference whitepoint for D65
Illuminant, with XYZ tristimulus values of ``(95.047, 100., 108.883)``. See
function :func:`~.xyz_tristimulus_values` for a list of supported illuminants.
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELUV
rgb2gray(rgb, *, channel_axis=-1)
Compute luminance of an RGB image.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
Returns
-------
out : ndarray
The luminance image - an array which is the same size as the input
array, but with the channel dimension removed.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The weights used in this conversion are calibrated for contemporary
CRT phosphors::
Y = 0.2125 R + 0.7154 G + 0.0721 B
If there is an alpha channel present, it is ignored.
References
----------
.. [1] http://poynton.ca/PDFs/ColorFAQ.pdf
Examples
--------
>>> from skimage.color import rgb2gray
>>> from skimage import data
>>> img = data.astronaut()
>>> img_gray = rgb2gray(img)
rgb2hed(rgb, *, channel_axis=-1)
RGB to Haematoxylin-Eosin-DAB (HED) color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in HED format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] A. C. Ruifrok and D. A. Johnston, "Quantification of histochemical
staining by color deconvolution.," Analytical and quantitative
cytology and histology / the International Academy of Cytology [and]
American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001.
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2hed
>>> ihc = data.immunohistochemistry()
>>> ihc_hed = rgb2hed(ihc)
rgb2hsv(rgb, *, channel_axis=-1)
RGB to HSV color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in HSV format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Conversion between RGB and HSV color spaces results in some loss of
precision, due to integer arithmetic and rounding [1]_.
References
----------
.. [1] https://en.wikipedia.org/wiki/HSL_and_HSV
Examples
--------
>>> from skimage import color
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = color.rgb2hsv(img)
rgb2lab(rgb, illuminant='D65', observer='2', *, channel_axis=-1)
Conversion from the sRGB color space (IEC 61966-2-1:1999)
to the CIE Lab colorspace under the given illuminant and observer.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
The aperture angle of the observer.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in Lab format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
RGB is a device-dependent color space so, if you use this function, be
sure that the image you are analyzing has been mapped to the sRGB color
space.
This function uses rgb2xyz and xyz2lab.
By default Observer="2", Illuminant="D65". CIE XYZ tristimulus values
x_ref=95.047, y_ref=100., z_ref=108.883. See function
:func:`~.xyz_tristimulus_values` for a list of supported illuminants.
References
----------
.. [1] https://en.wikipedia.org/wiki/Standard_illuminant
rgb2luv(rgb, *, channel_axis=-1)
RGB to CIE-Luv color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in CIE Luv format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
This function uses rgb2xyz and xyz2luv.
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELUV
rgb2rgbcie(rgb, *, channel_axis=-1)
RGB to RGB CIE color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB CIE format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2rgbcie
>>> img = data.astronaut()
>>> img_rgbcie = rgb2rgbcie(img)
rgb2xyz(rgb, *, channel_axis=-1)
RGB to XYZ color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in XYZ format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The CIE XYZ color space is derived from the CIE RGB color space. Note
however that this function converts from sRGB.
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
rgb2ycbcr(rgb, *, channel_axis=-1)
RGB to YCbCr color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in YCbCr format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Y is between 16 and 235. This is the color space commonly used by video
codecs; it is sometimes incorrectly called "YUV".
References
----------
.. [1] https://en.wikipedia.org/wiki/YCbCr
rgb2ydbdr(rgb, *, channel_axis=-1)
RGB to YDbDr color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in YDbDr format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
This is the color space commonly used by video codecs. It is also the
reversible color transform in JPEG2000.
References
----------
.. [1] https://en.wikipedia.org/wiki/YDbDr
rgb2yiq(rgb, *, channel_axis=-1)
RGB to YIQ color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in YIQ format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
rgb2ypbpr(rgb, *, channel_axis=-1)
RGB to YPbPr color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in YPbPr format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/YPbPr
rgb2yuv(rgb, *, channel_axis=-1)
RGB to YUV color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in YUV format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Y is between 0 and 1. Use YCbCr instead of YUV for the color space
commonly used by video codecs, where Y ranges from 16 to 235.
References
----------
.. [1] https://en.wikipedia.org/wiki/YUV
rgba2rgb(rgba, background=(1, 1, 1), *, channel_axis=-1)
RGBA to RGB conversion using alpha blending [1]_.
Parameters
----------
rgba : (..., C=4, ...) array_like
The image in RGBA format. By default, the final dimension denotes
channels.
background : array_like
The color of the background to blend the image with (3 floats
between 0 to 1 - the RGB value of the background).
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `rgba` is not at least 2D with shape (..., 4, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
Examples
--------
>>> from skimage import color
>>> from skimage import data
>>> img_rgba = data.logo()
>>> img_rgb = color.rgba2rgb(img_rgba)
rgbcie2rgb(rgbcie, *, channel_axis=-1)
RGB CIE to RGB color space conversion.
Parameters
----------
rgbcie : (..., C=3, ...) array_like
The image in RGB CIE format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `rgbcie` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2rgbcie, rgbcie2rgb
>>> img = data.astronaut()
>>> img_rgbcie = rgb2rgbcie(img)
>>> img_rgb = rgbcie2rgb(img_rgbcie)
separate_stains(rgb, conv_matrix, *, channel_axis=-1)
RGB to stain color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
conv_matrix: ndarray
The stain separation matrix as described by G. Landini [1]_.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in stain color space. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Stain separation matrices available in the ``color`` module and their
respective colorspace:
* ``hed_from_rgb``: Hematoxylin + Eosin + DAB
* ``hdx_from_rgb``: Hematoxylin + DAB
* ``fgx_from_rgb``: Feulgen + Light Green
* ``bex_from_rgb``: Giemsa stain : Methyl Blue + Eosin
* ``rbd_from_rgb``: FastRed + FastBlue + DAB
* ``gdx_from_rgb``: Methyl Green + DAB
* ``hax_from_rgb``: Hematoxylin + AEC
* ``bro_from_rgb``: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G
* ``bpx_from_rgb``: Methyl Blue + Ponceau Fuchsin
* ``ahx_from_rgb``: Alcian Blue + Hematoxylin
* ``hpx_from_rgb``: Hematoxylin + PAS
This implementation borrows some ideas from DIPlib [2]_, e.g. the
compensation using a small value to avoid log artifacts when
calculating the Beer-Lambert law.
References
----------
.. [1] https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html
.. [2] https://github.com/DIPlib/diplib/
.. [3] A. C. Ruifrok and D. A. Johnston, “Quantification of histochemical
staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol.
23, no. 4, pp. 291–299, Aug. 2001.
Examples
--------
>>> from skimage import data
>>> from skimage.color import separate_stains, hdx_from_rgb
>>> ihc = data.immunohistochemistry()
>>> ihc_hdx = separate_stains(ihc, hdx_from_rgb)
xyz2lab(xyz, illuminant='D65', observer='2', *, channel_axis=-1)
XYZ to CIE-LAB color space conversion.
Parameters
----------
xyz : (..., C=3, ...) array_like
The image in XYZ format. By default, the final dimension denotes
channels.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
One of: 2-degree observer, 10-degree observer, or 'R' observer as in
R function grDevices::convertColor.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in CIE-LAB format. Same dimensions as input.
Raises
------
ValueError
If `xyz` is not at least 2-D with shape (..., C=3, ...).
ValueError
If either the illuminant or the observer angle is unsupported or
unknown.
Notes
-----
By default Observer="2", Illuminant="D65". CIE XYZ tristimulus values
x_ref=95.047, y_ref=100., z_ref=108.883. See function
:func:`~.xyz_tristimulus_values` for a list of supported illuminants.
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELAB_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2xyz, xyz2lab
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
>>> img_lab = xyz2lab(img_xyz)
xyz2luv(xyz, illuminant='D65', observer='2', *, channel_axis=-1)
XYZ to CIE-Luv color space conversion.
Parameters
----------
xyz : (..., C=3, ...) array_like
The image in XYZ format. By default, the final dimension denotes
channels.
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}, optional
The aperture angle of the observer.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in CIE-Luv format. Same dimensions as input.
Raises
------
ValueError
If `xyz` is not at least 2-D with shape (..., C=3, ...).
ValueError
If either the illuminant or the observer angle are not supported or
unknown.
Notes
-----
By default XYZ conversion weights use observer=2A. Reference whitepoint
for D65 Illuminant, with XYZ tristimulus values of ``(95.047, 100.,
108.883)``. See function :func:`~.xyz_tristimulus_values` for a list of supported
illuminants.
References
----------
.. [1] http://www.easyrgb.com/en/math.php
.. [2] https://en.wikipedia.org/wiki/CIELUV
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2xyz, xyz2luv
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
>>> img_luv = xyz2luv(img_xyz)
xyz2rgb(xyz, *, channel_axis=-1)
XYZ to RGB color space conversion.
Parameters
----------
xyz : (..., C=3, ...) array_like
The image in XYZ format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `xyz` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The CIE XYZ color space is derived from the CIE RGB color space. Note
however that this function converts to sRGB.
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2xyz, xyz2rgb
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
>>> img_rgb = xyz2rgb(img_xyz)
xyz_tristimulus_values(*, illuminant, observer, dtype=<class 'float'>)
Get the CIE XYZ tristimulus values.
Given an illuminant and observer, this function returns the CIE XYZ tristimulus
values [2]_ scaled such that :math:`Y = 1`.
Parameters
----------
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}
One of: 2-degree observer, 10-degree observer, or 'R' observer as in
R function ``grDevices::convertColor`` [3]_.
dtype: dtype, optional
Output data type.
Returns
-------
values : array
Array with 3 elements :math:`X, Y, Z` containing the CIE XYZ tristimulus values
of the given illuminant.
Raises
------
ValueError
If either the illuminant or the observer angle are not supported or
unknown.
References
----------
.. [1] https://en.wikipedia.org/wiki/Standard_illuminant#White_points_of_standard_illuminants
.. [2] https://en.wikipedia.org/wiki/CIE_1931_color_space#Meaning_of_X,_Y_and_Z
.. [3] https://www.rdocumentation.org/packages/grDevices/versions/3.6.2/topics/convertColor
Notes
-----
The CIE XYZ tristimulus values are calculated from :math:`x, y` [1]_, using the
formula
.. math:: X = x / y
.. math:: Y = 1
.. math:: Z = (1 - x - y) / y
The only exception is the illuminant "D65" with aperture angle 2° for
backward-compatibility reasons.
Examples
--------
Get the CIE XYZ tristimulus values for a "D65" illuminant for a 10 degree field of
view
>>> xyz_tristimulus_values(illuminant="D65", observer="10")
array([0.94809668, 1. , 1.07305136])
ycbcr2rgb(ycbcr, *, channel_axis=-1)
YCbCr to RGB color space conversion.
Parameters
----------
ycbcr : (..., C=3, ...) array_like
The image in YCbCr format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `ycbcr` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Y is between 16 and 235. This is the color space commonly used by video
codecs; it is sometimes incorrectly called "YUV".
References
----------
.. [1] https://en.wikipedia.org/wiki/YCbCr
ydbdr2rgb(ydbdr, *, channel_axis=-1)
YDbDr to RGB color space conversion.
Parameters
----------
ydbdr : (..., C=3, ...) array_like
The image in YDbDr format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `ydbdr` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
This is the color space commonly used by video codecs, also called the
reversible color transform in JPEG2000.
References
----------
.. [1] https://en.wikipedia.org/wiki/YDbDr
yiq2rgb(yiq, *, channel_axis=-1)
YIQ to RGB color space conversion.
Parameters
----------
yiq : (..., C=3, ...) array_like
The image in YIQ format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `yiq` is not at least 2-D with shape (..., C=3, ...).
ypbpr2rgb(ypbpr, *, channel_axis=-1)
YPbPr to RGB color space conversion.
Parameters
----------
ypbpr : (..., C=3, ...) array_like
The image in YPbPr format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `ypbpr` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/YPbPr
yuv2rgb(yuv, *, channel_axis=-1)
YUV to RGB color space conversion.
Parameters
----------
yuv : (..., C=3, ...) array_like
The image in YUV format. By default, the final dimension denotes
channels.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `yuv` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/YUV
DATA
ahx_from_rgb = array([[ 1.7793645 , -1.02183021, 0.19629009],
...
...
bex_from_rgb = array([[ 1.27238604, -0.70058186, -0.06873155],
...
...
bpx_from_rgb = array([[ 1.12901624, -0.561991 , 0.48367952],
...
...
bro_from_rgb = array([[ 1.22676889, -0.84839467, 0.30132221],
...
...
color_dict = {'aliceblue': (0.941, 0.973, 1), 'antiquewhite': (0.98, 0...
fgx_from_rgb = array([[-0.42297694, 1.24783103, 0.17179157],
...
...
gdx_from_rgb = array([[ 1.07756696, -0.21523401, 0.04528954],
...
...
hax_from_rgb = array([[ 1.51369317, -1.01440242, 1.03438371],
...
...
hdx_from_rgb = array([[ 1.20013702, -0.6897672 , 1.05605387],
...
...
hed_from_rgb = array([[ 1.87798274, -1.00767869, -0.55611582],
...
...
hpx_from_rgb = array([[ 1.79624863, -1.35324306, -0.5396002 ],
...
...
rbd_from_rgb = array([[-1.32952977, 1.62200656, 0.26012351],
...
...
rgb_from_ahx = array([[ 0.874622 , 0.457711 , 0.158256 ],
...
...
rgb_from_bex = array([[ 0.83475023, 0.51355628, 0.1963304 ],
...
...
rgb_from_bpx = array([[ 0.7995107 , 0.5913521 , 0.10528667],
...
...
rgb_from_bro = array([[0.853033 , 0.508733 , 0.112656 ],
...8],
...
rgb_from_fgx = array([[ 0.46420921, 0.83008335, 0.30827187],
...
...
rgb_from_gdx = array([[ 0.98003 , 0.144316 , 0.133146 ],
...
...
rgb_from_hax = array([[ 0.65 , 0.704 , 0.286 ],
... ],
...
rgb_from_hdx = array([[ 0.65 , 0.704 , 0.286 ],
...6 ...
rgb_from_hed = array([[0.65, 0.7 , 0.29],
[0.07, 0.99, 0.11],
...
rgb_from_hpx = array([[ 0.644211 , 0.716556 , 0.266844 ],
...
...
rgb_from_rbd = array([[0.21393921, 0.85112669, 0.47794022],
...2],
...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\color\__init__.py
scikit-image.data
Python Library Documentation: package skimage.data in skimage
NAME
skimage.data - Example images and datasets.
DESCRIPTION
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`.
PACKAGE CONTENTS
_binary_blobs
_fetchers
_registry
tests (package)
FUNCTIONS
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
<https://flic.kr/p/r9qvLn>`__.
No known copyright restrictions, released into the public domain.
Returns
-------
astronaut : (512, 512, 3) uint8 ndarray
Astronaut image.
binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, rng=None)
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.
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)
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/
brick()
Brick wall.
Returns
-------
brick : (512, 512) uint8 image
A small section of a brick wall.
Notes
-----
The original image was downloaded from
`CC0Textures <https://cc0textures.com/view.php?tex=Bricks25>`_ 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.
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
cat = 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.
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`
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)``.
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.
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.
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.
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.
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
<https://www.brooklynmuseum.org/opencollection/archives/image/51611>`__.
No known copyright restrictions.
Returns
-------
coins : (303, 384) uint8 ndarray
Coins image.
colorwheel()
Color Wheel.
Returns
-------
colorwheel : (370, 371, 3) uint8 image
A colorwheel.
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``.
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.
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)
grass()
Grass.
Returns
-------
grass : (512, 512) uint8 image
Some grass.
Notes
-----
The original image was downloaded from
`DeviantArt <https://www.deviantart.com/linolafett/art/Grass-01-434853879>`__
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.
gravel()
Gravel
Returns
-------
gravel : (512, 512) uint8 image
Grayscale gravel sample.
Notes
-----
The original image was downloaded from
`CC0Textures <https://cc0textures.com/view.php?tex=Gravel04>`__ 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.
horse()
Black and white silhouette of a horse.
This image was downloaded from
`openclipart <http://openclipart.org/detail/158377/horse-by-marauder>`
No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)).
Returns
-------
horse : (328, 400) bool ndarray
Horse image.
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
<http://hubblesite.org/newscenter/archive/releases/2012/37/image/a/>`__.
The image was captured by NASA and `may be freely used in the public domain
<http://www.nasa.gov/audience/formedia/features/MP_Photo_Guidelines.html>`_.
Returns
-------
hubble_deep_field : (872, 1000, 3) uint8 ndarray
Hubble deep field image.
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
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.
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.
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
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/
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.
logo()
Scikit-image logo, a RGBA image.
Returns
-------
logo : (500, 500, 4) uint8 ndarray
Logo image.
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`
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.
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.
page()
Scanned page.
This image of printed text is useful for demonstrations requiring uneven
background illumination.
Returns
-------
page : (191, 384) uint8 ndarray
Page image.
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.
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.
retina()
Human retina.
This image of a retina is useful for demonstrations requiring circular
images.
Notes
-----
This image was downloaded from
`wikimedia <https://commons.wikimedia.org/wiki/File:Fundus_photograph_of_normal_left_eye.jpg>`.
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.
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
<https://www.flickr.com/photos/spacexphotos/16511594820/in/photostream/>`__.
The image was captured by SpaceX and `released in the public domain
<http://arstechnica.com/tech-policy/2015/03/elon-musk-puts-spacex-photos-into-the-public-domain/>`_.
Returns
-------
rocket : (427, 640, 3) uint8 ndarray
Rocket image.
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.
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
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/
text()
Gray-level "text" image used for corner detection.
Notes
-----
This image was downloaded from Wikipedia
<https://en.wikipedia.org/wiki/File:Corner.png>`__.
No known copyright restrictions, released into the public domain.
Returns
-------
text : (172, 448) uint8 ndarray
Text image.
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
DATA
data_dir = r'C:\Users\Youse\AppData\Local\scikit-image\scikit-image\Ca...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\data\__init__.py
scikit-image.draw
Python Library Documentation: package skimage.draw in skimage
NAME
skimage.draw - Drawing primitives, such as lines, circles, text, etc.
PACKAGE CONTENTS
_draw
_polygon2mask
_random_shapes
draw
draw3d
draw_nd
tests (package)
FUNCTIONS
_bezier_segment(r0, c0, r1, c1, r2, c2, weight)
Generate Bezier segment coordinates.
Parameters
----------
r0, c0 : int
Coordinates of the first control point.
r1, c1 : int
Coordinates of the middle control point.
r2, c2 : int
Coordinates of the last control point.
weight : cnp.float64_t
Middle control point weight, it describes the line tension.
Returns
-------
rr, cc : (N,) ndarray of int
Indices of pixels that belong to the Bezier curve.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Notes
-----
The algorithm is the rational quadratic algorithm presented in
reference [1]_.
References
----------
.. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012
http://members.chello.at/easyfilter/Bresenham.pdf
bezier_curve(r0, c0, r1, c1, r2, c2, weight, shape=None)
Generate Bezier curve coordinates.
Parameters
----------
r0, c0 : int
Coordinates of the first control point.
r1, c1 : int
Coordinates of the middle control point.
r2, c2 : int
Coordinates of the last control point.
weight : double
Middle control point weight, it describes the line tension.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for curves that exceed the image
size. If None, the full extent of the curve is used.
Returns
-------
rr, cc : (N,) ndarray of int
Indices of pixels that belong to the Bezier curve.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Notes
-----
The algorithm is the rational quadratic algorithm presented in
reference [1]_.
References
----------
.. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012
http://members.chello.at/easyfilter/Bresenham.pdf
Examples
--------
>>> import numpy as np
>>> from skimage.draw import bezier_curve
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = bezier_curve(1, 5, 5, -2, 8, 8, 2)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
circle_perimeter(r, c, radius, method='bresenham', shape=None)
Generate circle perimeter coordinates.
Parameters
----------
r, c : int
Centre coordinate of circle.
radius : int
Radius of circle.
method : {'bresenham', 'andres'}, optional
bresenham : Bresenham method (default)
andres : Andres method
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for circles that exceed the image
size. If None, the full extent of the circle is used. Must be at least
length 2. Only the first two values are used to determine the extent of
the input image.
Returns
-------
rr, cc : (N,) ndarray of int
Bresenham and Andres' method:
Indices of pixels that belong to the circle perimeter.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Notes
-----
Andres method presents the advantage that concentric
circles create a disc whereas Bresenham can make holes. There
is also less distortions when Andres circles are rotated.
Bresenham method is also known as midpoint circle algorithm.
Anti-aliased circle generator is available with `circle_perimeter_aa`.
References
----------
.. [1] J.E. Bresenham, "Algorithm for computer control of a digital
plotter", IBM Systems journal, 4 (1965) 25-30.
.. [2] E. Andres, "Discrete circles, rings and spheres", Computers &
Graphics, 18 (1994) 695-706.
Examples
--------
>>> from skimage.draw import circle_perimeter
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = circle_perimeter(4, 4, 3)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
circle_perimeter_aa(r, c, radius, shape=None)
Generate anti-aliased circle perimeter coordinates.
Parameters
----------
r, c : int
Centre coordinate of circle.
radius : int
Radius of circle.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for circles that exceed the image
size. If None, the full extent of the circle is used. Must be at least
length 2. Only the first two values are used to determine the extent of
the input image.
Returns
-------
rr, cc, val : (N,) ndarray (int, int, float)
Indices of pixels (`rr`, `cc`) and intensity values (`val`).
``img[rr, cc] = val``.
Notes
-----
Wu's method draws anti-aliased circle. This implementation doesn't use
lookup table optimization.
Use the function ``draw.set_color`` to apply ``circle_perimeter_aa``
results to color images.
References
----------
.. [1] X. Wu, "An efficient antialiasing technique", In ACM SIGGRAPH
Computer Graphics, 25 (1991) 143-152.
Examples
--------
>>> from skimage.draw import circle_perimeter_aa
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc, val = circle_perimeter_aa(4, 4, 3)
>>> img[rr, cc] = val * 255
>>> img
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0],
[ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0],
[ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0],
[ 0, 255, 0, 0, 0, 0, 0, 255, 0, 0],
[ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0],
[ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0],
[ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> from skimage import data, draw
>>> image = data.chelsea()
>>> rr, cc, val = draw.circle_perimeter_aa(r=100, c=100, radius=75)
>>> draw.set_color(image, (rr, cc), [1, 0, 0], alpha=val)
disk(center, radius, *, shape=None)
Generate coordinates of pixels within circle.
Parameters
----------
center : tuple
Center coordinate of disk.
radius : double
Radius of disk.
shape : tuple, optional
Image shape as a tuple of size 2. Determines the maximum
extent of output pixel coordinates. This is useful for disks that
exceed the image size. If None, the full extent of the disk is used.
The shape might result in negative coordinates and wraparound
behaviour.
Returns
-------
rr, cc : ndarray of int
Pixel coordinates of disk.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Examples
--------
>>> import numpy as np
>>> from skimage.draw import disk
>>> shape = (4, 4)
>>> img = np.zeros(shape, dtype=np.uint8)
>>> rr, cc = disk((0, 0), 2, shape=shape)
>>> img[rr, cc] = 1
>>> img
array([[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=uint8)
>>> img = np.zeros(shape, dtype=np.uint8)
>>> # Negative coordinates in rr and cc perform a wraparound
>>> rr, cc = disk((0, 0), 2, shape=None)
>>> img[rr, cc] = 1
>>> img
array([[1, 1, 0, 1],
[1, 1, 0, 1],
[0, 0, 0, 0],
[1, 1, 0, 1]], dtype=uint8)
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = disk((4, 4), 5)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
ellipse(r, c, r_radius, c_radius, shape=None, rotation=0.0)
Generate coordinates of pixels within ellipse.
Parameters
----------
r, c : double
Centre coordinate of ellipse.
r_radius, c_radius : double
Minor and major semi-axes. ``(r/r_radius)**2 + (c/c_radius)**2 = 1``.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output pixel
coordinates. This is useful for ellipses which exceed the image size.
By default the full extent of the ellipse are used. Must be at least
length 2. Only the first two values are used to determine the extent.
rotation : float, optional (default 0.)
Set the ellipse rotation (rotation) in range (-PI, PI)
in contra clock wise direction, so PI/2 degree means swap ellipse axis
Returns
-------
rr, cc : ndarray of int
Pixel coordinates of ellipse.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Examples
--------
>>> from skimage.draw import ellipse
>>> img = np.zeros((10, 12), dtype=np.uint8)
>>> rr, cc = ellipse(5, 6, 3, 5, rotation=np.deg2rad(30))
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
Notes
-----
The ellipse equation::
((x * cos(alpha) + y * sin(alpha)) / x_radius) ** 2 +
((x * sin(alpha) - y * cos(alpha)) / y_radius) ** 2 = 1
Note that the positions of `ellipse` without specified `shape` can have
also, negative values, as this is correct on the plane. On the other hand
using these ellipse positions for an image afterwards may lead to appearing
on the other side of image, because ``image[-1, -1] = image[end-1, end-1]``
>>> rr, cc = ellipse(1, 2, 3, 6)
>>> img = np.zeros((6, 12), dtype=np.uint8)
>>> img[rr, cc] = 1
>>> img
array([[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1]], dtype=uint8)
ellipse_perimeter(r, c, r_radius, c_radius, orientation=0, shape=None)
Generate ellipse perimeter coordinates.
Parameters
----------
r, c : int
Centre coordinate of ellipse.
r_radius, c_radius : int
Minor and major semi-axes. ``(r/r_radius)**2 + (c/c_radius)**2 = 1``.
orientation : double, optional
Major axis orientation in clockwise direction as radians.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for ellipses that exceed the image
size. If None, the full extent of the ellipse is used. Must be at
least length 2. Only the first two values are used to determine the
extent of the input image.
Returns
-------
rr, cc : (N,) ndarray of int
Indices of pixels that belong to the ellipse perimeter.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
References
----------
.. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012
http://members.chello.at/easyfilter/Bresenham.pdf
Examples
--------
>>> from skimage.draw import ellipse_perimeter
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = ellipse_perimeter(5, 5, 3, 4)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
Note that the positions of `ellipse` without specified `shape` can have
also, negative values, as this is correct on the plane. On the other hand
using these ellipse positions for an image afterwards may lead to appearing
on the other side of image, because ``image[-1, -1] = image[end-1, end-1]``
>>> rr, cc = ellipse_perimeter(2, 3, 4, 5)
>>> img = np.zeros((9, 12), dtype=np.uint8)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=uint8)
ellipsoid(a, b, c, spacing=(1.0, 1.0, 1.0), levelset=False)
Generate ellipsoid for given semi-axis lengths.
The respective semi-axis lengths are given along three dimensions in
Cartesian coordinates. Each dimension may use a different grid spacing.
Parameters
----------
a : float
Length of semi-axis along x-axis.
b : float
Length of semi-axis along y-axis.
c : float
Length of semi-axis along z-axis.
spacing : 3-tuple of floats
Grid spacing in three spatial dimensions.
levelset : bool
If True, returns the level set for this ellipsoid (signed level
set about zero, with positive denoting interior) as np.float64.
False returns a binarized version of said level set.
Returns
-------
ellipsoid : (M, N, P) array
Ellipsoid centered in a correctly sized array for given `spacing`.
Boolean dtype unless `levelset=True`, in which case a float array is
returned with the level set above 0.0 representing the ellipsoid.
ellipsoid_stats(a, b, c)
Calculate analytical volume and surface area of an ellipsoid.
The surface area of an ellipsoid is given by
.. math:: S=4\pi b c R_G\!\left(1, \frac{a^2}{b^2}, \frac{a^2}{c^2}\right)
where :math:`R_G` is Carlson's completely symmetric elliptic integral of
the second kind [1]_. The latter is implemented as
:py:func:`scipy.special.elliprg`.
Parameters
----------
a : float
Length of semi-axis along x-axis.
b : float
Length of semi-axis along y-axis.
c : float
Length of semi-axis along z-axis.
Returns
-------
vol : float
Calculated volume of ellipsoid.
surf : float
Calculated surface area of ellipsoid.
References
----------
.. [1] Paul Masson (2020). Surface Area of an Ellipsoid.
https://analyticphysics.com/Mathematical%20Methods/Surface%20Area%20of%20an%20Ellipsoid.htm
line(r0, c0, r1, c1)
Generate line pixel coordinates.
Parameters
----------
r0, c0 : int
Starting position (row, column).
r1, c1 : int
End position (row, column).
Returns
-------
rr, cc : (N,) ndarray of int
Indices of pixels that belong to the line.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Notes
-----
Anti-aliased line generator is available with `line_aa`.
Examples
--------
>>> from skimage.draw import line
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = line(1, 1, 8, 8)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
line_aa(r0, c0, r1, c1)
Generate anti-aliased line pixel coordinates.
Parameters
----------
r0, c0 : int
Starting position (row, column).
r1, c1 : int
End position (row, column).
Returns
-------
rr, cc, val : (N,) ndarray (int, int, float)
Indices of pixels (`rr`, `cc`) and intensity values (`val`).
``img[rr, cc] = val``.
References
----------
.. [1] A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012
http://members.chello.at/easyfilter/Bresenham.pdf
Examples
--------
>>> from skimage.draw import line_aa
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc, val = line_aa(1, 1, 8, 8)
>>> img[rr, cc] = val * 255
>>> img
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 255, 74, 0, 0, 0, 0, 0, 0, 0],
[ 0, 74, 255, 74, 0, 0, 0, 0, 0, 0],
[ 0, 0, 74, 255, 74, 0, 0, 0, 0, 0],
[ 0, 0, 0, 74, 255, 74, 0, 0, 0, 0],
[ 0, 0, 0, 0, 74, 255, 74, 0, 0, 0],
[ 0, 0, 0, 0, 0, 74, 255, 74, 0, 0],
[ 0, 0, 0, 0, 0, 0, 74, 255, 74, 0],
[ 0, 0, 0, 0, 0, 0, 0, 74, 255, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
line_nd(start, stop, *, endpoint=False, integer=True)
Draw a single-pixel thick line in n dimensions.
The line produced will be ndim-connected. That is, two subsequent
pixels in the line will be either direct or diagonal neighbors in
n dimensions.
Parameters
----------
start : array-like, shape (N,)
The start coordinates of the line.
stop : array-like, shape (N,)
The end coordinates of the line.
endpoint : bool, optional
Whether to include the endpoint in the returned line. Defaults
to False, which allows for easy drawing of multi-point paths.
integer : bool, optional
Whether to round the coordinates to integer. If True (default),
the returned coordinates can be used to directly index into an
array. `False` could be used for e.g. vector drawing.
Returns
-------
coords : tuple of arrays
The coordinates of points on the line.
Examples
--------
>>> lin = line_nd((1, 1), (5, 2.5), endpoint=False)
>>> lin
(array([1, 2, 3, 4]), array([1, 1, 2, 2]))
>>> im = np.zeros((6, 5), dtype=int)
>>> im[lin] = 1
>>> im
array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])
>>> line_nd([2, 1, 1], [5, 5, 2.5], endpoint=True)
(array([2, 3, 4, 4, 5]), array([1, 2, 3, 4, 5]), array([1, 1, 2, 2, 2]))
polygon(r, c, shape=None)
Generate coordinates of pixels inside a polygon.
Parameters
----------
r : (N,) array_like
Row coordinates of the polygon's vertices.
c : (N,) array_like
Column coordinates of the polygon's vertices.
shape : tuple, optional
Image shape which is used to determine the maximum extent of output
pixel coordinates. This is useful for polygons that exceed the image
size. If None, the full extent of the polygon is used. Must be at
least length 2. Only the first two values are used to determine the
extent of the input image.
Returns
-------
rr, cc : ndarray of int
Pixel coordinates of polygon.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
See Also
--------
polygon2mask:
Create a binary mask from a polygon.
Notes
-----
This function ensures that `rr` and `cc` don't contain negative values.
Pixels of the polygon that whose coordinates are smaller 0, are not drawn.
Examples
--------
>>> import skimage as ski
>>> r = np.array([1, 2, 8])
>>> c = np.array([1, 7, 4])
>>> rr, cc = ski.draw.polygon(r, c)
>>> img = np.zeros((10, 10), dtype=int)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
If the image `shape` is defined and vertices / points of the `polygon` are
outside this coordinate space, only a part (or none at all) of the polygon's
pixels is returned. Shifting the polygon's vertices by an offset can be used
to move the polygon around and potentially draw an arbitrary sub-region of
the polygon.
>>> offset = (2, -4)
>>> rr, cc = ski.draw.polygon(r - offset[0], c - offset[1], shape=img.shape)
>>> img = np.zeros((10, 10), dtype=int)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
polygon2mask(image_shape, polygon)
Create a binary mask from a polygon.
Parameters
----------
image_shape : tuple of size 2
The shape of the mask.
polygon : (N, 2) array_like
The polygon coordinates of shape (N, 2) where N is
the number of points. The coordinates are (row, column).
Returns
-------
mask : 2-D ndarray of type 'bool'
The binary mask that corresponds to the input polygon.
See Also
--------
polygon:
Generate coordinates of pixels inside a polygon.
Notes
-----
This function does not do any border checking. Parts of the polygon that
are outside the coordinate space defined by `image_shape` are not drawn.
Examples
--------
>>> import skimage as ski
>>> image_shape = (10, 10)
>>> polygon = np.array([[1, 1], [2, 7], [8, 4]])
>>> mask = ski.draw.polygon2mask(image_shape, polygon)
>>> mask.astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
If vertices / points of the `polygon` are outside the coordinate space
defined by `image_shape`, only a part (or none at all) of the polygon is
drawn in the mask.
>>> offset = np.array([[2, -4]])
>>> ski.draw.polygon2mask(image_shape, polygon - offset).astype(int)
array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
polygon_perimeter(r, c, shape=None, clip=False)
Generate polygon perimeter coordinates.
Parameters
----------
r : (N,) ndarray
Row coordinates of vertices of polygon.
c : (N,) ndarray
Column coordinates of vertices of polygon.
shape : tuple, optional
Image shape which is used to determine maximum extents of output pixel
coordinates. This is useful for polygons that exceed the image size.
If None, the full extents of the polygon is used. Must be at least
length 2. Only the first two values are used to determine the extent of
the input image.
clip : bool, optional
Whether to clip the polygon to the provided shape. If this is set
to True, the drawn figure will always be a closed polygon with all
edges visible.
Returns
-------
rr, cc : ndarray of int
Pixel coordinates of polygon.
May be used to directly index into an array, e.g.
``img[rr, cc] = 1``.
Examples
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('matplotlib')
>>> from skimage.draw import polygon_perimeter
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = polygon_perimeter([5, -1, 5, 10],
... [-1, 5, 11, 5],
... shape=img.shape, clip=True)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)
random_shapes(image_shape, max_shapes, min_shapes=1, min_size=2, max_size=None, num_channels=3, shape=None, intensity_range=None, allow_overlap=False, num_trials=100, rng=None, *, channel_axis=-1)
Generate an image with random shapes, labeled with bounding boxes.
The image is populated with random shapes with random sizes, random
locations, and random colors, with or without overlap.
Shapes have random (row, col) starting coordinates and random sizes bounded
by `min_size` and `max_size`. It can occur that a randomly generated shape
will not fit the image at all. In that case, the algorithm will try again
with new starting coordinates a certain number of times. However, it also
means that some shapes may be skipped altogether. In that case, this
function will generate fewer shapes than requested.
Parameters
----------
image_shape : tuple
The number of rows and columns of the image to generate.
max_shapes : int
The maximum number of shapes to (attempt to) fit into the shape.
min_shapes : int, optional
The minimum number of shapes to (attempt to) fit into the shape.
min_size : int, optional
The minimum dimension of each shape to fit into the image.
max_size : int, optional
The maximum dimension of each shape to fit into the image.
num_channels : int, optional
Number of channels in the generated image. If 1, generate monochrome
images, else color images with multiple channels. Ignored if
``multichannel`` is set to False.
shape : {rectangle, circle, triangle, ellipse, None} str, optional
The name of the shape to generate or `None` to pick random ones.
intensity_range : {tuple of tuples of uint8, tuple of uint8}, optional
The range of values to sample pixel values from. For grayscale
images the format is (min, max). For multichannel - ((min, max),)
if the ranges are equal across the channels, and
((min_0, max_0), ... (min_N, max_N)) if they differ. As the
function supports generation of uint8 arrays only, the maximum
range is (0, 255). If None, set to (0, 254) for each channel
reserving color of intensity = 255 for background.
allow_overlap : bool, optional
If `True`, allow shapes to overlap.
num_trials : int, optional
How often to attempt to fit a shape into the image before skipping it.
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
image : uint8 array
An image with the fitted shapes.
labels : list
A list of labels, one per shape in the image. Each label is a
(category, ((r0, r1), (c0, c1))) tuple specifying the category and
bounding box coordinates of the shape.
Examples
--------
>>> import skimage.draw
>>> image, labels = skimage.draw.random_shapes((32, 32), max_shapes=3)
>>> image # doctest: +SKIP
array([
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8)
>>> labels # doctest: +SKIP
[('circle', ((22, 18), (25, 21))),
('triangle', ((5, 6), (13, 13)))]
rectangle(start, end=None, extent=None, shape=None)
Generate coordinates of pixels within a rectangle.
Parameters
----------
start : tuple
Origin point of the rectangle, e.g., ``([plane,] row, column)``.
end : tuple
End point of the rectangle ``([plane,] row, column)``.
For a 2D matrix, the slice defined by the rectangle is
``[start:(end+1)]``.
Either `end` or `extent` must be specified.
extent : tuple
The extent (size) of the drawn rectangle. E.g.,
``([num_planes,] num_rows, num_cols)``.
Either `end` or `extent` must be specified.
A negative extent is valid, and will result in a rectangle
going along the opposite direction. If extent is negative, the
`start` point is not included.
shape : tuple, optional
Image shape used to determine the maximum bounds of the output
coordinates. This is useful for clipping rectangles that exceed
the image size. By default, no clipping is done.
Returns
-------
coords : array of int, shape (Ndim, Npoints)
The coordinates of all pixels in the rectangle.
Notes
-----
This function can be applied to N-dimensional images, by passing `start` and
`end` or `extent` as tuples of length N.
Examples
--------
>>> import numpy as np
>>> from skimage.draw import rectangle
>>> img = np.zeros((5, 5), dtype=np.uint8)
>>> start = (1, 1)
>>> extent = (3, 3)
>>> rr, cc = rectangle(start, extent=extent, shape=img.shape)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> img = np.zeros((5, 5), dtype=np.uint8)
>>> start = (0, 1)
>>> end = (3, 3)
>>> rr, cc = rectangle(start, end=end, shape=img.shape)
>>> img[rr, cc] = 1
>>> img
array([[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> import numpy as np
>>> from skimage.draw import rectangle
>>> img = np.zeros((6, 6), dtype=np.uint8)
>>> start = (3, 3)
>>>
>>> rr, cc = rectangle(start, extent=(2, 2))
>>> img[rr, cc] = 1
>>> rr, cc = rectangle(start, extent=(-2, 2))
>>> img[rr, cc] = 2
>>> rr, cc = rectangle(start, extent=(-2, -2))
>>> img[rr, cc] = 3
>>> rr, cc = rectangle(start, extent=(2, -2))
>>> img[rr, cc] = 4
>>> print(img)
[[0 0 0 0 0 0]
[0 3 3 2 2 0]
[0 3 3 2 2 0]
[0 4 4 1 1 0]
[0 4 4 1 1 0]
[0 0 0 0 0 0]]
rectangle_perimeter(start, end=None, extent=None, shape=None, clip=False)
Generate coordinates of pixels that are exactly around a rectangle.
Parameters
----------
start : tuple
Origin point of the inner rectangle, e.g., ``(row, column)``.
end : tuple
End point of the inner rectangle ``(row, column)``.
For a 2D matrix, the slice defined by inner the rectangle is
``[start:(end+1)]``.
Either `end` or `extent` must be specified.
extent : tuple
The extent (size) of the inner rectangle. E.g.,
``(num_rows, num_cols)``.
Either `end` or `extent` must be specified.
Negative extents are permitted. See `rectangle` to better
understand how they behave.
shape : tuple, optional
Image shape used to determine the maximum bounds of the output
coordinates. This is useful for clipping perimeters that exceed
the image size. By default, no clipping is done. Must be at least
length 2. Only the first two values are used to determine the extent of
the input image.
clip : bool, optional
Whether to clip the perimeter to the provided shape. If this is set
to True, the drawn figure will always be a closed polygon with all
edges visible.
Returns
-------
coords : array of int, shape (2, Npoints)
The coordinates of all pixels in the rectangle.
Examples
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('matplotlib')
>>> import numpy as np
>>> from skimage.draw import rectangle_perimeter
>>> img = np.zeros((5, 6), dtype=np.uint8)
>>> start = (2, 3)
>>> end = (3, 4)
>>> rr, cc = rectangle_perimeter(start, end=end, shape=img.shape)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 1]], dtype=uint8)
>>> img = np.zeros((5, 5), dtype=np.uint8)
>>> r, c = rectangle_perimeter(start, (10, 10), shape=img.shape, clip=True)
>>> img[r, c] = 1
>>> img
array([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 1],
[0, 0, 1, 0, 1],
[0, 0, 1, 0, 1],
[0, 0, 1, 1, 1]], dtype=uint8)
set_color(image, coords, color, alpha=1)
Set pixel color in the image at the given coordinates.
Note that this function modifies the color of the image in-place.
Coordinates that exceed the shape of the image will be ignored.
Parameters
----------
image : (M, N, C) ndarray
Image
coords : tuple of ((K,) ndarray, (K,) ndarray)
Row and column coordinates of pixels to be colored.
color : (C,) ndarray
Color to be assigned to coordinates in the image.
alpha : scalar or (K,) ndarray
Alpha values used to blend color with image. 0 is transparent,
1 is opaque.
Examples
--------
>>> from skimage.draw import line, set_color
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = line(1, 1, 20, 20)
>>> set_color(img, (rr, cc), 1)
>>> img
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=uint8)
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\draw\__init__.py
scikit-image.exposure
Python Library Documentation: package skimage.exposure in skimage
NAME
skimage.exposure - Image intensity adjustment, e.g., histogram equalization, etc.
PACKAGE CONTENTS
_adapthist
exposure
histogram_matching
tests (package)
FUNCTIONS
adjust_gamma(image, gamma=1, gain=1)
Performs Gamma Correction on the input image.
Also known as Power Law Transform.
This function transforms the input image pixelwise according to the
equation ``O = I**gamma`` after scaling each pixel to the range 0 to 1.
Parameters
----------
image : ndarray
Input image.
gamma : float, optional
Non negative real number. Default value is 1.
gain : float, optional
The constant multiplier. Default value is 1.
Returns
-------
out : ndarray
Gamma corrected output image.
See Also
--------
adjust_log
Notes
-----
For gamma greater than 1, the histogram will shift towards left and
the output image will be darker than the input image.
For gamma less than 1, the histogram will shift towards right and
the output image will be brighter than the input image.
References
----------
.. [1] https://en.wikipedia.org/wiki/Gamma_correction
Examples
--------
>>> from skimage import data, exposure, img_as_float
>>> image = img_as_float(data.moon())
>>> gamma_corrected = exposure.adjust_gamma(image, 2)
>>> # Output is darker for gamma > 1
>>> image.mean() > gamma_corrected.mean()
True
adjust_log(image, gain=1, inv=False)
Performs Logarithmic correction on the input image.
This function transforms the input image pixelwise according to the
equation ``O = gain*log(1 + I)`` after scaling each pixel to the range
0 to 1. For inverse logarithmic correction, the equation is
``O = gain*(2**I - 1)``.
Parameters
----------
image : ndarray
Input image.
gain : float, optional
The constant multiplier. Default value is 1.
inv : float, optional
If True, it performs inverse logarithmic correction,
else correction will be logarithmic. Defaults to False.
Returns
-------
out : ndarray
Logarithm corrected output image.
See Also
--------
adjust_gamma
References
----------
.. [1] http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf
adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False)
Performs Sigmoid Correction on the input image.
Also known as Contrast Adjustment.
This function transforms the input image pixelwise according to the
equation ``O = 1/(1 + exp*(gain*(cutoff - I)))`` after scaling each pixel
to the range 0 to 1.
Parameters
----------
image : ndarray
Input image.
cutoff : float, optional
Cutoff of the sigmoid function that shifts the characteristic curve
in horizontal direction. Default value is 0.5.
gain : float, optional
The constant multiplier in exponential's power of sigmoid function.
Default value is 10.
inv : bool, optional
If True, returns the negative sigmoid correction. Defaults to False.
Returns
-------
out : ndarray
Sigmoid corrected output image.
See Also
--------
adjust_gamma
References
----------
.. [1] Gustav J. Braun, "Image Lightness Rescaling Using Sigmoidal Contrast
Enhancement Functions",
http://markfairchild.org/PDFs/PAP07.pdf
cumulative_distribution(image, nbins=256)
Return cumulative distribution function (cdf) for the given image.
Parameters
----------
image : array
Image array.
nbins : int, optional
Number of bins for image histogram.
Returns
-------
img_cdf : array
Values of cumulative distribution function.
bin_centers : array
Centers of bins.
See Also
--------
histogram
References
----------
.. [1] https://en.wikipedia.org/wiki/Cumulative_distribution_function
Examples
--------
>>> from skimage import data, exposure, img_as_float
>>> image = img_as_float(data.camera())
>>> hi = exposure.histogram(image)
>>> cdf = exposure.cumulative_distribution(image)
>>> all(cdf[0] == np.cumsum(hi[0])/float(image.size))
True
equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256)
Contrast Limited Adaptive Histogram Equalization (CLAHE).
An algorithm for local contrast enhancement, that uses histograms computed
over different tile regions of the image. Local details can therefore be
enhanced even in regions that are darker or lighter than most of the image.
Parameters
----------
image : (M[, ...][, C]) ndarray
Input image.
kernel_size : int or array_like, optional
Defines the shape of contextual regions used in the algorithm. If
iterable is passed, it must have the same number of elements as
``image.ndim`` (without color channel). If integer, it is broadcasted
to each `image` dimension. By default, ``kernel_size`` is 1/8 of
``image`` height by 1/8 of its width.
clip_limit : float, optional
Clipping limit, normalized between 0 and 1 (higher values give more
contrast).
nbins : int, optional
Number of gray bins for histogram ("data range").
Returns
-------
out : (M[, ...][, C]) ndarray
Equalized image with float64 dtype.
See Also
--------
equalize_hist, rescale_intensity
Notes
-----
* For color images, the following steps are performed:
- The image is converted to HSV color space
- The CLAHE algorithm is run on the V (Value) channel
- The image is converted back to RGB space and returned
* For RGBA images, the original alpha channel is removed.
.. versionchanged:: 0.17
The values returned by this function are slightly shifted upwards
because of an internal change in rounding behavior.
References
----------
.. [1] http://tog.acm.org/resources/GraphicsGems/
.. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE
equalize_hist(image, nbins=256, mask=None)
Return image after histogram equalization.
Parameters
----------
image : array
Image array.
nbins : int, optional
Number of bins for image histogram. Note: this argument is
ignored for integer images, for which each integer is its own
bin.
mask : ndarray of bools or 0s and 1s, optional
Array of same shape as `image`. Only points at which mask == True
are used for the equalization, which is applied to the whole image.
Returns
-------
out : float array
Image array after histogram equalization.
Notes
-----
This function is adapted from [1]_ with the author's permission.
References
----------
.. [1] http://www.janeriksolem.net/histogram-equalization-with-python-and.html
.. [2] https://en.wikipedia.org/wiki/Histogram_equalization
histogram(image, nbins=256, source_range='image', normalize=False, *, channel_axis=None)
Return histogram of image.
Unlike `numpy.histogram`, this function returns the centers of bins and
does not rebin integer arrays. For integer arrays, each integer value has
its own bin, which improves speed and intensity-resolution.
If `channel_axis` is not set, the histogram is computed on the flattened
image. For color or multichannel images, set ``channel_axis`` to use a
common binning for all channels. Alternatively, one may apply the function
separately on each channel to obtain a histogram for each color channel
with separate binning.
Parameters
----------
image : array
Input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
source_range : string, optional
'image' (default) determines the range from the input image.
'dtype' determines the range from the expected range of the images
of that data type.
normalize : bool, optional
If True, normalize the histogram by the sum of its values.
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.
Returns
-------
hist : array
The values of the histogram. When ``channel_axis`` is not None, hist
will be a 2D array where the first axis corresponds to channels.
bin_centers : array
The values at the center of the bins.
See Also
--------
cumulative_distribution
Examples
--------
>>> from skimage import data, exposure, img_as_float
>>> image = img_as_float(data.camera())
>>> np.histogram(image, bins=2)
(array([ 93585, 168559]), array([0. , 0.5, 1. ]))
>>> exposure.histogram(image, nbins=2)
(array([ 93585, 168559]), array([0.25, 0.75]))
is_low_contrast(image, fraction_threshold=0.05, lower_percentile=1, upper_percentile=99, method='linear')
Determine if an image is low contrast.
Parameters
----------
image : array-like
The image under test.
fraction_threshold : float, optional
The low contrast fraction threshold. An image is considered low-
contrast when its range of brightness spans less than this
fraction of its data type's full range. [1]_
lower_percentile : float, optional
Disregard values below this percentile when computing image contrast.
upper_percentile : float, optional
Disregard values above this percentile when computing image contrast.
method : str, optional
The contrast determination method. Right now the only available
option is "linear".
Returns
-------
out : bool
True when the image is determined to be low contrast.
Notes
-----
For boolean images, this function returns False only if all values are
the same (the method, threshold, and percentile arguments are ignored).
References
----------
.. [1] https://scikit-image.org/docs/dev/user_guide/data_types.html
Examples
--------
>>> image = np.linspace(0, 0.04, 100)
>>> is_low_contrast(image)
True
>>> image[-1] = 1
>>> is_low_contrast(image)
True
>>> is_low_contrast(image, upper_percentile=100)
False
match_histograms(image, reference, *, channel_axis=None)
Adjust an image so that its cumulative histogram matches that of another.
The adjustment is applied separately for each channel.
Parameters
----------
image : ndarray
Input image. Can be gray-scale or in color.
reference : ndarray
Image to match histogram of. Must have the same number of channels as
image.
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.
Returns
-------
matched : ndarray
Transformed input image.
Raises
------
ValueError
Thrown when the number of channels in the input image and the reference
differ.
References
----------
.. [1] http://paulbourke.net/miscellaneous/equalisation/
rescale_intensity(image, in_range='image', out_range='dtype')
Return image after stretching or shrinking its intensity levels.
The desired intensity range of the input and output, `in_range` and
`out_range` respectively, are used to stretch or shrink the intensity range
of the input image. See examples below.
Parameters
----------
image : array
Image array.
in_range, out_range : str or 2-tuple, optional
Min and max intensity values of input and output image.
The possible values for this parameter are enumerated below.
'image'
Use image min/max as the intensity range.
'dtype'
Use min/max of the image's dtype as the intensity range.
dtype-name
Use intensity range based on desired `dtype`. Must be valid key
in `DTYPE_RANGE`.
2-tuple
Use `range_values` as explicit min/max intensities.
Returns
-------
out : array
Image array after rescaling its intensity. This image is the same dtype
as the input image.
Notes
-----
.. versionchanged:: 0.17
The dtype of the output array has changed to match the input dtype, or
float if the output range is specified by a pair of values.
See Also
--------
equalize_hist
Examples
--------
By default, the min/max intensities of the input image are stretched to
the limits allowed by the image's dtype, since `in_range` defaults to
'image' and `out_range` defaults to 'dtype':
>>> image = np.array([51, 102, 153], dtype=np.uint8)
>>> rescale_intensity(image)
array([ 0, 127, 255], dtype=uint8)
It's easy to accidentally convert an image dtype from uint8 to float:
>>> 1.0 * image
array([ 51., 102., 153.])
Use `rescale_intensity` to rescale to the proper range for float dtypes:
>>> image_float = 1.0 * image
>>> rescale_intensity(image_float)
array([0. , 0.5, 1. ])
To maintain the low contrast of the original, use the `in_range` parameter:
>>> rescale_intensity(image_float, in_range=(0, 255))
array([0.2, 0.4, 0.6])
If the min/max value of `in_range` is more/less than the min/max image
intensity, then the intensity levels are clipped:
>>> rescale_intensity(image_float, in_range=(0, 102))
array([0.5, 1. , 1. ])
If you have an image with signed integers but want to rescale the image to
just the positive range, use the `out_range` parameter. In that case, the
output dtype will be float:
>>> image = np.array([-10, 0, 10], dtype=np.int8)
>>> rescale_intensity(image, out_range=(0, 127))
array([ 0. , 63.5, 127. ])
To get the desired range with a specific dtype, use ``.astype()``:
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8)
array([ 0, 63, 127], dtype=int8)
If the input image is constant, the output will be clipped directly to the
output range:
>>> image = np.array([130, 130, 130], dtype=np.int32)
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32)
array([127, 127, 127], dtype=int32)
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\exposure\__init__.py
scikit-image.feature
Python Library Documentation: package skimage.feature in skimage
NAME
skimage.feature - Feature detection and extraction, e.g., texture analysis, corners, etc.
PACKAGE CONTENTS
_basic_features
_canny
_canny_cy
_cascade
_daisy
_fisher_vector
_haar
_hessian_det_appx
_hog
_hoghistogram
_orb_descriptor_positions
_sift
_texture
blob
brief
brief_cy
censure
censure_cy
corner
corner_cy
haar
match
orb
orb_cy
peak
sift
template
tests (package)
texture
util
CLASSES
builtins.object
skimage.feature._cascade.Cascade
skimage.feature.util.DescriptorExtractor(builtins.object)
skimage.feature.brief.BRIEF
skimage.feature.orb.ORB(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
skimage.feature.sift.SIFT(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
skimage.feature.util.FeatureDetector(builtins.object)
skimage.feature.censure.CENSURE
skimage.feature.orb.ORB(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
skimage.feature.sift.SIFT(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
class BRIEF(skimage.feature.util.DescriptorExtractor)
| BRIEF(descriptor_size=256, patch_size=49, mode='normal', sigma=1, rng=1)
|
| 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]])
|
| Method resolution order:
| BRIEF
| skimage.feature.util.DescriptorExtractor
| builtins.object
|
| Methods defined here:
|
| __init__(self, descriptor_size=256, patch_size=49, mode='normal', sigma=1, rng=1)
| Initialize self. See help(type(self)) for accurate signature.
|
| 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)``.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from skimage.feature.util.DescriptorExtractor:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class CENSURE(skimage.feature.util.FeatureDetector)
| CENSURE(min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)
|
| 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])
|
| Method resolution order:
| CENSURE
| skimage.feature.util.FeatureDetector
| builtins.object
|
| Methods defined here:
|
| __init__(self, min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)
| Initialize self. See help(type(self)) for accurate signature.
|
| detect(self, image)
| Detect CENSURE keypoints along with the corresponding scale.
|
| Parameters
| ----------
| image : 2D ndarray
| Input image.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from skimage.feature.util.FeatureDetector:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Cascade(builtins.object)
| Class for cascade of classifiers that is used for object detection.
|
| The main idea behind cascade of classifiers is to create classifiers
| of medium accuracy and ensemble them into one strong classifier
| instead of just creating a strong one. The second advantage of cascade
| classifier is that easy examples can be classified only by evaluating
| some of the classifiers in the cascade, making the process much faster
| than the process of evaluating a one strong classifier.
|
| Attributes
| ----------
| eps : cnp.float32_t
| Accuracy parameter. Increasing it, makes the classifier detect less
| false positives but at the same time the false negative score increases.
| stages_number : Py_ssize_t
| Amount of stages in a cascade. Each cascade consists of stumps i.e.
| trained features.
| stumps_number : Py_ssize_t
| The overall amount of stumps in all the stages of cascade.
| features_number : Py_ssize_t
| The overall amount of different features used by cascade.
| Two stumps can use the same features but has different trained
| values.
| window_width : Py_ssize_t
| The width of a detection window that is used. Objects smaller than
| this window can't be detected.
| window_height : Py_ssize_t
| The height of a detection window.
| stages : Stage*
| A pointer to the C array that stores stages information using a
| Stage struct.
| features : MBLBP*
| A pointer to the C array that stores MBLBP features using an MBLBP
| struct.
| LUTs : cnp.uint32_t*
| A pointer to the C array with look-up tables that are used by trained
| MBLBP features (MBLBPStumps) to evaluate a particular region.
|
| Notes
| -----
| The cascade approach was first described by Viola and Jones [1]_, [2]_,
| although these initial publications used a set of Haar-like features. This
| implementation instead uses multi-scale block local binary pattern (MB-LBP)
| features [3]_.
|
| References
| ----------
| .. [1] Viola, P. and Jones, M. "Rapid object detection using a boosted
| cascade of simple features," In: Proceedings of the 2001 IEEE
| Computer Society Conference on Computer Vision and Pattern
| Recognition. CVPR 2001, pp. I-I.
| :DOI:`10.1109/CVPR.2001.990517`
| .. [2] Viola, P. and Jones, M.J, "Robust Real-Time Face Detection",
| International Journal of Computer Vision 57, 137–154 (2004).
| :DOI:`10.1023/B:VISI.0000013087.49260.fb`
| .. [3] Liao, S. et al. Learning Multi-scale Block Local Binary Patterns for
| Face Recognition. International Conference on Biometrics (ICB),
| 2007, pp. 828-837. In: Lecture Notes in Computer Science, vol 4642.
| Springer, Berlin, Heidelberg.
| :DOI:`10.1007/978-3-540-74549-5_87`
|
| Methods defined here:
|
| __init__(...)
| Initialize cascade classifier.
|
| Parameters
| ----------
| xml_file : file's path or file's object
| A file in a OpenCv format from which all the cascade classifier's
| parameters are loaded.
| eps : cnp.float32_t
| Accuracy parameter. Increasing it, makes the classifier
| detect less false positives but at the same time the false
| negative score increases.
|
| __reduce__ = __reduce_cython__(...)
|
| __setstate__ = __setstate_cython__(...)
|
| detect_multi_scale(self, img, scale_factor, step_ratio, min_size, max_size, min_neighbor_number=4, intersection_score_threshold=0.5)
| Search for the object on multiple scales of input image.
|
| The function takes the input image, the scale factor by which the
| searching window is multiplied on each step, minimum window size
| and maximum window size that specify the interval for the search
| windows that are applied to the input image to detect objects.
|
| Parameters
| ----------
| img : 2-D or 3-D ndarray
| Ndarray that represents the input image.
| scale_factor : cnp.float32_t
| The scale by which searching window is multiplied on each step.
| step_ratio : cnp.float32_t
| The ratio by which the search step in multiplied on each scale
| of the image. 1 represents the exaustive search and usually is
| slow. By setting this parameter to higher values the results will
| be worse but the computation will be much faster. Usually, values
| in the interval [1, 1.5] give good results.
| min_size : tuple (int, int)
| Minimum size of the search window.
| max_size : tuple (int, int)
| Maximum size of the search window.
| min_neighbor_number : int
| Minimum amount of intersecting detections in order for detection
| to be approved by the function.
| intersection_score_threshold : cnp.float32_t
| The minimum value of value of ratio
| (intersection area) / (small rectangle ratio) in order to merge
| two detections into one.
|
| Returns
| -------
| output : list of dicts
| Dict have form {'r': int, 'c': int, 'width': int, 'height': int},
| where 'r' represents row position of top left corner of detected
| window, 'c' - col position, 'width' - width of detected window,
| 'height' - height of detected window.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| eps
|
| features_number
|
| stages_number
|
| stumps_number
|
| window_height
|
| window_width
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
class ORB(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
| ORB(downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)
|
| 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.]])
|
| Method resolution order:
| ORB
| skimage.feature.util.FeatureDetector
| skimage.feature.util.DescriptorExtractor
| builtins.object
|
| Methods defined here:
|
| __init__(self, downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)
| Initialize self. See help(type(self)) for accurate signature.
|
| detect(self, image)
| Detect oriented FAST keypoints along with the corresponding scale.
|
| Parameters
| ----------
| image : 2D array
| Input image.
|
| 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.
|
| 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.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from skimage.feature.util.FeatureDetector:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class SIFT(skimage.feature.util.FeatureDetector, skimage.feature.util.DescriptorExtractor)
| SIFT(upsampling=2, n_octaves=8, n_scales=3, sigma_min=1.6, sigma_in=0.5, c_dog=0.013333333333333334, c_edge=10, n_bins=36, lambda_ori=1.5, c_max=0.8, lambda_descr=6, n_hist=4, n_ori=8)
|
| 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]])
|
| Method resolution order:
| SIFT
| skimage.feature.util.FeatureDetector
| skimage.feature.util.DescriptorExtractor
| builtins.object
|
| Methods defined here:
|
| __init__(self, upsampling=2, n_octaves=8, n_scales=3, sigma_min=1.6, sigma_in=0.5, c_dog=0.013333333333333334, c_edge=10, n_bins=36, lambda_ori=1.5, c_max=0.8, lambda_descr=6, n_hist=4, n_ori=8)
| Initialize self. See help(type(self)) for accurate signature.
|
| detect(self, image)
| Detect the keypoints.
|
| Parameters
| ----------
| image : 2D array
| Input image.
|
| detect_and_extract(self, image)
| Detect the keypoints and extract their descriptors.
|
| Parameters
| ----------
| image : 2D array
| Input image.
|
| extract(self, image)
| Extract the descriptors for all keypoints in the image.
|
| Parameters
| ----------
| image : 2D array
| Input image.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| deltas
| The sampling distances of all octaves
|
| ----------------------------------------------------------------------
| Data descriptors inherited from skimage.feature.util.FeatureDetector:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
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)
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
The minimum standard deviation for Gaussian kernel. Keep this low to
detect smaller blobs. 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.
max_sigma : scalar or sequence of scalars, optional
The maximum standard deviation for Gaussian kernel. Keep this high to
detect larger blobs. 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.
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.
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 low to detect smaller blobs.
max_sigma : float, optional
The maximum standard deviation for Gaussian Kernel used to compute
Hessian matrix. Keep this high to detect larger blobs.
num_sigma : int, optional
The number of intermediate values of standard deviations to consider
between `min_sigma` and `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.
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)
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
the minimum standard deviation for Gaussian kernel. Keep this low to
detect smaller blobs. 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.
max_sigma : scalar or sequence of scalars, optional
The maximum standard deviation for Gaussian kernel. Keep this high to
detect larger blobs. 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.
num_sigma : int, optional
The number of intermediate values of standard deviations to consider
between `min_sigma` and `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.
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)
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]])
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]])
corner_harris(image, method='k', k=0.05, eps=1e-06, 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]])
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`
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]])
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.])
corner_peaks(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, indices=True, num_peaks=inf, footprint=None, labels=None, *, num_peaks_per_label=inf, p_norm=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]])
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]])
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]])
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
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. ]],
<BLANKLINE>
[[0.5, 0. , 0. ],
[0. , 0.5, 0. ]]])
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`
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
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('sklearn')
>>> 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)
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)
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 ]])
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`
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)
hessian_matrix(image, sigma=1, mode='constant', cval=0, order='rc', use_gaussian_derivatives=None)
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 : boolean, 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.]])
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.
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.]])
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.
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
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('sklearn')
>>> 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)
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`
match_descriptors(descriptors1, descriptors2, metric=None, p=2, max_distance=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.
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]])
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`
multiscale_basic_features(image, intensity=True, edges=True, texture=True, sigma_min=0.5, sigma_max=16, num_sigma=None, num_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.
num_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``)
peak_local_max(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, num_peaks=inf, footprint=None, labels=None, num_peaks_per_label=inf, p_norm=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]])
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`.
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]])
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
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
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\feature\__init__.py
scikit-image.filters
Python Library Documentation: package skimage.filters in skimage
NAME
skimage.filters - Sharpening, edge finding, rank filters, thresholding, etc.
PACKAGE CONTENTS
_fft_based
_gabor
_gaussian
_median
_multiotsu
_rank_order
_sparse
_unsharp_mask
_window
edges
lpi_filter
rank (package)
ridges
tests (package)
thresholding
CLASSES
builtins.object
skimage.filters.lpi_filter.LPIFilter2D
class LPIFilter2D(builtins.object)
| LPIFilter2D(impulse_response, **filter_params)
|
| Linear Position-Invariant Filter (2-dimensional)
|
| Methods defined here:
|
| __call__(self, data)
| Apply the filter to the given data.
|
| Parameters
| ----------
| data : (M, N) ndarray
|
| __init__(self, impulse_response, **filter_params)
| Parameters
| ----------
| impulse_response : callable `f(r, c, **filter_params)`
| Function that yields the impulse response. ``r`` and ``c`` are
| 1-dimensional vectors that represent row and column positions, in
| other words coordinates are (r[0],c[0]),(r[0],c[1]) etc.
| `**filter_params` are passed through.
|
| In other words, ``impulse_response`` would be called like this:
|
| >>> def impulse_response(r, c, **filter_params):
| ... pass
| >>>
| >>> r = [0,0,0,1,1,1,2,2,2]
| >>> c = [0,1,2,0,1,2,0,1,2]
| >>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3}
| >>> impulse_response(r, c, **filter_params)
|
|
| Examples
| --------
| Gaussian filter without normalization of coefficients:
|
| >>> def filt_func(r, c, sigma=1):
| ... return np.exp(-(r**2 + c**2)/(2 * sigma**2))
| >>> filter = LPIFilter2D(filt_func)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
apply_hysteresis_threshold(image, low, high)
Apply hysteresis thresholding to ``image``.
This algorithm finds regions where ``image`` is greater than ``high``
OR ``image`` is greater than ``low`` *and* that region is connected to
a region greater than ``high``.
Parameters
----------
image : (M[, ...]) ndarray
Grayscale input image.
low : float, or array of same shape as ``image``
Lower threshold.
high : float, or array of same shape as ``image``
Higher threshold.
Returns
-------
thresholded : (M[, ...]) array of bool
Array in which ``True`` indicates the locations where ``image``
was above the hysteresis threshold.
Examples
--------
>>> image = np.array([1, 2, 3, 2, 1, 2, 1, 3, 2])
>>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int)
array([0, 1, 1, 1, 0, 0, 0, 1, 1])
References
----------
.. [1] J. Canny. A computational approach to edge detection.
IEEE Transactions on Pattern Analysis and Machine Intelligence.
1986; vol. 8, pp.679-698.
:DOI:`10.1109/TPAMI.1986.4767851`
butterworth(image, cutoff_frequency_ratio=0.005, high_pass=True, order=2.0, channel_axis=None, *, squared_butterworth=True, npad=0)
Apply a Butterworth filter to enhance high or low frequency features.
This filter is defined in the Fourier domain.
Parameters
----------
image : (M[, N[, ..., P]][, C]) ndarray
Input image.
cutoff_frequency_ratio : float, optional
Determines the position of the cut-off relative to the shape of the
FFT. Receives a value between [0, 0.5].
high_pass : bool, optional
Whether to perform a high pass filter. If False, a low pass filter is
performed.
order : float, optional
Order of the filter which affects the slope near the cut-off. Higher
order means steeper slope in frequency space.
channel_axis : int, optional
If there is a channel dimension, provide the index here. If None
(default) then all axes are assumed to be spatial dimensions.
squared_butterworth : bool, optional
When True, the square of a Butterworth filter is used. See notes below
for more details.
npad : int, optional
Pad each edge of the image by `npad` pixels using `numpy.pad`'s
``mode='edge'`` extension.
Returns
-------
result : ndarray
The Butterworth-filtered image.
Notes
-----
A band-pass filter can be achieved by combining a high-pass and low-pass
filter. The user can increase `npad` if boundary artifacts are apparent.
The "Butterworth filter" used in image processing textbooks (e.g. [1]_,
[2]_) is often the square of the traditional Butterworth filters as
described by [3]_, [4]_. The squared version will be used here if
`squared_butterworth` is set to ``True``. The lowpass, squared Butterworth
filter is given by the following expression for the lowpass case:
.. math::
H_{low}(f) = \frac{1}{1 + \left(\frac{f}{c f_s}\right)^{2n}}
with the highpass case given by
.. math::
H_{hi}(f) = 1 - H_{low}(f)
where :math:`f=\sqrt{\sum_{d=0}^{\mathrm{ndim}} f_{d}^{2}}` is the
absolute value of the spatial frequency, :math:`f_s` is the sampling
frequency, :math:`c` the ``cutoff_frequency_ratio``, and :math:`n` is the
filter `order` [1]_. When ``squared_butterworth=False``, the square root of
the above expressions are used instead.
Note that ``cutoff_frequency_ratio`` is defined in terms of the sampling
frequency, :math:`f_s`. The FFT spectrum covers the Nyquist range
(:math:`[-f_s/2, f_s/2]`) so ``cutoff_frequency_ratio`` should have a value
between 0 and 0.5. The frequency response (gain) at the cutoff is 0.5 when
``squared_butterworth`` is true and :math:`1/\sqrt{2}` when it is false.
Examples
--------
Apply a high-pass and low-pass Butterworth filter to a grayscale and
color image respectively:
>>> from skimage.data import camera, astronaut
>>> from skimage.filters import butterworth
>>> high_pass = butterworth(camera(), 0.07, True, 8)
>>> low_pass = butterworth(astronaut(), 0.01, False, 4, channel_axis=-1)
References
----------
.. [1] Russ, John C., et al. The Image Processing Handbook, 3rd. Ed.
1999, CRC Press, LLC.
.. [2] Birchfield, Stan. Image Processing and Analysis. 2018. Cengage
Learning.
.. [3] Butterworth, Stephen. "On the theory of filter amplifiers."
Wireless Engineer 7.6 (1930): 536-541.
.. [4] https://en.wikipedia.org/wiki/Butterworth_filter
correlate_sparse(image, kernel, mode='reflect')
Compute valid cross-correlation of `padded_array` and `kernel`.
This function is *fast* when `kernel` is large with many zeros.
See ``scipy.ndimage.correlate`` for a description of cross-correlation.
Parameters
----------
image : ndarray, dtype float, shape (M, N[, ...], P)
The input array. If mode is 'valid', this array should already be
padded, as a margin of the same shape as kernel will be stripped
off.
kernel : ndarray, dtype float, shape (Q, R[, ...], S)
The kernel to be correlated. Must have the same number of
dimensions as `padded_array`. For high performance, it should
be sparse (few nonzero entries).
mode : string, optional
See `scipy.ndimage.correlate` for valid modes.
Additionally, mode 'valid' is accepted, in which case no padding is
applied and the result is the result for the smaller image for which
the kernel is entirely inside the original data.
Returns
-------
result : array of float, shape (M, N[, ...], P)
The result of cross-correlating `image` with `kernel`. If mode
'valid' is used, the resulting shape is (M-Q+1, N-R+1[, ...], P-S+1).
difference_of_gaussians(image, low_sigma, high_sigma=None, *, mode='nearest', cval=0, channel_axis=None, truncate=4.0)
Find features between ``low_sigma`` and ``high_sigma`` in size.
This function uses the Difference of Gaussians method for applying
band-pass filters to multi-dimensional arrays. The input array is
blurred with two Gaussian kernels of differing sigmas to produce two
intermediate, filtered images. The more-blurred image is then subtracted
from the less-blurred image. The final output image will therefore have
had high-frequency components attenuated by the smaller-sigma Gaussian, and
low frequency components will have been removed due to their presence in
the more-blurred intermediate.
Parameters
----------
image : ndarray
Input array to filter.
low_sigma : scalar or sequence of scalars
Standard deviation(s) for the Gaussian kernel with the smaller sigmas
across all axes. The standard deviations are given for each axis as a
sequence, or as a single number, in which case the single number is
used as the standard deviation value for all axes.
high_sigma : scalar or sequence of scalars, optional (default is None)
Standard deviation(s) for the Gaussian kernel with the larger sigmas
across all axes. The standard deviations are given for each axis as a
sequence, or as a single number, in which case the single number is
used as the standard deviation value for all axes. If None is given
(default), sigmas for all axes are calculated as 1.6 * low_sigma.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'nearest'.
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
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.
truncate : float, optional (default is 4.0)
Truncate the filter at this many standard deviations.
Returns
-------
filtered_image : ndarray
the filtered array.
See also
--------
skimage.feature.blob_dog
Notes
-----
This function will subtract an array filtered with a Gaussian kernel
with sigmas given by ``high_sigma`` from an array filtered with a
Gaussian kernel with sigmas provided by ``low_sigma``. The values for
``high_sigma`` must always be greater than or equal to the corresponding
values in ``low_sigma``, or a ``ValueError`` will be raised.
When ``high_sigma`` is none, the values for ``high_sigma`` will be
calculated as 1.6x the corresponding values in ``low_sigma``. This ratio
was originally proposed by Marr and Hildreth (1980) [1]_ and is commonly
used when approximating the inverted Laplacian of Gaussian, which is used
in edge and blob detection.
Input image is converted according to the conventions of ``img_as_float``.
Except for sigma values, all parameters are used for both filters.
Examples
--------
Apply a simple Difference of Gaussians filter to a color image:
>>> from skimage.data import astronaut
>>> from skimage.filters import difference_of_gaussians
>>> filtered_image = difference_of_gaussians(astronaut(), 2, 10,
... channel_axis=-1)
Apply a Laplacian of Gaussian filter as approximated by the Difference
of Gaussians filter:
>>> filtered_image = difference_of_gaussians(astronaut(), 2,
... channel_axis=-1)
Apply a Difference of Gaussians filter to a grayscale image using different
sigma values for each axis:
>>> from skimage.data import camera
>>> filtered_image = difference_of_gaussians(camera(), (2,5), (3,20))
References
----------
.. [1] Marr, D. and Hildreth, E. Theory of Edge Detection. Proc. R. Soc.
Lond. Series B 207, 187-217 (1980).
https://doi.org/10.1098/rspb.1980.0020
farid(image, mask=None, *, axis=None, mode='reflect', cval=0.0)
Find the edge magnitude using the Farid transform.
Parameters
----------
image : array
The input image.
mask : array of bool, optional
Clip the output image to this mask. (Values where mask=0 will be set
to 0.)
axis : int or sequence of int, optional
Compute the edge filter along this axis. If not provided, the edge
magnitude is computed. This is defined as::
farid_mag = np.sqrt(sum([farid(image, axis=i)**2
for i in range(image.ndim)]) / image.ndim)
The magnitude is also computed if axis is a sequence.
mode : str or sequence of str, optional
The boundary mode for the convolution. See `scipy.ndimage.convolve`
for a description of the modes. This can be either a single boundary
mode or one boundary mode per axis.
cval : float, optional
When `mode` is ``'constant'``, this is the constant used in values
outside the boundary of the image data.
Returns
-------
output : array of float
The Farid edge map.
See also
--------
farid_h, farid_v : horizontal and vertical edge detection.
scharr, sobel, prewitt, skimage.feature.canny
Notes
-----
Take the square root of the sum of the squares of the horizontal and
vertical derivatives to get a magnitude that is somewhat insensitive to
direction. Similar to the Scharr operator, this operator is designed with
a rotation invariance constraint.
References
----------
.. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete
multidimensional signals", IEEE Transactions on Image Processing
13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819`
.. [2] Wikipedia, "Farid and Simoncelli Derivatives." Available at:
<https://en.wikipedia.org/wiki/Image_derivatives#Farid_and_Simoncelli_Derivatives>
Examples
--------
>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.farid(camera)
farid_h(image, *, mask=None)
Find the horizontal edges of an image using the Farid transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Farid edge map.
Notes
-----
The kernel was constructed using the 5-tap weights from [1].
References
----------
.. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete
multidimensional signals", IEEE Transactions on Image Processing
13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819`
.. [2] Farid, H. and Simoncelli, E. P. "Optimally rotation-equivariant
directional derivative kernels", In: 7th International Conference on
Computer Analysis of Images and Patterns, Kiel, Germany. Sep, 1997.
farid_v(image, *, mask=None)
Find the vertical edges of an image using the Farid transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Farid edge map.
Notes
-----
The kernel was constructed using the 5-tap weights from [1].
References
----------
.. [1] Farid, H. and Simoncelli, E. P., "Differentiation of discrete
multidimensional signals", IEEE Transactions on Image Processing
13(4): 496-508, 2004. :DOI:`10.1109/TIP.2004.823819`
filter_forward(data, impulse_response=None, filter_params=None, predefined_filter=None)
Apply the given filter to data.
Parameters
----------
data : (M, N) ndarray
Input data.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See LPIFilter2D.__init__.
filter_params : dict, optional
Additional keyword parameters to the impulse_response function.
Other Parameters
----------------
predefined_filter : LPIFilter2D
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
Examples
--------
Gaussian filter without normalization:
>>> def filt_func(r, c, sigma=1):
... return np.exp(-(r**2 + c**2)/(2 * sigma**2))
>>>
>>> from skimage import data
>>> filtered = filter_forward(data.coins(), filt_func)
filter_inverse(data, impulse_response=None, filter_params=None, max_gain=2, predefined_filter=None)
Apply the filter in reverse to the given data.
Parameters
----------
data : (M, N) ndarray
Input data.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See :class:`~.LPIFilter2D`. This is a required
argument unless a `predifined_filter` is provided.
filter_params : dict, optional
Additional keyword parameters to the impulse_response function.
max_gain : float, optional
Limit the filter gain. Often, the filter contains zeros, which would
cause the inverse filter to have infinite gain. High gain causes
amplification of artefacts, so a conservative limit is recommended.
Other Parameters
----------------
predefined_filter : LPIFilter2D, optional
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
frangi(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=None, black_ridges=True, mode='reflect', cval=0)
Filter an image with the Frangi vesselness filter.
This filter can be used to detect continuous ridges, e.g. vessels,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Defined only for 2-D and 3-D images. Calculates the eigenvalues of the
Hessian to compute the similarity of an image region to vessels, according
to the method described in [1]_.
Parameters
----------
image : (M, N[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter, i.e.,
np.arange(scale_range[0], scale_range[1], scale_step)
scale_range : 2-tuple of floats, optional
The range of sigmas used.
scale_step : float, optional
Step size between sigmas.
alpha : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a plate-like structure.
beta : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a blob-like structure.
gamma : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to areas of high variance/texture/structure.
The default, None, uses half of the maximum Hessian norm.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
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
-------
out : (M, N[, P]) ndarray
Filtered image (maximum of pixels across all scales).
Notes
-----
Earlier versions of this filter were implemented by Marc Schrijver,
(November 2001), D. J. Kroon, University of Twente (May 2009) [2]_, and
D. G. Ellis (January 2017) [3]_.
See also
--------
meijering
sato
hessian
References
----------
.. [1] Frangi, A. F., Niessen, W. J., Vincken, K. L., & Viergever, M. A.
(1998,). Multiscale vessel enhancement filtering. In International
Conference on Medical Image Computing and Computer-Assisted
Intervention (pp. 130-137). Springer Berlin Heidelberg.
:DOI:`10.1007/BFb0056195`
.. [2] Kroon, D. J.: Hessian based Frangi vesselness filter.
.. [3] Ellis, D. G.: https://github.com/ellisdg/frangi3d/tree/master/frangi
gabor(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)
Return real and imaginary responses to Gabor filter.
The real and imaginary parts of the Gabor filter kernel are applied to the
image and the response is returned as a pair of arrays.
Gabor filter is a linear filter with a Gaussian kernel which is modulated
by a sinusoidal plane wave. Frequency and orientation representations of
the Gabor filter are similar to those of the human visual system.
Gabor filter banks are commonly used in computer vision and image
processing. They are especially suitable for edge detection and texture
classification.
Parameters
----------
image : 2-D array
Input image.
frequency : float
Spatial frequency of the harmonic function. Specified in pixels.
theta : float, optional
Orientation in radians. If 0, the harmonic is in the x-direction.
bandwidth : float, optional
The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x``
and ``sigma_y`` will decrease with increasing frequency. This value is
ignored if ``sigma_x`` and ``sigma_y`` are set by the user.
sigma_x, sigma_y : float, optional
Standard deviation in x- and y-directions. These directions apply to
the kernel *before* rotation. If `theta = pi/2`, then the kernel is
rotated 90 degrees so that ``sigma_x`` controls the *vertical*
direction.
n_stds : scalar, optional
The linear size of the kernel is n_stds (3 by default) standard
deviations.
offset : float, optional
Phase offset of harmonic function in radians.
mode : {'constant', 'nearest', 'reflect', 'mirror', 'wrap'}, optional
Mode used to convolve image with a kernel, passed to `ndi.convolve`
cval : scalar, optional
Value to fill past edges of input if ``mode`` of convolution is
'constant'. The parameter is passed to `ndi.convolve`.
Returns
-------
real, imag : arrays
Filtered images using the real and imaginary parts of the Gabor filter
kernel. Images are of the same dimensions as the input one.
References
----------
.. [1] https://en.wikipedia.org/wiki/Gabor_filter
.. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf
Examples
--------
>>> from skimage.filters import gabor
>>> from skimage import data
>>> from matplotlib import pyplot as plt # doctest: +SKIP
>>> image = data.coins()
>>> # detecting edges in a coin image
>>> filt_real, filt_imag = gabor(image, frequency=0.6)
>>> fix, ax = plt.subplots() # doctest: +SKIP
>>> ax.imshow(filt_real) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
>>> # less sensitivity to finer details with the lower frequency kernel
>>> filt_real, filt_imag = gabor(image, frequency=0.1)
>>> fig, ax = plt.subplots() # doctest: +SKIP
>>> ax.imshow(filt_real) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, dtype=<class 'numpy.complex128'>)
Return complex 2D Gabor filter kernel.
Gabor kernel is a Gaussian kernel modulated by a complex harmonic function.
Harmonic function consists of an imaginary sine function and a real
cosine function. Spatial frequency is inversely proportional to the
wavelength of the harmonic and to the standard deviation of a Gaussian
kernel. The bandwidth is also inversely proportional to the standard
deviation.
Parameters
----------
frequency : float
Spatial frequency of the harmonic function. Specified in pixels.
theta : float, optional
Orientation in radians. If 0, the harmonic is in the x-direction.
bandwidth : float, optional
The bandwidth captured by the filter. For fixed bandwidth, ``sigma_x``
and ``sigma_y`` will decrease with increasing frequency. This value is
ignored if ``sigma_x`` and ``sigma_y`` are set by the user.
sigma_x, sigma_y : float, optional
Standard deviation in x- and y-directions. These directions apply to
the kernel *before* rotation. If `theta = pi/2`, then the kernel is
rotated 90 degrees so that ``sigma_x`` controls the *vertical*
direction.
n_stds : scalar, optional
The linear size of the kernel is n_stds (3 by default) standard
deviations
offset : float, optional
Phase offset of harmonic function in radians.
dtype : {np.complex64, np.complex128}
Specifies if the filter is single or double precision complex.
Returns
-------
g : complex array
Complex filter kernel.
References
----------
.. [1] https://en.wikipedia.org/wiki/Gabor_filter
.. [2] https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf
Examples
--------
>>> from skimage.filters import gabor_kernel
>>> from matplotlib import pyplot as plt # doctest: +SKIP
>>> gk = gabor_kernel(frequency=0.2)
>>> fig, ax = plt.subplots() # doctest: +SKIP
>>> ax.imshow(gk.real) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
>>> # more ripples (equivalent to increasing the size of the
>>> # Gaussian spread)
>>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1)
>>> fig, ax = plt.suplots() # doctest: +SKIP
>>> ax.imshow(gk.real) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
gaussian(image, sigma=1.0, *, mode='nearest', cval=0, preserve_range=False, truncate=4.0, channel_axis=None, out=None)
Multi-dimensional Gaussian filter.
Parameters
----------
image : ndarray
Input image (grayscale or color) to filter.
sigma : scalar or sequence of scalars, optional
Standard deviation for Gaussian kernel. The standard
deviations of the Gaussian filter are given for each axis as a
sequence, or as a single number, in which case it is equal for
all axes.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'nearest'.
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
preserve_range : bool, optional
If True, keep the original range of values. Otherwise, the input
``image`` is converted according to the conventions of ``img_as_float``
(Normalized first to values [-1.0 ; 1.0] or [0 ; 1.0] depending on
dtype of input)
For more information, see:
https://scikit-image.org/docs/dev/user_guide/data_types.html
truncate : float, optional
Truncate the filter at this many standard deviations.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
`channel_axis` was added in 0.19.
out : ndarray, optional
If given, the filtered image will be stored in this array.
.. versionadded:: 0.23
`out` was added in 0.23.
Returns
-------
filtered_image : ndarray
the filtered array
Notes
-----
This function is a wrapper around :func:`scipy.ndimage.gaussian_filter`.
Integer arrays are converted to float.
`out` should be of floating-point data type since `gaussian` converts the
input `image` to float. If `out` is not provided, another array
will be allocated and returned as the result.
The multi-dimensional filter is implemented as a sequence of
one-dimensional convolution filters. The intermediate arrays are
stored in the same data type as the output. Therefore, for output
types with a limited precision, the results may be imprecise
because intermediate results may be stored with insufficient
precision.
Examples
--------
>>> import skimage as ski
>>> a = np.zeros((3, 3))
>>> a[1, 1] = 1
>>> a
array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]])
>>> ski.filters.gaussian(a, sigma=0.4) # mild smoothing
array([[0.00163116, 0.03712502, 0.00163116],
[0.03712502, 0.84496158, 0.03712502],
[0.00163116, 0.03712502, 0.00163116]])
>>> ski.filters.gaussian(a, sigma=1) # more smoothing
array([[0.05855018, 0.09653293, 0.05855018],
[0.09653293, 0.15915589, 0.09653293],
[0.05855018, 0.09653293, 0.05855018]])
>>> # Several modes are possible for handling boundaries
>>> ski.filters.gaussian(a, sigma=1, mode='reflect')
array([[0.08767308, 0.12075024, 0.08767308],
[0.12075024, 0.16630671, 0.12075024],
[0.08767308, 0.12075024, 0.08767308]])
>>> # For RGB images, each is filtered separately
>>> image = ski.data.astronaut()
>>> filtered_img = ski.filters.gaussian(image, sigma=1, channel_axis=-1)
hessian(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode='reflect', cval=0)
Filter an image with the Hybrid Hessian filter.
This filter can be used to detect continuous edges, e.g. vessels,
wrinkles, rivers. It can be used to calculate the fraction of the whole
image containing such objects.
Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but
uses alternative method of smoothing. Refer to [1]_ to find the differences
between Frangi and Hessian filters.
Parameters
----------
image : (M, N[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter, i.e.,
np.arange(scale_range[0], scale_range[1], scale_step)
scale_range : 2-tuple of floats, optional
The range of sigmas used.
scale_step : float, optional
Step size between sigmas.
beta : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a blob-like structure.
gamma : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to areas of high variance/texture/structure.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
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
-------
out : (M, N[, P]) ndarray
Filtered image (maximum of pixels across all scales).
Notes
-----
Written by Marc Schrijver (November 2001)
Re-Written by D. J. Kroon University of Twente (May 2009) [2]_
See also
--------
meijering
sato
frangi
References
----------
.. [1] Ng, C. C., Yap, M. H., Costen, N., & Li, B. (2014,). Automatic
wrinkle detection using hybrid Hessian filter. In Asian Conference on
Computer Vision (pp. 609-622). Springer International Publishing.
:DOI:`10.1007/978-3-319-16811-1_40`
.. [2] Kroon, D. J.: Hessian based Frangi vesselness filter.
laplace(image, ksize=3, mask=None)
Find the edges of an image using the Laplace operator.
Parameters
----------
image : ndarray
Image to process.
ksize : int, optional
Define the size of the discrete Laplacian operator such that it
will have a size of (ksize,) * image.ndim.
mask : ndarray, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : ndarray
The Laplace edge map.
Notes
-----
The Laplacian operator is generated using the function
skimage.restoration.uft.laplacian().
median(image, footprint=None, out=None, mode='nearest', cval=0.0, behavior='ndimage')
Return local median of an image.
Parameters
----------
image : array-like
Input image.
footprint : ndarray, optional
If ``behavior=='rank'``, ``footprint`` is a 2-D array of 1's and 0's.
If ``behavior=='ndimage'``, ``footprint`` is a N-D array of 1's and 0's
with the same number of dimension than ``image``.
If None, ``footprint`` will be a N-D array with 3 elements for each
dimension (e.g., vector, square, cube, etc.)
out : ndarray, (same dtype as image), optional
If None, a new array is allocated.
mode : {'reflect', 'constant', 'nearest', 'mirror','‘wrap'}, optional
The mode parameter determines how the array borders are handled, where
``cval`` is the value when mode is equal to 'constant'.
Default is 'nearest'.
.. versionadded:: 0.15
``mode`` is used when ``behavior='ndimage'``.
cval : scalar, optional
Value to fill past edges of input if mode is 'constant'. Default is 0.0
.. versionadded:: 0.15
``cval`` was added in 0.15 is used when ``behavior='ndimage'``.
behavior : {'ndimage', 'rank'}, optional
Either to use the old behavior (i.e., < 0.15) or the new behavior.
The old behavior will call the :func:`skimage.filters.rank.median`.
The new behavior will call the :func:`scipy.ndimage.median_filter`.
Default is 'ndimage'.
.. versionadded:: 0.15
``behavior`` is introduced in 0.15
.. versionchanged:: 0.16
Default ``behavior`` has been changed from 'rank' to 'ndimage'
Returns
-------
out : 2-D array (same dtype as input image)
Output image.
See also
--------
skimage.filters.rank.median : Rank-based implementation of the median
filtering offering more flexibility with additional parameters but
dedicated for unsigned integer images.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters import median
>>> img = data.camera()
>>> med = median(img, disk(5))
meijering(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0)
Filter an image with the Meijering neuriteness filter.
This filter can be used to detect continuous ridges, e.g. neurites,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Calculates the eigenvalues of the Hessian to compute the similarity of
an image region to neurites, according to the method described in [1]_.
Parameters
----------
image : (M, N[, ...]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter
alpha : float, optional
Shaping filter constant, that selects maximally flat elongated
features. The default, None, selects the optimal value -1/(ndim+1).
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
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
-------
out : (M, N[, ...]) ndarray
Filtered image (maximum of pixels across all scales).
See also
--------
sato
frangi
hessian
References
----------
.. [1] Meijering, E., Jacob, M., Sarria, J. C., Steiner, P., Hirling, H.,
Unser, M. (2004). Design and validation of a tool for neurite tracing
and analysis in fluorescence microscopy images. Cytometry Part A,
58(2), 167-176.
:DOI:`10.1002/cyto.a.20022`
prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0)
Find the edge magnitude using the Prewitt transform.
Parameters
----------
image : array
The input image.
mask : array of bool, optional
Clip the output image to this mask. (Values where mask=0 will be set
to 0.)
axis : int or sequence of int, optional
Compute the edge filter along this axis. If not provided, the edge
magnitude is computed. This is defined as::
prw_mag = np.sqrt(sum([prewitt(image, axis=i)**2
for i in range(image.ndim)]) / image.ndim)
The magnitude is also computed if axis is a sequence.
mode : str or sequence of str, optional
The boundary mode for the convolution. See `scipy.ndimage.convolve`
for a description of the modes. This can be either a single boundary
mode or one boundary mode per axis.
cval : float, optional
When `mode` is ``'constant'``, this is the constant used in values
outside the boundary of the image data.
Returns
-------
output : array of float
The Prewitt edge map.
See also
--------
prewitt_h, prewitt_v : horizontal and vertical edge detection.
sobel, scharr, farid, skimage.feature.canny
Notes
-----
The edge magnitude depends slightly on edge directions, since the
approximation of the gradient operator by the Prewitt operator is not
completely rotation invariant. For a better rotation invariance, the Scharr
operator should be used. The Sobel operator has a better rotation
invariance than the Prewitt operator, but a worse rotation invariance than
the Scharr operator.
Examples
--------
>>> from skimage import data
>>> from skimage import filters
>>> camera = data.camera()
>>> edges = filters.prewitt(camera)
prewitt_h(image, mask=None)
Find the horizontal edges of an image using the Prewitt transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Prewitt edge map.
Notes
-----
We use the following kernel::
1/3 1/3 1/3
0 0 0
-1/3 -1/3 -1/3
prewitt_v(image, mask=None)
Find the vertical edges of an image using the Prewitt transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Prewitt edge map.
Notes
-----
We use the following kernel::
1/3 0 -1/3
1/3 0 -1/3
1/3 0 -1/3
rank_order(image)
Return an image of the same shape where each pixel is the
index of the pixel value in the ascending order of the unique
values of ``image``, aka the rank-order value.
Parameters
----------
image : ndarray
Returns
-------
labels : ndarray of unsigned integers, of shape image.shape
New array where each pixel has the rank-order value of the
corresponding pixel in ``image``. Pixel values are between 0 and
n - 1, where n is the number of distinct unique values in
``image``. The dtype of this array will be determined by
``np.min_scalar_type(image.size)``.
original_values : 1-D ndarray
Unique original values of ``image``. This will have the same dtype as
``image``.
Examples
--------
>>> a = np.array([[1, 4, 5], [4, 4, 1], [5, 1, 1]])
>>> a
array([[1, 4, 5],
[4, 4, 1],
[5, 1, 1]])
>>> rank_order(a)
(array([[0, 1, 2],
[1, 1, 0],
[2, 0, 0]], dtype=uint8), array([1, 4, 5]))
>>> b = np.array([-1., 2.5, 3.1, 2.5])
>>> rank_order(b)
(array([0, 1, 2, 1], dtype=uint8), array([-1. , 2.5, 3.1]))
roberts(image, mask=None)
Find the edge magnitude using Roberts' cross operator.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Roberts' Cross edge map.
See also
--------
roberts_pos_diag, roberts_neg_diag : diagonal edge detection.
sobel, scharr, prewitt, skimage.feature.canny
Examples
--------
>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.roberts(camera)
roberts_neg_diag(image, mask=None)
Find the cross edges of an image using the Roberts' Cross operator.
The kernel is applied to the input image to produce separate measurements
of the gradient component one orientation.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Robert's edge map.
Notes
-----
We use the following kernel::
0 1
-1 0
roberts_pos_diag(image, mask=None)
Find the cross edges of an image using Roberts' cross operator.
The kernel is applied to the input image to produce separate measurements
of the gradient component one orientation.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Robert's edge map.
Notes
-----
We use the following kernel::
1 0
0 -1
sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode='reflect', cval=0)
Filter an image with the Sato tubeness filter.
This filter can be used to detect continuous ridges, e.g. tubes,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Defined only for 2-D and 3-D images. Calculates the eigenvalues of the
Hessian to compute the similarity of an image region to tubes, according to
the method described in [1]_.
Parameters
----------
image : (M, N[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
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
-------
out : (M, N[, P]) ndarray
Filtered image (maximum of pixels across all scales).
See also
--------
meijering
frangi
hessian
References
----------
.. [1] Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S.,
Koller, T., ..., Kikinis, R. (1998). Three-dimensional multi-scale line
filter for segmentation and visualization of curvilinear structures in
medical images. Medical image analysis, 2(2), 143-168.
:DOI:`10.1016/S1361-8415(98)80009-1`
scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0)
Find the edge magnitude using the Scharr transform.
Parameters
----------
image : array
The input image.
mask : array of bool, optional
Clip the output image to this mask. (Values where mask=0 will be set
to 0.)
axis : int or sequence of int, optional
Compute the edge filter along this axis. If not provided, the edge
magnitude is computed. This is defined as::
sch_mag = np.sqrt(sum([scharr(image, axis=i)**2
for i in range(image.ndim)]) / image.ndim)
The magnitude is also computed if axis is a sequence.
mode : str or sequence of str, optional
The boundary mode for the convolution. See `scipy.ndimage.convolve`
for a description of the modes. This can be either a single boundary
mode or one boundary mode per axis.
cval : float, optional
When `mode` is ``'constant'``, this is the constant used in values
outside the boundary of the image data.
Returns
-------
output : array of float
The Scharr edge map.
See also
--------
scharr_h, scharr_v : horizontal and vertical edge detection.
sobel, prewitt, farid, skimage.feature.canny
Notes
-----
The Scharr operator has a better rotation invariance than
other edge filters such as the Sobel or the Prewitt operators.
References
----------
.. [1] D. Kroon, 2009, Short Paper University Twente, Numerical
Optimization of Kernel Based Image Derivatives.
.. [2] https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators
Examples
--------
>>> from skimage import data
>>> from skimage import filters
>>> camera = data.camera()
>>> edges = filters.scharr(camera)
scharr_h(image, mask=None)
Find the horizontal edges of an image using the Scharr transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Scharr edge map.
Notes
-----
We use the following kernel::
3 10 3
0 0 0
-3 -10 -3
References
----------
.. [1] D. Kroon, 2009, Short Paper University Twente, Numerical
Optimization of Kernel Based Image Derivatives.
scharr_v(image, mask=None)
Find the vertical edges of an image using the Scharr transform.
Parameters
----------
image : 2-D array
Image to process
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Scharr edge map.
Notes
-----
We use the following kernel::
3 0 -3
10 0 -10
3 0 -3
References
----------
.. [1] D. Kroon, 2009, Short Paper University Twente, Numerical
Optimization of Kernel Based Image Derivatives.
sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0)
Find edges in an image using the Sobel filter.
Parameters
----------
image : array
The input image.
mask : array of bool, optional
Clip the output image to this mask. (Values where mask=0 will be set
to 0.)
axis : int or sequence of int, optional
Compute the edge filter along this axis. If not provided, the edge
magnitude is computed. This is defined as::
sobel_mag = np.sqrt(sum([sobel(image, axis=i)**2
for i in range(image.ndim)]) / image.ndim)
The magnitude is also computed if axis is a sequence.
mode : str or sequence of str, optional
The boundary mode for the convolution. See `scipy.ndimage.convolve`
for a description of the modes. This can be either a single boundary
mode or one boundary mode per axis.
cval : float, optional
When `mode` is ``'constant'``, this is the constant used in values
outside the boundary of the image data.
Returns
-------
output : array of float
The Sobel edge map.
See also
--------
sobel_h, sobel_v : horizontal and vertical edge detection.
scharr, prewitt, farid, skimage.feature.canny
References
----------
.. [1] D. Kroon, 2009, Short Paper University Twente, Numerical
Optimization of Kernel Based Image Derivatives.
.. [2] https://en.wikipedia.org/wiki/Sobel_operator
Examples
--------
>>> from skimage import data
>>> from skimage import filters
>>> camera = data.camera()
>>> edges = filters.sobel(camera)
sobel_h(image, mask=None)
Find the horizontal edges of an image using the Sobel transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Sobel edge map.
Notes
-----
We use the following kernel::
1 2 1
0 0 0
-1 -2 -1
sobel_v(image, mask=None)
Find the vertical edges of an image using the Sobel transform.
Parameters
----------
image : 2-D array
Image to process.
mask : 2-D array, optional
An optional mask to limit the application to a certain area.
Note that pixels surrounding masked regions are also masked to
prevent masked regions from affecting the result.
Returns
-------
output : 2-D array
The Sobel edge map.
Notes
-----
We use the following kernel::
1 0 -1
2 0 -2
1 0 -1
threshold_isodata(image=None, nbins=256, return_all=False, *, hist=None)
Return threshold value(s) based on ISODATA method.
Histogram-based threshold, known as Ridler-Calvard method or inter-means.
Threshold values returned satisfy the following equality::
threshold = (image[image <= threshold].mean() +
image[image > threshold].mean()) / 2.0
That is, returned thresholds are intensities that separate the image into
two groups of pixels, where the threshold intensity is midway between the
mean intensities of these groups.
For integer images, the above equality holds to within one; for floating-
point images, the equality holds to within the histogram bin-width.
Either image or hist must be provided. In case hist is given, the actual
histogram of the image is ignored.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
return_all : bool, optional
If False (default), return only the lowest threshold that satisfies
the above equality. If True, return all valid thresholds.
hist : array, or 2-tuple of arrays, optional
Histogram to determine the threshold from and a corresponding array
of bin center intensities. Alternatively, only the histogram can be
passed.
Returns
-------
threshold : float or int or array
Threshold value(s).
References
----------
.. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an
iterative selection method"
IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,
:DOI:`10.1109/TSMC.1978.4310039`
.. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
Techniques and Quantitative Performance Evaluation" Journal of
Electronic Imaging, 13(1): 146-165,
http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
:DOI:`10.1117/1.1631315`
.. [3] ImageJ AutoThresholder code,
http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
--------
>>> from skimage.data import coins
>>> image = coins()
>>> thresh = threshold_isodata(image)
>>> binary = image > thresh
threshold_li(image, *, tolerance=None, initial_guess=None, iter_callback=None)
Compute threshold value by Li's iterative Minimum Cross Entropy method.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
tolerance : float, optional
Finish the computation when the change in the threshold in an iteration
is less than this value. By default, this is half the smallest
difference between intensity values in ``image``.
initial_guess : float or Callable[[array[float]], float], optional
Li's iterative method uses gradient descent to find the optimal
threshold. If the image intensity histogram contains more than two
modes (peaks), the gradient descent could get stuck in a local optimum.
An initial guess for the iteration can help the algorithm find the
globally-optimal threshold. A float value defines a specific start
point, while a callable should take in an array of image intensities
and return a float value. Example valid callables include
``numpy.mean`` (default), ``lambda arr: numpy.quantile(arr, 0.95)``,
or even :func:`skimage.filters.threshold_otsu`.
iter_callback : Callable[[float], Any], optional
A function that will be called on the threshold at every iteration of
the algorithm.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
References
----------
.. [1] Li C.H. and Lee C.K. (1993) "Minimum Cross Entropy Thresholding"
Pattern Recognition, 26(4): 617-625
:DOI:`10.1016/0031-3203(93)90115-D`
.. [2] Li C.H. and Tam P.K.S. (1998) "An Iterative Algorithm for Minimum
Cross Entropy Thresholding" Pattern Recognition Letters, 18(8): 771-776
:DOI:`10.1016/S0167-8655(98)00057-9`
.. [3] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
Techniques and Quantitative Performance Evaluation" Journal of
Electronic Imaging, 13(1): 146-165
:DOI:`10.1117/1.1631315`
.. [4] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_li(image)
>>> binary = image > thresh
threshold_local(image, block_size=3, method='gaussian', offset=0, mode='reflect', param=None, cval=0)
Compute a threshold mask image based on local pixel neighborhood.
Also known as adaptive or dynamic thresholding. The threshold value is
the weighted mean for the local neighborhood of a pixel subtracted by a
constant. Alternatively the threshold can be determined dynamically by a
given function, using the 'generic' method.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
block_size : int or sequence of int
Odd size of pixel neighborhood which is used to calculate the
threshold value (e.g. 3, 5, 7, ..., 21, ...).
method : {'generic', 'gaussian', 'mean', 'median'}, optional
Method used to determine adaptive threshold for local neighborhood in
weighted mean image.
* 'generic': use custom function (see ``param`` parameter)
* 'gaussian': apply gaussian filter (see ``param`` parameter for custom sigma value)
* 'mean': apply arithmetic mean filter
* 'median': apply median rank filter
By default, the 'gaussian' method is used.
offset : float, optional
Constant subtracted from weighted mean of neighborhood to calculate
the local threshold value. Default offset is 0.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
Default is 'reflect'.
param : {int, function}, optional
Either specify sigma for 'gaussian' method or function object for
'generic' method. This functions takes the flat array of local
neighborhood as a single argument and returns the calculated
threshold for the centre pixel.
cval : float, optional
Value to fill past edges of input if mode is 'constant'.
Returns
-------
threshold : (M, N[, ...]) ndarray
Threshold image. All pixels in the input image higher than the
corresponding pixel in the threshold image are considered foreground.
References
----------
.. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing
(2nd Edition)." Prentice-Hall Inc., 2002: 600--612.
ISBN: 0-201-18075-8
Examples
--------
>>> from skimage.data import camera
>>> image = camera()[:50, :50]
>>> binary_image1 = image > threshold_local(image, 15, 'mean')
>>> func = lambda arr: arr.mean()
>>> binary_image2 = image > threshold_local(image, 15, 'generic',
... param=func)
threshold_mean(image)
Return threshold value based on the mean of grayscale values.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
References
----------
.. [1] C. A. Glasbey, "An analysis of histogram-based thresholding
algorithms," CVGIP: Graphical Models and Image Processing,
vol. 55, pp. 532-537, 1993.
:DOI:`10.1006/cgip.1993.1040`
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_mean(image)
>>> binary = image > thresh
threshold_minimum(image=None, nbins=256, max_num_iter=10000, *, hist=None)
Return threshold value based on minimum method.
The histogram of the input ``image`` is computed if not provided and
smoothed until there are only two maxima. Then the minimum in between is
the threshold value.
Either image or hist must be provided. In case hist is given, the actual
histogram of the image is ignored.
Parameters
----------
image : (M, N[, ...]) ndarray, optional
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
max_num_iter : int, optional
Maximum number of iterations to smooth the histogram.
hist : array, or 2-tuple of arrays, optional
Histogram to determine the threshold from and a corresponding array
of bin center intensities. Alternatively, only the histogram can be
passed.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
Raises
------
RuntimeError
If unable to find two local maxima in the histogram or if the
smoothing takes more than 1e4 iterations.
References
----------
.. [1] C. A. Glasbey, "An analysis of histogram-based thresholding
algorithms," CVGIP: Graphical Models and Image Processing,
vol. 55, pp. 532-537, 1993.
.. [2] Prewitt, JMS & Mendelsohn, ML (1966), "The analysis of cell
images", Annals of the New York Academy of Sciences 128: 1035-1053
:DOI:`10.1111/j.1749-6632.1965.tb11715.x`
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_minimum(image)
>>> binary = image > thresh
threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None)
Generate `classes`-1 threshold values to divide gray levels in `image`,
following Otsu's method for multiple classes.
The threshold values are chosen to maximize the total sum of pairwise
variances between the thresholded graylevel classes. See Notes and [1]_
for more details.
Either image or hist must be provided. If hist is provided, the actual
histogram of the image is ignored.
Parameters
----------
image : (M, N[, ...]) ndarray, optional
Grayscale input image.
classes : int, optional
Number of classes to be thresholded, i.e. the number of resulting
regions.
nbins : int, optional
Number of bins used to calculate the histogram. This value is ignored
for integer arrays.
hist : array, or 2-tuple of arrays, optional
Histogram from which to determine the threshold, and optionally a
corresponding array of bin center intensities. If no hist provided,
this function will compute it from the image (see notes).
Returns
-------
thresh : array
Array containing the threshold values for the desired classes.
Raises
------
ValueError
If ``image`` contains less grayscale value then the desired
number of classes.
Notes
-----
This implementation relies on a Cython function whose complexity
is :math:`O\left(\frac{Ch^{C-1}}{(C-1)!}\right)`, where :math:`h`
is the number of histogram bins and :math:`C` is the number of
classes desired.
If no hist is given, this function will make use of
`skimage.exposure.histogram`, which behaves differently than
`np.histogram`. While both allowed, use the former for consistent
behaviour.
The input image must be grayscale.
References
----------
.. [1] Liao, P-S., Chen, T-S. and Chung, P-C., "A fast algorithm for
multilevel thresholding", Journal of Information Science and
Engineering 17 (5): 713-727, 2001. Available at:
<https://ftp.iis.sinica.edu.tw/JISE/2001/200109_01.pdf>
:DOI:`10.6688/JISE.2001.17.5.1`
.. [2] Tosa, Y., "Multi-Otsu Threshold", a java plugin for ImageJ.
Available at:
<http://imagej.net/plugins/download/Multi_OtsuThreshold.java>
Examples
--------
>>> from skimage.color import label2rgb
>>> from skimage import data
>>> image = data.camera()
>>> thresholds = threshold_multiotsu(image)
>>> regions = np.digitize(image, bins=thresholds)
>>> regions_colorized = label2rgb(regions)
threshold_niblack(image, window_size=15, k=0.2)
Applies Niblack local threshold to an array.
A threshold T is calculated for every pixel in the image using the
following formula::
T = m(x,y) - k * s(x,y)
where m(x,y) and s(x,y) are the mean and standard deviation of
pixel (x,y) neighborhood defined by a rectangular window with size w
times w centered around the pixel. k is a configurable parameter
that weights the effect of standard deviation.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
window_size : int, or iterable of int, optional
Window size specified as a single odd integer (3, 5, 7, …),
or an iterable of length ``image.ndim`` containing only odd
integers (e.g. ``(1, 5, 5)``).
k : float, optional
Value of parameter k in threshold formula.
Returns
-------
threshold : (M, N[, ...]) ndarray
Threshold mask. All pixels with an intensity higher than
this value are assumed to be foreground.
Notes
-----
This algorithm is originally designed for text recognition.
The Bradley threshold is a particular case of the Niblack
one, being equivalent to
>>> from skimage import data
>>> image = data.page()
>>> q = 1
>>> threshold_image = threshold_niblack(image, k=0) * q
for some value ``q``. By default, Bradley and Roth use ``q=1``.
References
----------
.. [1] W. Niblack, An introduction to Digital Image Processing,
Prentice-Hall, 1986.
.. [2] D. Bradley and G. Roth, "Adaptive thresholding using Integral
Image", Journal of Graphics Tools 12(2), pp. 13-21, 2007.
:DOI:`10.1080/2151237X.2007.10129236`
Examples
--------
>>> from skimage import data
>>> image = data.page()
>>> threshold_image = threshold_niblack(image, window_size=7, k=0.1)
threshold_otsu(image=None, nbins=256, *, hist=None)
Return threshold value based on Otsu's method.
Either image or hist must be provided. If hist is provided, the actual
histogram of the image is ignored.
Parameters
----------
image : (M, N[, ...]) ndarray, optional
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
hist : array, or 2-tuple of arrays, optional
Histogram from which to determine the threshold, and optionally a
corresponding array of bin center intensities. If no hist provided,
this function will compute it from the image.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
References
----------
.. [1] Wikipedia, https://en.wikipedia.org/wiki/Otsu's_Method
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_otsu(image)
>>> binary = image <= thresh
Notes
-----
The input image must be grayscale.
threshold_sauvola(image, window_size=15, k=0.2, r=None)
Applies Sauvola local threshold to an array. Sauvola is a
modification of Niblack technique.
In the original method a threshold T is calculated for every pixel
in the image using the following formula::
T = m(x,y) * (1 + k * ((s(x,y) / R) - 1))
where m(x,y) and s(x,y) are the mean and standard deviation of
pixel (x,y) neighborhood defined by a rectangular window with size w
times w centered around the pixel. k is a configurable parameter
that weights the effect of standard deviation.
R is the maximum standard deviation of a grayscale image.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
window_size : int, or iterable of int, optional
Window size specified as a single odd integer (3, 5, 7, …),
or an iterable of length ``image.ndim`` containing only odd
integers (e.g. ``(1, 5, 5)``).
k : float, optional
Value of the positive parameter k.
r : float, optional
Value of R, the dynamic range of standard deviation.
If None, set to the half of the image dtype range.
Returns
-------
threshold : (M, N[, ...]) ndarray
Threshold mask. All pixels with an intensity higher than
this value are assumed to be foreground.
Notes
-----
This algorithm is originally designed for text recognition.
References
----------
.. [1] J. Sauvola and M. Pietikainen, "Adaptive document image
binarization," Pattern Recognition 33(2),
pp. 225-236, 2000.
:DOI:`10.1016/S0031-3203(99)00055-2`
Examples
--------
>>> from skimage import data
>>> image = data.page()
>>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2)
>>> binary_image = image > t_sauvola
threshold_triangle(image, nbins=256)
Return threshold value based on the triangle algorithm.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
References
----------
.. [1] Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
Automatic Measurement of Sister Chromatid Exchange Frequency,
Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
:DOI:`10.1177/25.7.70454`
.. [2] ImageJ AutoThresholder code,
http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_triangle(image)
>>> binary = image > thresh
threshold_yen(image=None, nbins=256, *, hist=None)
Return threshold value based on Yen's method.
Either image or hist must be provided. In case hist is given, the actual
histogram of the image is ignored.
Parameters
----------
image : (M, N[, ...]) ndarray
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
hist : array, or 2-tuple of arrays, optional
Histogram from which to determine the threshold, and optionally a
corresponding array of bin center intensities.
An alternative use of this function is to pass it only hist.
Returns
-------
threshold : float
Upper threshold value. All pixels with an intensity higher than
this value are assumed to be foreground.
References
----------
.. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
for Automatic Multilevel Thresholding" IEEE Trans. on Image
Processing, 4(3): 370-378. :DOI:`10.1109/83.366472`
.. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
Techniques and Quantitative Performance Evaluation" Journal of
Electronic Imaging, 13(1): 146-165, :DOI:`10.1117/1.1631315`
http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
.. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_yen(image)
>>> binary = image <= thresh
try_all_threshold(image, figsize=(8, 5), verbose=True)
Returns a figure comparing the outputs of different thresholding methods.
Parameters
----------
image : (M, N) ndarray
Input image.
figsize : tuple, optional
Figure size (in inches).
verbose : bool, optional
Print function name for each method.
Returns
-------
fig, ax : tuple
Matplotlib figure and axes.
Notes
-----
The following algorithms are used:
* isodata
* li
* mean
* minimum
* otsu
* triangle
* yen
Examples
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('matplotlib')
>>> from skimage.data import text
>>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False)
unsharp_mask(image, radius=1.0, amount=1.0, preserve_range=False, *, channel_axis=None)
Unsharp masking filter.
The sharp details are identified as the difference between the original
image and its blurred version. These details are then scaled, and added
back to the original image.
Parameters
----------
image : (M[, ...][, C]) ndarray
Input image.
radius : scalar or sequence of scalars, optional
If a scalar is given, then its value is used for all dimensions.
If sequence is given, then there must be exactly one radius
for each dimension except the last dimension for multichannel images.
Note that 0 radius means no blurring, and negative values are
not allowed.
amount : scalar, optional
The details will be amplified with this factor. The factor could be 0
or negative. Typically, it is a small positive number, e.g. 1.0.
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
-------
output : (M[, ...][, C]) ndarray of float
Image with unsharp mask applied.
Notes
-----
Unsharp masking is an image sharpening technique. It is a linear image
operation, and numerically stable, unlike deconvolution which is an
ill-posed problem. Because of this stability, it is often
preferred over deconvolution.
The main idea is as follows: sharp details are identified as the
difference between the original image and its blurred version.
These details are added back to the original image after a scaling step:
enhanced image = original + amount * (original - blurred)
When applying this filter to several color layers independently,
color bleeding may occur. More visually pleasing result can be
achieved by processing only the brightness/lightness/intensity
channel in a suitable color space such as HSV, HSL, YUV, or YCbCr.
Unsharp masking is described in most introductory digital image
processing books. This implementation is based on [1]_.
Examples
--------
>>> array = np.ones(shape=(5,5), dtype=np.uint8)*100
>>> array[2,2] = 120
>>> array
array([[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100],
[100, 100, 120, 100, 100],
[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100]], dtype=uint8)
>>> np.around(unsharp_mask(array, radius=0.5, amount=2),2)
array([[0.39, 0.39, 0.39, 0.39, 0.39],
[0.39, 0.39, 0.38, 0.39, 0.39],
[0.39, 0.38, 0.53, 0.38, 0.39],
[0.39, 0.39, 0.38, 0.39, 0.39],
[0.39, 0.39, 0.39, 0.39, 0.39]])
>>> array = np.ones(shape=(5,5), dtype=np.int8)*100
>>> array[2,2] = 127
>>> np.around(unsharp_mask(array, radius=0.5, amount=2),2)
array([[0.79, 0.79, 0.79, 0.79, 0.79],
[0.79, 0.78, 0.75, 0.78, 0.79],
[0.79, 0.75, 1. , 0.75, 0.79],
[0.79, 0.78, 0.75, 0.78, 0.79],
[0.79, 0.79, 0.79, 0.79, 0.79]])
>>> np.around(unsharp_mask(array, radius=0.5, amount=2, preserve_range=True), 2)
array([[100. , 100. , 99.99, 100. , 100. ],
[100. , 99.39, 95.48, 99.39, 100. ],
[ 99.99, 95.48, 147.59, 95.48, 99.99],
[100. , 99.39, 95.48, 99.39, 100. ],
[100. , 100. , 99.99, 100. , 100. ]])
References
----------
.. [1] Maria Petrou, Costas Petrou
"Image Processing: The Fundamentals", (2010), ed ii., page 357,
ISBN 13: 9781119994398 :DOI:`10.1002/9781119994398`
.. [2] Wikipedia. Unsharp masking
https://en.wikipedia.org/wiki/Unsharp_masking
wiener(data, impulse_response=None, filter_params=None, K=0.25, predefined_filter=None)
Minimum Mean Square Error (Wiener) inverse filter.
Parameters
----------
data : (M, N) ndarray
Input data.
K : float or (M, N) ndarray
Ratio between power spectrum of noise and undegraded
image.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See LPIFilter2D.__init__.
filter_params : dict, optional
Additional keyword parameters to the impulse_response function.
Other Parameters
----------------
predefined_filter : LPIFilter2D
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
window(window_type, shape, warp_kwargs=None)
Return an n-dimensional window of a given size and dimensionality.
Parameters
----------
window_type : string, float, or tuple
The type of window to be created. Any window type supported by
``scipy.signal.get_window`` is allowed here. See notes below for a
current list, or the SciPy documentation for the version of SciPy
on your machine.
shape : tuple of int or int
The shape of the window along each axis. If an integer is provided,
a 1D window is generated.
warp_kwargs : dict
Keyword arguments passed to `skimage.transform.warp` (e.g.,
``warp_kwargs={'order':3}`` to change interpolation method).
Returns
-------
nd_window : ndarray
A window of the specified ``shape``. ``dtype`` is ``np.float64``.
Notes
-----
This function is based on ``scipy.signal.get_window`` and thus can access
all of the window types available to that function
(e.g., ``"hann"``, ``"boxcar"``). Note that certain window types require
parameters that have to be supplied with the window name as a tuple
(e.g., ``("tukey", 0.8)``). If only a float is supplied, it is interpreted
as the beta parameter of the Kaiser window.
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html
for more details.
Note that this function generates a double precision array of the specified
``shape`` and can thus generate very large arrays that consume a large
amount of available memory.
The approach taken here to create nD windows is to first calculate the
Euclidean distance from the center of the intended nD window to each
position in the array. That distance is used to sample, with
interpolation, from a 1D window returned from ``scipy.signal.get_window``.
The method of interpolation can be changed with the ``order`` keyword
argument passed to `skimage.transform.warp`.
Some coordinates in the output window will be outside of the original
signal; these will be filled in with zeros.
Window types:
- boxcar
- triang
- blackman
- hamming
- hann
- bartlett
- flattop
- parzen
- bohman
- blackmanharris
- nuttall
- barthann
- kaiser (needs beta)
- gaussian (needs standard deviation)
- general_gaussian (needs power, width)
- slepian (needs width)
- dpss (needs normalized half-bandwidth)
- chebwin (needs attenuation)
- exponential (needs decay scale)
- tukey (needs taper fraction)
Examples
--------
Return a Hann window with shape (512, 512):
>>> from skimage.filters import window
>>> w = window('hann', (512, 512))
Return a Kaiser window with beta parameter of 16 and shape (256, 256, 35):
>>> w = window(16, (256, 256, 35))
Return a Tukey window with an alpha parameter of 0.8 and shape (100, 300):
>>> w = window(('tukey', 0.8), (100, 300))
References
----------
.. [1] Two-dimensional window design, Wikipedia,
https://en.wikipedia.org/wiki/Two_dimensional_window_design
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\filters\__init__.py
scikit-image.future
Python Library Documentation: package skimage.future in skimage
NAME
skimage.future - Functionality with an experimental API.
DESCRIPTION
.. warning::
Although you can count on the functions in this package being
around in the future, the API may change with any version update
**and will not follow the skimage two-version deprecation path**.
Therefore, use the functions herein with care, and do not use them
in production code that will depend on updated skimage versions.
PACKAGE CONTENTS
manual_segmentation
tests (package)
trainable_segmentation
CLASSES
builtins.object
skimage.future.trainable_segmentation.TrainableSegmenter
class TrainableSegmenter(builtins.object)
| TrainableSegmenter(clf=None, features_func=None)
|
| Estimator for classifying pixels.
|
| Parameters
| ----------
| clf : classifier object, optional
| classifier object, exposing a ``fit`` and a ``predict`` method as in
| scikit-learn's API, for example an instance of
| ``RandomForestClassifier`` or ``LogisticRegression`` classifier.
| features_func : function, optional
| function computing features on all pixels of the image, to be passed
| to the classifier. The output should be of shape
| ``(m_features, *labels.shape)``. If None,
| :func:`skimage.feature.multiscale_basic_features` is used.
|
| Methods
| -------
| compute_features
| fit
| predict
|
| Methods defined here:
|
| __init__(self, clf=None, features_func=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| compute_features(self, image)
|
| fit(self, image, labels)
| Train classifier using partially labeled (annotated) image.
|
| Parameters
| ----------
| image : ndarray
| Input image, which can be grayscale or multichannel, and must have a
| number of dimensions compatible with ``self.features_func``.
| labels : ndarray of ints
| Labeled array of shape compatible with ``image`` (same shape for a
| single-channel image). Labels >= 1 correspond to the training set and
| label 0 to unlabeled pixels to be segmented.
|
| predict(self, image)
| Segment new image using trained internal classifier.
|
| Parameters
| ----------
| image : ndarray
| Input image, which can be grayscale or multichannel, and must have a
| number of dimensions compatible with ``self.features_func``.
|
| Raises
| ------
| NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
fit_segmenter(labels, features, clf)
Segmentation using labeled parts of the image and a classifier.
Parameters
----------
labels : ndarray of ints
Image of labels. Labels >= 1 correspond to the training set and
label 0 to unlabeled pixels to be segmented.
features : ndarray
Array of features, with the first dimension corresponding to the number
of features, and the other dimensions correspond to ``labels.shape``.
clf : classifier object
classifier object, exposing a ``fit`` and a ``predict`` method as in
scikit-learn's API, for example an instance of
``RandomForestClassifier`` or ``LogisticRegression`` classifier.
Returns
-------
clf : classifier object
classifier trained on ``labels``
Raises
------
NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``).
manual_lasso_segmentation(image, alpha=0.4, return_all=False)
Return a label image based on freeform selections made with the mouse.
Parameters
----------
image : (M, N[, 3]) array
Grayscale or RGB image.
alpha : float, optional
Transparency value for polygons drawn over the image.
return_all : bool, optional
If True, an array containing each separate polygon drawn is returned.
(The polygons may overlap.) If False (default), latter polygons
"overwrite" earlier ones where they overlap.
Returns
-------
labels : array of int, shape ([Q, ]M, N)
The segmented regions. If mode is `'separate'`, the leading dimension
of the array corresponds to the number of regions that the user drew.
Notes
-----
Press and hold the left mouse button to draw around each object.
Examples
--------
>>> from skimage import data, future
>>> import matplotlib.pyplot as plt # doctest: +SKIP
>>> camera = data.camera()
>>> mask = future.manual_lasso_segmentation(camera) # doctest: +SKIP
>>> fig, ax = plt.subplots() # doctest: +SKIP
>>> ax.imshow(mask) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
manual_polygon_segmentation(image, alpha=0.4, return_all=False)
Return a label image based on polygon selections made with the mouse.
Parameters
----------
image : (M, N[, 3]) array
Grayscale or RGB image.
alpha : float, optional
Transparency value for polygons drawn over the image.
return_all : bool, optional
If True, an array containing each separate polygon drawn is returned.
(The polygons may overlap.) If False (default), latter polygons
"overwrite" earlier ones where they overlap.
Returns
-------
labels : array of int, shape ([Q, ]M, N)
The segmented regions. If mode is `'separate'`, the leading dimension
of the array corresponds to the number of regions that the user drew.
Notes
-----
Use left click to select the vertices of the polygon
and right click to confirm the selection once all vertices are selected.
Examples
--------
>>> from skimage import data, future
>>> import matplotlib.pyplot as plt # doctest: +SKIP
>>> camera = data.camera()
>>> mask = future.manual_polygon_segmentation(camera) # doctest: +SKIP
>>> fig, ax = plt.subplots() # doctest: +SKIP
>>> ax.imshow(mask) # doctest: +SKIP
>>> plt.show() # doctest: +SKIP
predict_segmenter(features, clf)
Segmentation of images using a pretrained classifier.
Parameters
----------
features : ndarray
Array of features, with the last dimension corresponding to the number
of features, and the other dimensions are compatible with the shape of
the image to segment, or a flattened image.
clf : classifier object
trained classifier object, exposing a ``predict`` method as in
scikit-learn's API, for example an instance of
``RandomForestClassifier`` or ``LogisticRegression`` classifier. The
classifier must be already trained, for example with
:func:`skimage.future.fit_segmenter`.
Returns
-------
output : ndarray
Labeled array, built from the prediction of the classifier.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\future\__init__.py
scikit-image.graph
Python Library Documentation: package skimage.graph in skimage
NAME
skimage.graph - Graph-based operations, e.g., shortest paths.
DESCRIPTION
This includes creating adjacency graphs of pixels in an image, finding the
central pixel in an image, finding (minimum-cost) paths across pixels, merging
and cutting of graphs, etc.
PACKAGE CONTENTS
_graph
_graph_cut
_graph_merge
_mcp
_ncut
_ncut_cy
_rag
_spath
heap
mcp
spath
tests (package)
CLASSES
builtins.object
skimage.graph._mcp.MCP
skimage.graph._mcp.MCP_Connect
skimage.graph._mcp.MCP_Flexible
skimage.graph._mcp.MCP_Geometric
networkx.classes.graph.Graph(builtins.object)
skimage.graph._rag.RAG
class MCP(builtins.object)
| MCP(costs, offsets=None, fully_connected=True, sampling=None)
|
| A class for finding the minimum cost path through a given n-d costs array.
|
| Given an n-d costs array, this class can be used to find the minimum-cost
| path through that array from any set of points to any other set of points.
| Basic usage is to initialize the class and call find_costs() with a one
| or more starting indices (and an optional list of end indices). After
| that, call traceback() one or more times to find the path from any given
| end-position to the closest starting index. New paths through the same
| costs array can be found by calling find_costs() repeatedly.
|
| The cost of a path is calculated simply as the sum of the values of the
| `costs` array at each point on the path. The class MCP_Geometric, on the
| other hand, accounts for the fact that diagonal vs. axial moves are of
| different lengths, and weights the path cost accordingly.
|
| Array elements with infinite or negative costs will simply be ignored, as
| will paths whose cumulative cost overflows to infinite.
|
| Parameters
| ----------
| costs : ndarray
| offsets : iterable, optional
| A list of offset tuples: each offset specifies a valid move from a
| given n-d position.
| If not provided, offsets corresponding to a singly- or fully-connected
| n-d neighborhood will be constructed with make_offsets(), using the
| `fully_connected` parameter value.
| fully_connected : bool, optional
| If no `offsets` are provided, this determines the connectivity of the
| generated neighborhood. If true, the path may go along diagonals
| between elements of the `costs` array; otherwise only axial moves are
| permitted.
| sampling : tuple, optional
| For each dimension, specifies the distance between two cells/voxels.
| If not given or None, the distance is assumed unit.
|
| Attributes
| ----------
| offsets : ndarray
| Equivalent to the `offsets` provided to the constructor, or if none
| were so provided, the offsets created for the requested n-d
| neighborhood. These are useful for interpreting the `traceback` array
| returned by the find_costs() method.
|
| Methods defined here:
|
| __init__(...)
| __init__(costs, offsets=None, fully_connected=True, sampling=None)
|
| See class documentation.
|
| __reduce__ = __reduce_cython__(...)
|
| __reduce_cython__(self)
|
| __setstate__ = __setstate_cython__(...)
|
| __setstate_cython__(self, __pyx_state)
|
| find_costs(self, starts, ends=None, find_all_ends=True, max_coverage=1.0, max_cumulative_cost=None, max_cost=None)
| Find the minimum-cost path from the given starting points.
|
| This method finds the minimum-cost path to the specified ending
| indices from any one of the specified starting indices. If no end
| positions are given, then the minimum-cost path to every position in
| the costs array will be found.
|
| Parameters
| ----------
| starts : iterable
| A list of n-d starting indices (where n is the dimension of the
| `costs` array). The minimum cost path to the closest/cheapest
| starting point will be found.
| ends : iterable, optional
| A list of n-d ending indices.
| find_all_ends : bool, optional
| If 'True' (default), the minimum-cost-path to every specified
| end-position will be found; otherwise the algorithm will stop when
| a a path is found to any end-position. (If no `ends` were
| specified, then this parameter has no effect.)
|
| Returns
| -------
| cumulative_costs : ndarray
| Same shape as the `costs` array; this array records the minimum
| cost path from the nearest/cheapest starting index to each index
| considered. (If `ends` were specified, not all elements in the
| array will necessarily be considered: positions not evaluated will
| have a cumulative cost of inf. If `find_all_ends` is 'False', only
| one of the specified end-positions will have a finite cumulative
| cost.)
| traceback : ndarray
| Same shape as the `costs` array; this array contains the offset to
| any given index from its predecessor index. The offset indices
| index into the `offsets` attribute, which is a array of n-d
| offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
| that means that the predecessor of [x, y] in the minimum cost path
| to some start position is [x+1, y+1]. Note that if the
| offset_index is -1, then the given index was not considered.
|
| goal_reached(self, index, cumcost)
| int goal_reached(int index, float cumcost)
| This method is called each iteration after popping an index
| from the heap, before examining the neighbors.
|
| This method can be overloaded to modify the behavior of the MCP
| algorithm. An example might be to stop the algorithm when a
| certain cumulative cost is reached, or when the front is a
| certain distance away from the seed point.
|
| This method should return 1 if the algorithm should not check
| the current point's neighbors and 2 if the algorithm is now
| done.
|
| traceback(self, end)
| traceback(end)
|
| Trace a minimum cost path through the pre-calculated traceback array.
|
| This convenience function reconstructs the the minimum cost path to a
| given end position from one of the starting indices provided to
| find_costs(), which must have been called previously. This function
| can be called as many times as desired after find_costs() has been
| run.
|
| Parameters
| ----------
| end : iterable
| An n-d index into the `costs` array.
|
| Returns
| -------
| traceback : list of n-d tuples
| A list of indices into the `costs` array, starting with one of
| the start positions passed to find_costs(), and ending with the
| given `end` index. These indices specify the minimum-cost path
| from any given start index to the `end` index. (The total cost
| of that path can be read out from the `cumulative_costs` array
| returned by find_costs().)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| offsets
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
class MCP_Connect(MCP)
| MCP_Connect(costs, offsets=None, fully_connected=True)
|
| Connect source points using the distance-weighted minimum cost function.
|
| A front is grown from each seed point simultaneously, while the
| origin of the front is tracked as well. When two fronts meet,
| create_connection() is called. This method must be overloaded to
| deal with the found edges in a way that is appropriate for the
| application.
|
| Method resolution order:
| MCP_Connect
| MCP
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__ = __reduce_cython__(...)
|
| __reduce_cython__(self)
|
| __setstate__ = __setstate_cython__(...)
|
| __setstate_cython__(self, __pyx_state)
|
| create_connection(self, id1, id2, tb1, tb2, cost1, cost2)
| create_connection id1, id2, pos1, pos2, cost1, cost2)
|
| Overload this method to keep track of the connections that are
| found during MCP processing. Note that a connection with the
| same ids can be found multiple times (but with different
| positions and costs).
|
| At the time that this method is called, both points are "frozen"
| and will not be visited again by the MCP algorithm.
|
| Parameters
| ----------
| id1 : int
| The seed point id where the first neighbor originated from.
| id2 : int
| The seed point id where the second neighbor originated from.
| pos1 : tuple
| The index of of the first neighbor in the connection.
| pos2 : tuple
| The index of of the second neighbor in the connection.
| cost1 : float
| The cumulative cost at `pos1`.
| cost2 : float
| The cumulative costs at `pos2`.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from MCP:
|
| find_costs(self, starts, ends=None, find_all_ends=True, max_coverage=1.0, max_cumulative_cost=None, max_cost=None)
| Find the minimum-cost path from the given starting points.
|
| This method finds the minimum-cost path to the specified ending
| indices from any one of the specified starting indices. If no end
| positions are given, then the minimum-cost path to every position in
| the costs array will be found.
|
| Parameters
| ----------
| starts : iterable
| A list of n-d starting indices (where n is the dimension of the
| `costs` array). The minimum cost path to the closest/cheapest
| starting point will be found.
| ends : iterable, optional
| A list of n-d ending indices.
| find_all_ends : bool, optional
| If 'True' (default), the minimum-cost-path to every specified
| end-position will be found; otherwise the algorithm will stop when
| a a path is found to any end-position. (If no `ends` were
| specified, then this parameter has no effect.)
|
| Returns
| -------
| cumulative_costs : ndarray
| Same shape as the `costs` array; this array records the minimum
| cost path from the nearest/cheapest starting index to each index
| considered. (If `ends` were specified, not all elements in the
| array will necessarily be considered: positions not evaluated will
| have a cumulative cost of inf. If `find_all_ends` is 'False', only
| one of the specified end-positions will have a finite cumulative
| cost.)
| traceback : ndarray
| Same shape as the `costs` array; this array contains the offset to
| any given index from its predecessor index. The offset indices
| index into the `offsets` attribute, which is a array of n-d
| offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
| that means that the predecessor of [x, y] in the minimum cost path
| to some start position is [x+1, y+1]. Note that if the
| offset_index is -1, then the given index was not considered.
|
| goal_reached(self, index, cumcost)
| int goal_reached(int index, float cumcost)
| This method is called each iteration after popping an index
| from the heap, before examining the neighbors.
|
| This method can be overloaded to modify the behavior of the MCP
| algorithm. An example might be to stop the algorithm when a
| certain cumulative cost is reached, or when the front is a
| certain distance away from the seed point.
|
| This method should return 1 if the algorithm should not check
| the current point's neighbors and 2 if the algorithm is now
| done.
|
| traceback(self, end)
| traceback(end)
|
| Trace a minimum cost path through the pre-calculated traceback array.
|
| This convenience function reconstructs the the minimum cost path to a
| given end position from one of the starting indices provided to
| find_costs(), which must have been called previously. This function
| can be called as many times as desired after find_costs() has been
| run.
|
| Parameters
| ----------
| end : iterable
| An n-d index into the `costs` array.
|
| Returns
| -------
| traceback : list of n-d tuples
| A list of indices into the `costs` array, starting with one of
| the start positions passed to find_costs(), and ending with the
| given `end` index. These indices specify the minimum-cost path
| from any given start index to the `end` index. (The total cost
| of that path can be read out from the `cumulative_costs` array
| returned by find_costs().)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from MCP:
|
| offsets
class MCP_Flexible(MCP)
| MCP_Flexible(costs, offsets=None, fully_connected=True)
|
| Find minimum cost paths through an N-d costs array.
|
| See the documentation for MCP for full details. This class differs from
| MCP in that several methods can be overloaded (from pure Python) to
| modify the behavior of the algorithm and/or create custom algorithms
| based on MCP. Note that goal_reached can also be overloaded in the
| MCP class.
|
| Method resolution order:
| MCP_Flexible
| MCP
| builtins.object
|
| Methods defined here:
|
| __reduce__ = __reduce_cython__(...)
|
| __reduce_cython__(self)
|
| __setstate__ = __setstate_cython__(...)
|
| __setstate_cython__(self, __pyx_state)
|
| examine_neighbor(self, index, new_index, offset_length)
| examine_neighbor(index, new_index, offset_length)
| This method is called once for every pair of neighboring nodes,
| as soon as both nodes are frozen.
|
| This method can be overloaded to obtain information about
| neighboring nodes, and/or to modify the behavior of the MCP
| algorithm. One example is the MCP_Connect class, which checks
| for meeting fronts using this hook.
|
| travel_cost(self, old_cost, new_cost, offset_length)
| travel_cost(old_cost, new_cost, offset_length)
| This method calculates the travel cost for going from the
| current node to the next. The default implementation returns
| new_cost. Overload this method to adapt the behaviour of the
| algorithm.
|
| update_node(self, index, new_index, offset_length)
| update_node(index, new_index, offset_length)
| This method is called when a node is updated, right after
| new_index is pushed onto the heap and the traceback map is
| updated.
|
| This method can be overloaded to keep track of other arrays
| that are used by a specific implementation of the algorithm.
| For instance the MCP_Connect class uses it to update an id map.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from MCP:
|
| __init__(...)
| __init__(costs, offsets=None, fully_connected=True, sampling=None)
|
| See class documentation.
|
| find_costs(self, starts, ends=None, find_all_ends=True, max_coverage=1.0, max_cumulative_cost=None, max_cost=None)
| Find the minimum-cost path from the given starting points.
|
| This method finds the minimum-cost path to the specified ending
| indices from any one of the specified starting indices. If no end
| positions are given, then the minimum-cost path to every position in
| the costs array will be found.
|
| Parameters
| ----------
| starts : iterable
| A list of n-d starting indices (where n is the dimension of the
| `costs` array). The minimum cost path to the closest/cheapest
| starting point will be found.
| ends : iterable, optional
| A list of n-d ending indices.
| find_all_ends : bool, optional
| If 'True' (default), the minimum-cost-path to every specified
| end-position will be found; otherwise the algorithm will stop when
| a a path is found to any end-position. (If no `ends` were
| specified, then this parameter has no effect.)
|
| Returns
| -------
| cumulative_costs : ndarray
| Same shape as the `costs` array; this array records the minimum
| cost path from the nearest/cheapest starting index to each index
| considered. (If `ends` were specified, not all elements in the
| array will necessarily be considered: positions not evaluated will
| have a cumulative cost of inf. If `find_all_ends` is 'False', only
| one of the specified end-positions will have a finite cumulative
| cost.)
| traceback : ndarray
| Same shape as the `costs` array; this array contains the offset to
| any given index from its predecessor index. The offset indices
| index into the `offsets` attribute, which is a array of n-d
| offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
| that means that the predecessor of [x, y] in the minimum cost path
| to some start position is [x+1, y+1]. Note that if the
| offset_index is -1, then the given index was not considered.
|
| goal_reached(self, index, cumcost)
| int goal_reached(int index, float cumcost)
| This method is called each iteration after popping an index
| from the heap, before examining the neighbors.
|
| This method can be overloaded to modify the behavior of the MCP
| algorithm. An example might be to stop the algorithm when a
| certain cumulative cost is reached, or when the front is a
| certain distance away from the seed point.
|
| This method should return 1 if the algorithm should not check
| the current point's neighbors and 2 if the algorithm is now
| done.
|
| traceback(self, end)
| traceback(end)
|
| Trace a minimum cost path through the pre-calculated traceback array.
|
| This convenience function reconstructs the the minimum cost path to a
| given end position from one of the starting indices provided to
| find_costs(), which must have been called previously. This function
| can be called as many times as desired after find_costs() has been
| run.
|
| Parameters
| ----------
| end : iterable
| An n-d index into the `costs` array.
|
| Returns
| -------
| traceback : list of n-d tuples
| A list of indices into the `costs` array, starting with one of
| the start positions passed to find_costs(), and ending with the
| given `end` index. These indices specify the minimum-cost path
| from any given start index to the `end` index. (The total cost
| of that path can be read out from the `cumulative_costs` array
| returned by find_costs().)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from MCP:
|
| offsets
class MCP_Geometric(MCP)
| MCP_Geometric(costs, offsets=None, fully_connected=True)
|
| Find distance-weighted minimum cost paths through an n-d costs array.
|
| See the documentation for MCP for full details. This class differs from
| MCP in that the cost of a path is not simply the sum of the costs along
| that path.
|
| This class instead assumes that the costs array contains at each position
| the "cost" of a unit distance of travel through that position. For
| example, a move (in 2-d) from (1, 1) to (1, 2) is assumed to originate in
| the center of the pixel (1, 1) and terminate in the center of (1, 2). The
| entire move is of distance 1, half through (1, 1) and half through (1, 2);
| thus the cost of that move is `(1/2)*costs[1,1] + (1/2)*costs[1,2]`.
|
| On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and
| is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the
| other half in (2, 2), so the cost of this move is calculated as
| `(sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2]`.
|
| These calculations don't make a lot of sense with offsets of magnitude
| greater than 1. Use the `sampling` argument in order to deal with
| anisotropic data.
|
| Method resolution order:
| MCP_Geometric
| MCP
| builtins.object
|
| Methods defined here:
|
| __init__(...)
| __init__(costs, offsets=None, fully_connected=True, sampling=None)
|
| See class documentation.
|
| __reduce__ = __reduce_cython__(...)
|
| __reduce_cython__(self)
|
| __setstate__ = __setstate_cython__(...)
|
| __setstate_cython__(self, __pyx_state)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from MCP:
|
| find_costs(self, starts, ends=None, find_all_ends=True, max_coverage=1.0, max_cumulative_cost=None, max_cost=None)
| Find the minimum-cost path from the given starting points.
|
| This method finds the minimum-cost path to the specified ending
| indices from any one of the specified starting indices. If no end
| positions are given, then the minimum-cost path to every position in
| the costs array will be found.
|
| Parameters
| ----------
| starts : iterable
| A list of n-d starting indices (where n is the dimension of the
| `costs` array). The minimum cost path to the closest/cheapest
| starting point will be found.
| ends : iterable, optional
| A list of n-d ending indices.
| find_all_ends : bool, optional
| If 'True' (default), the minimum-cost-path to every specified
| end-position will be found; otherwise the algorithm will stop when
| a a path is found to any end-position. (If no `ends` were
| specified, then this parameter has no effect.)
|
| Returns
| -------
| cumulative_costs : ndarray
| Same shape as the `costs` array; this array records the minimum
| cost path from the nearest/cheapest starting index to each index
| considered. (If `ends` were specified, not all elements in the
| array will necessarily be considered: positions not evaluated will
| have a cumulative cost of inf. If `find_all_ends` is 'False', only
| one of the specified end-positions will have a finite cumulative
| cost.)
| traceback : ndarray
| Same shape as the `costs` array; this array contains the offset to
| any given index from its predecessor index. The offset indices
| index into the `offsets` attribute, which is a array of n-d
| offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1),
| that means that the predecessor of [x, y] in the minimum cost path
| to some start position is [x+1, y+1]. Note that if the
| offset_index is -1, then the given index was not considered.
|
| goal_reached(self, index, cumcost)
| int goal_reached(int index, float cumcost)
| This method is called each iteration after popping an index
| from the heap, before examining the neighbors.
|
| This method can be overloaded to modify the behavior of the MCP
| algorithm. An example might be to stop the algorithm when a
| certain cumulative cost is reached, or when the front is a
| certain distance away from the seed point.
|
| This method should return 1 if the algorithm should not check
| the current point's neighbors and 2 if the algorithm is now
| done.
|
| traceback(self, end)
| traceback(end)
|
| Trace a minimum cost path through the pre-calculated traceback array.
|
| This convenience function reconstructs the the minimum cost path to a
| given end position from one of the starting indices provided to
| find_costs(), which must have been called previously. This function
| can be called as many times as desired after find_costs() has been
| run.
|
| Parameters
| ----------
| end : iterable
| An n-d index into the `costs` array.
|
| Returns
| -------
| traceback : list of n-d tuples
| A list of indices into the `costs` array, starting with one of
| the start positions passed to find_costs(), and ending with the
| given `end` index. These indices specify the minimum-cost path
| from any given start index to the `end` index. (The total cost
| of that path can be read out from the `cumulative_costs` array
| returned by find_costs().)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from MCP:
|
| offsets
class RAG(networkx.classes.graph.Graph)
| RAG(label_image=None, connectivity=1, data=None, **attr)
|
| The Region Adjacency Graph (RAG) of an image, subclasses :obj:`networkx.Graph`.
|
| Parameters
| ----------
| label_image : array of int
| An initial segmentation, with each region labeled as a different
| integer. Every unique value in ``label_image`` will correspond to
| a node in the graph.
| connectivity : int in {1, ..., ``label_image.ndim``}, optional
| The connectivity between pixels in ``label_image``. For a 2D image,
| a connectivity of 1 corresponds to immediate neighbors up, down,
| left, and right, while a connectivity of 2 also includes diagonal
| neighbors. See :func:`scipy.ndimage.generate_binary_structure`.
| data : :obj:`networkx.Graph` specification, optional
| Initial or additional edges to pass to :obj:`networkx.Graph`
| constructor. Valid edge specifications include edge list (list of tuples),
| NumPy arrays, and SciPy sparse matrices.
| **attr : keyword arguments, optional
| Additional attributes to add to the graph.
|
| Method resolution order:
| RAG
| networkx.classes.graph.Graph
| builtins.object
|
| Methods defined here:
|
| __init__(self, label_image=None, connectivity=1, data=None, **attr)
| Initialize a graph with edges, name, or graph attributes.
|
| Parameters
| ----------
| incoming_graph_data : input graph (optional, default: None)
| Data to initialize graph. If None (default) an empty
| graph is created. The data can be an edge list, or any
| NetworkX graph object. If the corresponding optional Python
| packages are installed the data can also be a 2D NumPy array, a
| SciPy sparse array, or a PyGraphviz graph.
|
| attr : keyword arguments, optional (default= no attributes)
| Attributes to add to graph as key=value pairs.
|
| See Also
| --------
| convert
|
| Examples
| --------
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G = nx.Graph(name="my graph")
| >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
| >>> G = nx.Graph(e)
|
| Arbitrary graph attribute pairs (key=value) may be assigned
|
| >>> G = nx.Graph(e, day="Friday")
| >>> G.graph
| {'day': 'Friday'}
|
| add_edge(self, u, v, attr_dict=None, **attr)
| Add an edge between `u` and `v` while updating max node id.
|
| .. seealso:: :obj:`networkx.Graph.add_edge`.
|
| add_node(self, n, attr_dict=None, **attr)
| Add node `n` while updating the maximum node id.
|
| .. seealso:: :obj:`networkx.Graph.add_node`.
|
| copy(self)
| Copy the graph with its max node id.
|
| .. seealso:: :obj:`networkx.Graph.copy`.
|
| fresh_copy(self)
| Return a fresh copy graph with the same data structure.
|
| A fresh copy has no nodes, edges or graph attributes. It is
| the same data structure as the current graph. This method is
| typically used to create an empty version of the graph.
|
| This is required when subclassing Graph with networkx v2 and
| does not cause problems for v1. Here is more detail from
| the network migrating from 1.x to 2.x document::
|
| With the new GraphViews (SubGraph, ReversedGraph, etc)
| you can't assume that ``G.__class__()`` will create a new
| instance of the same graph type as ``G``. In fact, the
| call signature for ``__class__`` differs depending on
| whether ``G`` is a view or a base class. For v2.x you
| should use ``G.fresh_copy()`` to create a null graph of
| the correct type---ready to fill with nodes and edges.
|
| merge_nodes(self, src, dst, weight_func=<function min_weight at 0x000002539A2F3060>, in_place=True, extra_arguments=None, extra_keywords=None)
| Merge node `src` and `dst`.
|
| The new combined node is adjacent to all the neighbors of `src`
| and `dst`. `weight_func` is called to decide the weight of edges
| incident on the new node.
|
| Parameters
| ----------
| src, dst : int
| Nodes to be merged.
| weight_func : callable, optional
| Function to decide the attributes of edges incident on the new
| node. For each neighbor `n` for `src` and `dst`, `weight_func` will
| be called as follows: `weight_func(src, dst, n, *extra_arguments,
| **extra_keywords)`. `src`, `dst` and `n` are IDs of vertices in the
| RAG object which is in turn a subclass of :obj:`networkx.Graph`. It is
| expected to return a dict of attributes of the resulting edge.
| in_place : bool, optional
| If set to `True`, the merged node has the id `dst`, else merged
| node has a new id which is returned.
| extra_arguments : sequence, optional
| The sequence of extra positional arguments passed to
| `weight_func`.
| extra_keywords : dictionary, optional
| The dict of keyword arguments passed to the `weight_func`.
|
| Returns
| -------
| id : int
| The id of the new node.
|
| Notes
| -----
| If `in_place` is `False` the resulting node has a new id, rather than
| `dst`.
|
| next_id(self)
| Returns the `id` for the new node to be inserted.
|
| The current implementation returns one more than the maximum `id`.
|
| Returns
| -------
| id : int
| The `id` of the new node to be inserted.
|
| ----------------------------------------------------------------------
| Methods inherited from networkx.classes.graph.Graph:
|
| __contains__(self, n)
| Returns True if n is a node, False otherwise. Use: 'n in G'.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> 1 in G
| True
|
| __getitem__(self, n)
| Returns a dict of neighbors of node n. Use: 'G[n]'.
|
| Parameters
| ----------
| n : node
| A node in the graph.
|
| Returns
| -------
| adj_dict : dictionary
| The adjacency dictionary for nodes connected to n.
|
| Notes
| -----
| G[n] is the same as G.adj[n] and similar to G.neighbors(n)
| (which is an iterator over G.adj[n])
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G[0]
| AtlasView({1: {}})
|
| __iter__(self)
| Iterate over the nodes. Use: 'for n in G'.
|
| Returns
| -------
| niter : iterator
| An iterator over all nodes in the graph.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> [n for n in G]
| [0, 1, 2, 3]
| >>> list(G)
| [0, 1, 2, 3]
|
| __len__(self)
| Returns the number of nodes in the graph. Use: 'len(G)'.
|
| Returns
| -------
| nnodes : int
| The number of nodes in the graph.
|
| See Also
| --------
| number_of_nodes: identical method
| order: identical method
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> len(G)
| 4
|
| __str__(self)
| Returns a short summary of the graph.
|
| Returns
| -------
| info : string
| Graph information including the graph name (if any), graph type, and the
| number of nodes and edges.
|
| Examples
| --------
| >>> G = nx.Graph(name="foo")
| >>> str(G)
| "Graph named 'foo' with 0 nodes and 0 edges"
|
| >>> G = nx.path_graph(3)
| >>> str(G)
| 'Graph with 3 nodes and 2 edges'
|
| add_edges_from(self, ebunch_to_add, **attr)
| Add all the edges in ebunch_to_add.
|
| Parameters
| ----------
| ebunch_to_add : container of edges
| Each edge given in the container will be added to the
| graph. The edges must be given as 2-tuples (u, v) or
| 3-tuples (u, v, d) where d is a dictionary containing edge data.
| attr : keyword arguments, optional
| Edge data (or labels or objects) can be assigned using
| keyword arguments.
|
| See Also
| --------
| add_edge : add a single edge
| add_weighted_edges_from : convenient way to add weighted edges
|
| Notes
| -----
| Adding the same edge twice has no effect but any edge data
| will be updated when each duplicate edge is added.
|
| Edge attributes specified in an ebunch take precedence over
| attributes specified via keyword arguments.
|
| When adding edges from an iterator over the graph you are changing,
| a `RuntimeError` can be raised with message:
| `RuntimeError: dictionary changed size during iteration`. This
| happens when the graph's underlying dictionary is modified during
| iteration. To avoid this error, evaluate the iterator into a separate
| object, e.g. by using `list(iterator_of_edges)`, and pass this
| object to `G.add_edges_from`.
|
| Examples
| --------
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
| >>> e = zip(range(0, 3), range(1, 4))
| >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
| Associate data to edges
|
| >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
| >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
| Evaluate an iterator over a graph if using it to modify the same graph
|
| >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
| >>> # Grow graph by one new node, adding edges to all existing nodes.
| >>> # wrong way - will raise RuntimeError
| >>> # G.add_edges_from(((5, n) for n in G.nodes))
| >>> # correct way - note that there will be no self-edge for node 5
| >>> G.add_edges_from(list((5, n) for n in G.nodes))
|
| add_nodes_from(self, nodes_for_adding, **attr)
| Add multiple nodes.
|
| Parameters
| ----------
| nodes_for_adding : iterable container
| A container of nodes (list, dict, set, etc.).
| OR
| A container of (node, attribute dict) tuples.
| Node attributes are updated using the attribute dict.
| attr : keyword arguments, optional (default= no attributes)
| Update attributes for all nodes in nodes.
| Node attributes specified in nodes as a tuple take
| precedence over attributes specified via keyword arguments.
|
| See Also
| --------
| add_node
|
| Notes
| -----
| When adding nodes from an iterator over the graph you are changing,
| a `RuntimeError` can be raised with message:
| `RuntimeError: dictionary changed size during iteration`. This
| happens when the graph's underlying dictionary is modified during
| iteration. To avoid this error, evaluate the iterator into a separate
| object, e.g. by using `list(iterator_of_nodes)`, and pass this
| object to `G.add_nodes_from`.
|
| Examples
| --------
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.add_nodes_from("Hello")
| >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
| >>> G.add_nodes_from(K3)
| >>> sorted(G.nodes(), key=str)
| [0, 1, 2, 'H', 'e', 'l', 'o']
|
| Use keywords to update specific node attributes for every node.
|
| >>> G.add_nodes_from([1, 2], size=10)
| >>> G.add_nodes_from([3, 4], weight=0.4)
|
| Use (node, attrdict) tuples to update attributes for specific nodes.
|
| >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
| >>> G.nodes[1]["size"]
| 11
| >>> H = nx.Graph()
| >>> H.add_nodes_from(G.nodes(data=True))
| >>> H.nodes[1]["size"]
| 11
|
| Evaluate an iterator over a graph if using it to modify the same graph
|
| >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
| >>> # wrong way - will raise RuntimeError
| >>> # G.add_nodes_from(n + 1 for n in G.nodes)
| >>> # correct way
| >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
|
| add_weighted_edges_from(self, ebunch_to_add, weight='weight', **attr)
| Add weighted edges in `ebunch_to_add` with specified weight attr
|
| Parameters
| ----------
| ebunch_to_add : container of edges
| Each edge given in the list or container will be added
| to the graph. The edges must be given as 3-tuples (u, v, w)
| where w is a number.
| weight : string, optional (default= 'weight')
| The attribute name for the edge weights to be added.
| attr : keyword arguments, optional (default= no attributes)
| Edge attributes to add/update for all edges.
|
| See Also
| --------
| add_edge : add a single edge
| add_edges_from : add multiple edges
|
| Notes
| -----
| Adding the same edge twice for Graph/DiGraph simply updates
| the edge data. For MultiGraph/MultiDiGraph, duplicate edges
| are stored.
|
| When adding edges from an iterator over the graph you are changing,
| a `RuntimeError` can be raised with message:
| `RuntimeError: dictionary changed size during iteration`. This
| happens when the graph's underlying dictionary is modified during
| iteration. To avoid this error, evaluate the iterator into a separate
| object, e.g. by using `list(iterator_of_edges)`, and pass this
| object to `G.add_weighted_edges_from`.
|
| Examples
| --------
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
|
| Evaluate an iterator over edges before passing it
|
| >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
| >>> weight = 0.1
| >>> # Grow graph by one new node, adding edges to all existing nodes.
| >>> # wrong way - will raise RuntimeError
| >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
| >>> # correct way - note that there will be no self-edge for node 5
| >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
|
| adj = <functools.cached_property object>
| Graph adjacency object holding the neighbors of each node.
|
| This object is a read-only dict-like structure with node keys
| and neighbor-dict values. The neighbor-dict is keyed by neighbor
| to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
| the color of the edge `(3, 2)` to `"blue"`.
|
| Iterating over G.adj behaves like a dict. Useful idioms include
| `for nbr, datadict in G.adj[n].items():`.
|
| The neighbor information is also provided by subscripting the graph.
| So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
| For directed graphs, `G.adj` holds outgoing (successor) info.
|
| adjacency(self)
| Returns an iterator over (node, adjacency dict) tuples for all nodes.
|
| For directed graphs, only outgoing neighbors/adjacencies are included.
|
| Returns
| -------
| adj_iter : iterator
| An iterator over (node, adjacency dictionary) for all nodes in
| the graph.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
| [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
|
| clear(self)
| Remove all nodes and edges from the graph.
|
| This also removes the name, and all graph, node, and edge attributes.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.clear()
| >>> list(G.nodes)
| []
| >>> list(G.edges)
| []
|
| clear_edges(self)
| Remove all edges from the graph without altering nodes.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.clear_edges()
| >>> list(G.nodes)
| [0, 1, 2, 3]
| >>> list(G.edges)
| []
|
| degree = <functools.cached_property object>
| A DegreeView for the Graph as G.degree or G.degree().
|
| The node degree is the number of edges adjacent to the node.
| The weighted node degree is the sum of the edge weights for
| edges incident to that node.
|
| This object provides an iterator for (node, degree) as well as
| lookup for the degree for a single node.
|
| Parameters
| ----------
| nbunch : single node, container, or all nodes (default= all nodes)
| The view will only report edges incident to these nodes.
|
| weight : string or None, optional (default=None)
| The name of an edge attribute that holds the numerical value used
| as a weight. If None, then each edge has weight 1.
| The degree is the sum of the edge weights adjacent to the node.
|
| Returns
| -------
| DegreeView or int
| If multiple nodes are requested (the default), returns a `DegreeView`
| mapping nodes to their degree.
| If a single node is requested, returns the degree of the node as an integer.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.degree[0] # node 0 has degree 1
| 1
| >>> list(G.degree([0, 1, 2]))
| [(0, 1), (1, 2), (2, 2)]
|
| edge_subgraph(self, edges)
| Returns the subgraph induced by the specified edges.
|
| The induced subgraph contains each edge in `edges` and each
| node incident to any one of those edges.
|
| Parameters
| ----------
| edges : iterable
| An iterable of edges in this graph.
|
| Returns
| -------
| G : Graph
| An edge-induced subgraph of this graph with the same edge
| attributes.
|
| Notes
| -----
| The graph, edge, and node attributes in the returned subgraph
| view are references to the corresponding attributes in the original
| graph. The view is read-only.
|
| To create a full graph version of the subgraph with its own copy
| of the edge or node attributes, use::
|
| G.edge_subgraph(edges).copy()
|
| Examples
| --------
| >>> G = nx.path_graph(5)
| >>> H = G.edge_subgraph([(0, 1), (3, 4)])
| >>> list(H.nodes)
| [0, 1, 3, 4]
| >>> list(H.edges)
| [(0, 1), (3, 4)]
|
| edges = <functools.cached_property object>
| An EdgeView of the Graph as G.edges or G.edges().
|
| edges(self, nbunch=None, data=False, default=None)
|
| The EdgeView provides set-like operations on the edge-tuples
| as well as edge attribute lookup. When called, it also provides
| an EdgeDataView object which allows control of access to edge
| attributes (but does not provide set-like operations).
| Hence, `G.edges[u, v]['color']` provides the value of the color
| attribute for edge `(u, v)` while
| `for (u, v, c) in G.edges.data('color', default='red'):`
| iterates through all the edges yielding the color attribute
| with default `'red'` if no color attribute exists.
|
| Parameters
| ----------
| nbunch : single node, container, or all nodes (default= all nodes)
| The view will only report edges from these nodes.
| data : string or bool, optional (default=False)
| The edge attribute returned in 3-tuple (u, v, ddict[data]).
| If True, return edge attribute dict in 3-tuple (u, v, ddict).
| If False, return 2-tuple (u, v).
| default : value, optional (default=None)
| Value used for edges that don't have the requested attribute.
| Only relevant if data is not True or False.
|
| Returns
| -------
| edges : EdgeView
| A view of edge attributes, usually it iterates over (u, v)
| or (u, v, d) tuples of edges, but can also be used for
| attribute lookup as `edges[u, v]['foo']`.
|
| Notes
| -----
| Nodes in nbunch that are not in the graph will be (quietly) ignored.
| For directed graphs this returns the out-edges.
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or MultiGraph, etc
| >>> G.add_edge(2, 3, weight=5)
| >>> [e for e in G.edges]
| [(0, 1), (1, 2), (2, 3)]
| >>> G.edges.data() # default data is {} (empty dict)
| EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
| >>> G.edges.data("weight", default=1)
| EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
| >>> G.edges([0, 3]) # only edges from these nodes
| EdgeDataView([(0, 1), (3, 2)])
| >>> G.edges(0) # only edges from node 0
| EdgeDataView([(0, 1)])
|
| get_edge_data(self, u, v, default=None)
| Returns the attribute dictionary associated with edge (u, v).
|
| This is identical to `G[u][v]` except the default is returned
| instead of an exception if the edge doesn't exist.
|
| Parameters
| ----------
| u, v : nodes
| default: any Python object (default=None)
| Value to return if the edge (u, v) is not found.
|
| Returns
| -------
| edge_dict : dictionary
| The edge attribute dictionary.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G[0][1]
| {}
|
| Warning: Assigning to `G[u][v]` is not permitted.
| But it is safe to assign attributes `G[u][v]['foo']`
|
| >>> G[0][1]["weight"] = 7
| >>> G[0][1]["weight"]
| 7
| >>> G[1][0]["weight"]
| 7
|
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.get_edge_data(0, 1) # default edge data is {}
| {}
| >>> e = (0, 1)
| >>> G.get_edge_data(*e) # tuple form
| {}
| >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
| 0
|
| has_edge(self, u, v)
| Returns True if the edge (u, v) is in the graph.
|
| This is the same as `v in G[u]` without KeyError exceptions.
|
| Parameters
| ----------
| u, v : nodes
| Nodes can be, for example, strings or numbers.
| Nodes must be hashable (and not None) Python objects.
|
| Returns
| -------
| edge_ind : bool
| True if edge is in the graph, False otherwise.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.has_edge(0, 1) # using two nodes
| True
| >>> e = (0, 1)
| >>> G.has_edge(*e) # e is a 2-tuple (u, v)
| True
| >>> e = (0, 1, {"weight": 7})
| >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
| True
|
| The following syntax are equivalent:
|
| >>> G.has_edge(0, 1)
| True
| >>> 1 in G[0] # though this gives KeyError if 0 not in G
| True
|
| has_node(self, n)
| Returns True if the graph contains the node n.
|
| Identical to `n in G`
|
| Parameters
| ----------
| n : node
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.has_node(0)
| True
|
| It is more readable and simpler to use
|
| >>> 0 in G
| True
|
| is_directed(self)
| Returns True if graph is directed, False otherwise.
|
| is_multigraph(self)
| Returns True if graph is a multigraph, False otherwise.
|
| nbunch_iter(self, nbunch=None)
| Returns an iterator over nodes contained in nbunch that are
| also in the graph.
|
| The nodes in nbunch are checked for membership in the graph
| and if not are silently ignored.
|
| Parameters
| ----------
| nbunch : single node, container, or all nodes (default= all nodes)
| The view will only report edges incident to these nodes.
|
| Returns
| -------
| niter : iterator
| An iterator over nodes in nbunch that are also in the graph.
| If nbunch is None, iterate over all nodes in the graph.
|
| Raises
| ------
| NetworkXError
| If nbunch is not a node or sequence of nodes.
| If a node in nbunch is not hashable.
|
| See Also
| --------
| Graph.__iter__
|
| Notes
| -----
| When nbunch is an iterator, the returned iterator yields values
| directly from nbunch, becoming exhausted when nbunch is exhausted.
|
| To test whether nbunch is a single node, one can use
| "if nbunch in self:", even after processing with this routine.
|
| If nbunch is not a node or a (possibly empty) sequence/iterator
| or None, a :exc:`NetworkXError` is raised. Also, if any object in
| nbunch is not hashable, a :exc:`NetworkXError` is raised.
|
| neighbors(self, n)
| Returns an iterator over all neighbors of node n.
|
| This is identical to `iter(G[n])`
|
| Parameters
| ----------
| n : node
| A node in the graph
|
| Returns
| -------
| neighbors : iterator
| An iterator over all neighbors of node n
|
| Raises
| ------
| NetworkXError
| If the node n is not in the graph.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> [n for n in G.neighbors(0)]
| [1]
|
| Notes
| -----
| Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
|
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.add_edge("a", "b", weight=7)
| >>> G["a"]
| AtlasView({'b': {'weight': 7}})
| >>> G = nx.path_graph(4)
| >>> [n for n in G[0]]
| [1]
|
| nodes = <functools.cached_property object>
| A NodeView of the Graph as G.nodes or G.nodes().
|
| Can be used as `G.nodes` for data lookup and for set-like operations.
| Can also be used as `G.nodes(data='color', default=None)` to return a
| NodeDataView which reports specific node data but no set operations.
| It presents a dict-like interface as well with `G.nodes.items()`
| iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
| providing the value of the `foo` attribute for node `3`. In addition,
| a view `G.nodes.data('foo')` provides a dict-like interface to the
| `foo` attribute of each node. `G.nodes.data('foo', default=1)`
| provides a default for nodes that do not have attribute `foo`.
|
| Parameters
| ----------
| data : string or bool, optional (default=False)
| The node attribute returned in 2-tuple (n, ddict[data]).
| If True, return entire node attribute dict as (n, ddict).
| If False, return just the nodes n.
|
| default : value, optional (default=None)
| Value used for nodes that don't have the requested attribute.
| Only relevant if data is not True or False.
|
| Returns
| -------
| NodeView
| Allows set-like operations over the nodes as well as node
| attribute dict lookup and calling to get a NodeDataView.
| A NodeDataView iterates over `(n, data)` and has no set operations.
| A NodeView iterates over `n` and includes set operations.
|
| When called, if data is False, an iterator over nodes.
| Otherwise an iterator of 2-tuples (node, attribute value)
| where the attribute is specified in `data`.
| If data is True then the attribute becomes the
| entire data dictionary.
|
| Notes
| -----
| If your node data is not needed, it is simpler and equivalent
| to use the expression ``for n in G``, or ``list(G)``.
|
| Examples
| --------
| There are two simple ways of getting a list of all nodes in the graph:
|
| >>> G = nx.path_graph(3)
| >>> list(G.nodes)
| [0, 1, 2]
| >>> list(G)
| [0, 1, 2]
|
| To get the node data along with the nodes:
|
| >>> G.add_node(1, time="5pm")
| >>> G.nodes[0]["foo"] = "bar"
| >>> list(G.nodes(data=True))
| [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
| >>> list(G.nodes.data())
| [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
|
| >>> list(G.nodes(data="foo"))
| [(0, 'bar'), (1, None), (2, None)]
| >>> list(G.nodes.data("foo"))
| [(0, 'bar'), (1, None), (2, None)]
|
| >>> list(G.nodes(data="time"))
| [(0, None), (1, '5pm'), (2, None)]
| >>> list(G.nodes.data("time"))
| [(0, None), (1, '5pm'), (2, None)]
|
| >>> list(G.nodes(data="time", default="Not Available"))
| [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
| >>> list(G.nodes.data("time", default="Not Available"))
| [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
|
| If some of your nodes have an attribute and the rest are assumed
| to have a default attribute value you can create a dictionary
| from node/attribute pairs using the `default` keyword argument
| to guarantee the value is never None::
|
| >>> G = nx.Graph()
| >>> G.add_node(0)
| >>> G.add_node(1, weight=2)
| >>> G.add_node(2, weight=3)
| >>> dict(G.nodes(data="weight", default=1))
| {0: 1, 1: 2, 2: 3}
|
| number_of_edges(self, u=None, v=None)
| Returns the number of edges between two nodes.
|
| Parameters
| ----------
| u, v : nodes, optional (default=all edges)
| If u and v are specified, return the number of edges between
| u and v. Otherwise return the total number of all edges.
|
| Returns
| -------
| nedges : int
| The number of edges in the graph. If nodes `u` and `v` are
| specified return the number of edges between those nodes. If
| the graph is directed, this only returns the number of edges
| from `u` to `v`.
|
| See Also
| --------
| size
|
| Examples
| --------
| For undirected graphs, this method counts the total number of
| edges in the graph:
|
| >>> G = nx.path_graph(4)
| >>> G.number_of_edges()
| 3
|
| If you specify two nodes, this counts the total number of edges
| joining the two nodes:
|
| >>> G.number_of_edges(0, 1)
| 1
|
| For directed graphs, this method can count the total number of
| directed edges from `u` to `v`:
|
| >>> G = nx.DiGraph()
| >>> G.add_edge(0, 1)
| >>> G.add_edge(1, 0)
| >>> G.number_of_edges(0, 1)
| 1
|
| number_of_nodes(self)
| Returns the number of nodes in the graph.
|
| Returns
| -------
| nnodes : int
| The number of nodes in the graph.
|
| See Also
| --------
| order: identical method
| __len__: identical method
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.number_of_nodes()
| 3
|
| order(self)
| Returns the number of nodes in the graph.
|
| Returns
| -------
| nnodes : int
| The number of nodes in the graph.
|
| See Also
| --------
| number_of_nodes: identical method
| __len__: identical method
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.order()
| 3
|
| remove_edge(self, u, v)
| Remove the edge between u and v.
|
| Parameters
| ----------
| u, v : nodes
| Remove the edge between nodes u and v.
|
| Raises
| ------
| NetworkXError
| If there is not an edge between u and v.
|
| See Also
| --------
| remove_edges_from : remove a collection of edges
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, etc
| >>> G.remove_edge(0, 1)
| >>> e = (1, 2)
| >>> G.remove_edge(*e) # unpacks e from an edge tuple
| >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
| >>> G.remove_edge(*e[:2]) # select first part of edge tuple
|
| remove_edges_from(self, ebunch)
| Remove all edges specified in ebunch.
|
| Parameters
| ----------
| ebunch: list or container of edge tuples
| Each edge given in the list or container will be removed
| from the graph. The edges can be:
|
| - 2-tuples (u, v) edge between u and v.
| - 3-tuples (u, v, k) where k is ignored.
|
| See Also
| --------
| remove_edge : remove a single edge
|
| Notes
| -----
| Will fail silently if an edge in ebunch is not in the graph.
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> ebunch = [(1, 2), (2, 3)]
| >>> G.remove_edges_from(ebunch)
|
| remove_node(self, n)
| Remove node n.
|
| Removes the node n and all adjacent edges.
| Attempting to remove a nonexistent node will raise an exception.
|
| Parameters
| ----------
| n : node
| A node in the graph
|
| Raises
| ------
| NetworkXError
| If n is not in the graph.
|
| See Also
| --------
| remove_nodes_from
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> list(G.edges)
| [(0, 1), (1, 2)]
| >>> G.remove_node(1)
| >>> list(G.edges)
| []
|
| remove_nodes_from(self, nodes)
| Remove multiple nodes.
|
| Parameters
| ----------
| nodes : iterable container
| A container of nodes (list, dict, set, etc.). If a node
| in the container is not in the graph it is silently
| ignored.
|
| See Also
| --------
| remove_node
|
| Notes
| -----
| When removing nodes from an iterator over the graph you are changing,
| a `RuntimeError` will be raised with message:
| `RuntimeError: dictionary changed size during iteration`. This
| happens when the graph's underlying dictionary is modified during
| iteration. To avoid this error, evaluate the iterator into a separate
| object, e.g. by using `list(iterator_of_nodes)`, and pass this
| object to `G.remove_nodes_from`.
|
| Examples
| --------
| >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> e = list(G.nodes)
| >>> e
| [0, 1, 2]
| >>> G.remove_nodes_from(e)
| >>> list(G.nodes)
| []
|
| Evaluate an iterator over a graph if using it to modify the same graph
|
| >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
| >>> # this command will fail, as the graph's dict is modified during iteration
| >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
| >>> # this command will work, since the dictionary underlying graph is not modified
| >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
|
| size(self, weight=None)
| Returns the number of edges or total of all edge weights.
|
| Parameters
| ----------
| weight : string or None, optional (default=None)
| The edge attribute that holds the numerical value used
| as a weight. If None, then each edge has weight 1.
|
| Returns
| -------
| size : numeric
| The number of edges or
| (if weight keyword is provided) the total weight sum.
|
| If weight is None, returns an int. Otherwise a float
| (or more general numeric if the weights are more general).
|
| See Also
| --------
| number_of_edges
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.size()
| 3
|
| >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> G.add_edge("a", "b", weight=2)
| >>> G.add_edge("b", "c", weight=4)
| >>> G.size()
| 2
| >>> G.size(weight="weight")
| 6.0
|
| subgraph(self, nodes)
| Returns a SubGraph view of the subgraph induced on `nodes`.
|
| The induced subgraph of the graph contains the nodes in `nodes`
| and the edges between those nodes.
|
| Parameters
| ----------
| nodes : list, iterable
| A container of nodes which will be iterated through once.
|
| Returns
| -------
| G : SubGraph View
| A subgraph view of the graph. The graph structure cannot be
| changed but node/edge attributes can and are shared with the
| original graph.
|
| Notes
| -----
| The graph, edge and node attributes are shared with the original graph.
| Changes to the graph structure is ruled out by the view, but changes
| to attributes are reflected in the original graph.
|
| To create a subgraph with its own copy of the edge/node attributes use:
| G.subgraph(nodes).copy()
|
| For an inplace reduction of a graph to a subgraph you can remove nodes:
| G.remove_nodes_from([n for n in G if n not in set(nodes)])
|
| Subgraph views are sometimes NOT what you want. In most cases where
| you want to do more than simply look at the induced edges, it makes
| more sense to just create the subgraph as its own graph with code like:
|
| ::
|
| # Create a subgraph SG based on a (possibly multigraph) G
| SG = G.__class__()
| SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
| if SG.is_multigraph():
| SG.add_edges_from(
| (n, nbr, key, d)
| for n, nbrs in G.adj.items()
| if n in largest_wcc
| for nbr, keydict in nbrs.items()
| if nbr in largest_wcc
| for key, d in keydict.items()
| )
| else:
| SG.add_edges_from(
| (n, nbr, d)
| for n, nbrs in G.adj.items()
| if n in largest_wcc
| for nbr, d in nbrs.items()
| if nbr in largest_wcc
| )
| SG.graph.update(G.graph)
|
| Examples
| --------
| >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
| >>> H = G.subgraph([0, 1, 2])
| >>> list(H.edges)
| [(0, 1), (1, 2)]
|
| to_directed(self, as_view=False)
| Returns a directed representation of the graph.
|
| Returns
| -------
| G : DiGraph
| A directed graph with the same name, same nodes, and with
| each edge (u, v, data) replaced by two directed edges
| (u, v, data) and (v, u, data).
|
| Notes
| -----
| This returns a "deepcopy" of the edge, node, and
| graph attributes which attempts to completely copy
| all of the data and references.
|
| This is in contrast to the similar D=DiGraph(G) which returns a
| shallow copy of the data.
|
| See the Python copy module for more information on shallow
| and deep copies, https://docs.python.org/3/library/copy.html.
|
| Warning: If you have subclassed Graph to use dict-like objects
| in the data structure, those changes do not transfer to the
| DiGraph created by this method.
|
| Examples
| --------
| >>> G = nx.Graph() # or MultiGraph, etc
| >>> G.add_edge(0, 1)
| >>> H = G.to_directed()
| >>> list(H.edges)
| [(0, 1), (1, 0)]
|
| If already directed, return a (deep) copy
|
| >>> G = nx.DiGraph() # or MultiDiGraph, etc
| >>> G.add_edge(0, 1)
| >>> H = G.to_directed()
| >>> list(H.edges)
| [(0, 1)]
|
| to_directed_class(self)
| Returns the class to use for empty directed copies.
|
| If you subclass the base classes, use this to designate
| what directed class to use for `to_directed()` copies.
|
| to_undirected(self, as_view=False)
| Returns an undirected copy of the graph.
|
| Parameters
| ----------
| as_view : bool (optional, default=False)
| If True return a view of the original undirected graph.
|
| Returns
| -------
| G : Graph/MultiGraph
| A deepcopy of the graph.
|
| See Also
| --------
| Graph, copy, add_edge, add_edges_from
|
| Notes
| -----
| This returns a "deepcopy" of the edge, node, and
| graph attributes which attempts to completely copy
| all of the data and references.
|
| This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
| shallow copy of the data.
|
| See the Python copy module for more information on shallow
| and deep copies, https://docs.python.org/3/library/copy.html.
|
| Warning: If you have subclassed DiGraph to use dict-like objects
| in the data structure, those changes do not transfer to the
| Graph created by this method.
|
| Examples
| --------
| >>> G = nx.path_graph(2) # or MultiGraph, etc
| >>> H = G.to_directed()
| >>> list(H.edges)
| [(0, 1), (1, 0)]
| >>> G2 = H.to_undirected()
| >>> list(G2.edges)
| [(0, 1)]
|
| to_undirected_class(self)
| Returns the class to use for empty undirected copies.
|
| If you subclass the base classes, use this to designate
| what directed class to use for `to_directed()` copies.
|
| update(self, edges=None, nodes=None)
| Update the graph using nodes/edges/graphs as input.
|
| Like dict.update, this method takes a graph as input, adding the
| graph's nodes and edges to this graph. It can also take two inputs:
| edges and nodes. Finally it can take either edges or nodes.
| To specify only nodes the keyword `nodes` must be used.
|
| The collections of edges and nodes are treated similarly to
| the add_edges_from/add_nodes_from methods. When iterated, they
| should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
|
| Parameters
| ----------
| edges : Graph object, collection of edges, or None
| The first parameter can be a graph or some edges. If it has
| attributes `nodes` and `edges`, then it is taken to be a
| Graph-like object and those attributes are used as collections
| of nodes and edges to be added to the graph.
| If the first parameter does not have those attributes, it is
| treated as a collection of edges and added to the graph.
| If the first argument is None, no edges are added.
| nodes : collection of nodes, or None
| The second parameter is treated as a collection of nodes
| to be added to the graph unless it is None.
| If `edges is None` and `nodes is None` an exception is raised.
| If the first parameter is a Graph, then `nodes` is ignored.
|
| Examples
| --------
| >>> G = nx.path_graph(5)
| >>> G.update(nx.complete_graph(range(4, 10)))
| >>> from itertools import combinations
| >>> edges = (
| ... (u, v, {"power": u * v})
| ... for u, v in combinations(range(10, 20), 2)
| ... if u * v < 225
| ... )
| >>> nodes = [1000] # for singleton, use a container
| >>> G.update(edges, nodes)
|
| Notes
| -----
| It you want to update the graph using an adjacency structure
| it is straightforward to obtain the edges/nodes from adjacency.
| The following examples provide common cases, your adjacency may
| be slightly different and require tweaks of these examples::
|
| >>> # dict-of-set/list/tuple
| >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
| >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
| >>> G.update(edges=e, nodes=adj)
|
| >>> DG = nx.DiGraph()
| >>> # dict-of-dict-of-attribute
| >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
| >>> e = [
| ... (u, v, {"weight": d})
| ... for u, nbrs in adj.items()
| ... for v, d in nbrs.items()
| ... ]
| >>> DG.update(edges=e, nodes=adj)
|
| >>> # dict-of-dict-of-dict
| >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
| >>> e = [
| ... (u, v, {"weight": d})
| ... for u, nbrs in adj.items()
| ... for v, d in nbrs.items()
| ... ]
| >>> DG.update(edges=e, nodes=adj)
|
| >>> # predecessor adjacency (dict-of-set)
| >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
| >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
|
| >>> # MultiGraph dict-of-dict-of-dict-of-attribute
| >>> MDG = nx.MultiDiGraph()
| >>> adj = {
| ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
| ... 3: {2: {0: {"weight": 0.7}}},
| ... }
| >>> e = [
| ... (u, v, ekey, d)
| ... for u, nbrs in adj.items()
| ... for v, keydict in nbrs.items()
| ... for ekey, d in keydict.items()
| ... ]
| >>> MDG.update(edges=e)
|
| See Also
| --------
| add_edges_from: add multiple edges to a graph
| add_nodes_from: add multiple nodes to a graph
|
| ----------------------------------------------------------------------
| Data descriptors inherited from networkx.classes.graph.Graph:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| name
| String identifier of the graph.
|
| This graph attribute appears in the attribute dict G.graph
| keyed by the string `"name"`. as well as an attribute (technically
| a property) `G.name`. This is entirely user controlled.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from networkx.classes.graph.Graph:
|
| __networkx_backend__ = 'networkx'
|
| adjlist_inner_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
|
| adjlist_outer_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
|
| edge_attr_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
|
| graph_attr_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
|
| node_attr_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
|
| node_dict_factory = <class 'dict'>
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
FUNCTIONS
central_pixel(graph, nodes=None, shape=None, partition_size=100)
Find the pixel with the highest closeness centrality.
Closeness centrality is the inverse of the total sum of shortest distances
from a node to every other node.
Parameters
----------
graph : scipy.sparse.csr_array or scipy.sparse.csr_matrix
The sparse representation of the graph.
nodes : array of int
The raveled index of each node in graph in the image. If not provided,
the returned value will be the index in the input graph.
shape : tuple of int
The shape of the image in which the nodes are embedded. If provided,
the returned coordinates are a NumPy multi-index of the same
dimensionality as the input shape. Otherwise, the returned coordinate
is the raveled index provided in `nodes`.
partition_size : int
This function computes the shortest path distance between every pair
of nodes in the graph. This can result in a very large (N*N) matrix.
As a simple performance tweak, the distance values are computed in
lots of `partition_size`, resulting in a memory requirement of only
partition_size*N.
Returns
-------
position : int or tuple of int
If shape is given, the coordinate of the central pixel in the image.
Otherwise, the raveled index of that pixel.
distances : array of float
The total sum of distances from each node to each other reachable
node.
cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True, max_edge=1.0, *, rng=None)
Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image's labels and its similarity RAG, recursively perform
a 2-way normalized cut on it. All nodes belonging to a subgraph
that cannot be cut further are assigned a unique label in the
output.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. A subgraph won't be further subdivided if the
value of the N-cut exceeds `thresh`.
num_cuts : int
The number or N-cuts to perform before determining the optimal one.
in_place : bool
If set, modifies `rag` in place. For each node `n` the function will
set a new attribute ``rag.nodes[n]['ncut label']``.
max_edge : float, optional
The maximum possible value of an edge in the RAG. This corresponds to
an edge between identical regions. This is used to put self
edges in the RAG.
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
The `rng` is used to determine the starting point
of `scipy.sparse.linalg.eigsh`.
Returns
-------
out : ndarray
The new labeled array.
Examples
--------
>>> from skimage import data, segmentation, graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels, mode='similarity')
>>> new_labels = graph.cut_normalized(labels, rag)
References
----------
.. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation",
Pattern Analysis and Machine Intelligence,
IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
cut_threshold(labels, rag, thresh, in_place=True)
Combine regions separated by weight less than threshold.
Given an image's labels and its RAG, output new labels by
combining regions whose nodes are separated by a weight less
than the given threshold.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. Regions connected by edges with smaller weights are
combined.
in_place : bool
If set, modifies `rag` in place. The function will remove the edges
with weights less that `thresh`. If set to `False` the function
makes a copy of `rag` before proceeding.
Returns
-------
out : ndarray
The new labelled array.
Examples
--------
>>> from skimage import data, segmentation, graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
>>> new_labels = graph.cut_threshold(labels, rag, 10)
References
----------
.. [1] Alain Tremeau and Philippe Colantoni
"Regions Adjacency Graph Applied To Color Image Segmentation"
:DOI:`10.1109/83.841950`
merge_hierarchical(labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func)
Perform hierarchical merging of a RAG.
Greedily merges the most similar pair of nodes until no edges lower than
`thresh` remain.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The Region Adjacency Graph.
thresh : float
Regions connected by an edge with weight smaller than `thresh` are
merged.
rag_copy : bool
If set, the RAG copied before modifying.
in_place_merge : bool
If set, the nodes are merged in place. Otherwise, a new node is
created for each merge..
merge_func : callable
This function is called before merging two nodes. For the RAG `graph`
while merging `src` and `dst`, it is called as follows
``merge_func(graph, src, dst)``.
weight_func : callable
The function to compute the new weights of the nodes adjacent to the
merged node. This is directly supplied as the argument `weight_func`
to `merge_nodes`.
Returns
-------
out : ndarray
The new labeled array.
pixel_graph(image, *, mask=None, edge_function=None, connectivity=1, spacing=None, sparse_type='matrix')
Create an adjacency graph of pixels in an image.
Pixels where the mask is True are nodes in the returned graph, and they are
connected by edges to their neighbors according to the connectivity
parameter. By default, the *value* of an edge when a mask is given, or when
the image is itself the mask, is the Euclidean distance between the pixels.
However, if an int- or float-valued image is given with no mask, the value
of the edges is the absolute difference in intensity between adjacent
pixels, weighted by the Euclidean distance.
Parameters
----------
image : array
The input image. If the image is of type bool, it will be used as the
mask as well.
mask : array of bool
Which pixels to use. If None, the graph for the whole image is used.
edge_function : callable
A function taking an array of pixel values, and an array of neighbor
pixel values, and an array of distances, and returning a value for the
edge. If no function is given, the value of an edge is just the
distance.
connectivity : int
The square connectivity of the pixel neighborhood: the number of
orthogonal steps allowed to consider a pixel a neighbor. See
`scipy.ndimage.generate_binary_structure` for details.
spacing : tuple of float
The spacing between pixels along each axis.
sparse_type : {"matrix", "array"}, optional
The return type of `graph`, either `scipy.sparse.csr_array` or
`scipy.sparse.csr_matrix` (default).
Returns
-------
graph : scipy.sparse.csr_matrix or scipy.sparse.csr_array
A sparse adjacency matrix in which entry (i, j) is 1 if nodes i and j
are neighbors, 0 otherwise. Depending on `sparse_type`, this can be
returned as a `scipy.sparse.csr_array`.
nodes : array of int
The nodes of the graph. These correspond to the raveled indices of the
nonzero pixels in the mask.
rag_boundary(labels, edge_map, connectivity=2)
Comouter RAG based on region boundaries
Given an image's initial segmentation and its edge map this method
constructs the corresponding Region Adjacency Graph (RAG). Each node in the
RAG represents a set of pixels within the image with the same label in
`labels`. The weight between two adjacent regions is the average value
in `edge_map` along their boundary.
labels : ndarray
The labelled image.
edge_map : ndarray
This should have the same shape as that of `labels`. For all pixels
along the boundary between 2 adjacent regions, the average value of the
corresponding pixels in `edge_map` is the edge weight between them.
connectivity : int, optional
Pixels with a squared distance less than `connectivity` from each other
are considered adjacent. It can range from 1 to `labels.ndim`. Its
behavior is the same as `connectivity` parameter in
`scipy.ndimage.generate_binary_structure`.
Examples
--------
>>> from skimage import data, segmentation, filters, color, graph
>>> img = data.chelsea()
>>> labels = segmentation.slic(img)
>>> edge_map = filters.sobel(color.rgb2gray(img))
>>> rag = graph.rag_boundary(labels, edge_map)
rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0)
Compute the Region Adjacency Graph using mean colors.
Given an image and its initial segmentation, this method constructs the
corresponding Region Adjacency Graph (RAG). Each node in the RAG
represents a set of pixels within `image` with the same label in `labels`.
The weight between two adjacent regions represents how similar or
dissimilar two regions are depending on the `mode` parameter.
Parameters
----------
image : ndarray, shape(M, N[, ..., P], 3)
Input image.
labels : ndarray, shape(M, N[, ..., P])
The labelled image. This should have one dimension less than
`image`. If `image` has dimensions `(M, N, 3)` `labels` should have
dimensions `(M, N)`.
connectivity : int, optional
Pixels with a squared distance less than `connectivity` from each other
are considered adjacent. It can range from 1 to `labels.ndim`. Its
behavior is the same as `connectivity` parameter in
``scipy.ndimage.generate_binary_structure``.
mode : {'distance', 'similarity'}, optional
The strategy to assign edge weights.
'distance' : The weight between two adjacent regions is the
:math:`|c_1 - c_2|`, where :math:`c_1` and :math:`c_2` are the mean
colors of the two regions. It represents the Euclidean distance in
their average color.
'similarity' : The weight between two adjacent is
:math:`e^{-d^2/sigma}` where :math:`d=|c_1 - c_2|`, where
:math:`c_1` and :math:`c_2` are the mean colors of the two regions.
It represents how similar two regions are.
sigma : float, optional
Used for computation when `mode` is "similarity". It governs how
close to each other two colors should be, for their corresponding edge
weight to be significant. A very large value of `sigma` could make
any two colors behave as though they were similar.
Returns
-------
out : RAG
The region adjacency graph.
Examples
--------
>>> from skimage import data, segmentation, graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
References
----------
.. [1] Alain Tremeau and Philippe Colantoni
"Regions Adjacency Graph Applied To Color Image Segmentation"
:DOI:`10.1109/83.841950`
route_through_array(array, start, end, fully_connected=True, geometric=True)
Simple example of how to use the MCP and MCP_Geometric classes.
See the MCP and MCP_Geometric class documentation for explanation of the
path-finding algorithm.
Parameters
----------
array : ndarray
Array of costs.
start : iterable
n-d index into `array` defining the starting point
end : iterable
n-d index into `array` defining the end point
fully_connected : bool (optional)
If True, diagonal moves are permitted, if False, only axial moves.
geometric : bool (optional)
If True, the MCP_Geometric class is used to calculate costs, if False,
the MCP base class is used. See the class documentation for
an explanation of the differences between MCP and MCP_Geometric.
Returns
-------
path : list
List of n-d index tuples defining the path from `start` to `end`.
cost : float
Cost of the path. If `geometric` is False, the cost of the path is
the sum of the values of `array` along the path. If `geometric` is
True, a finer computation is made (see the documentation of the
MCP_Geometric class).
See Also
--------
MCP, MCP_Geometric
Examples
--------
>>> import numpy as np
>>> from skimage.graph import route_through_array
>>>
>>> image = np.array([[1, 3], [10, 12]])
>>> image
array([[ 1, 3],
[10, 12]])
>>> # Forbid diagonal steps
>>> route_through_array(image, [0, 0], [1, 1], fully_connected=False)
([(0, 0), (0, 1), (1, 1)], 9.5)
>>> # Now allow diagonal steps: the path goes directly from start to end
>>> route_through_array(image, [0, 0], [1, 1])
([(0, 0), (1, 1)], 9.19238815542512)
>>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12)
>>> route_through_array(image, [0, 0], [1, 1], fully_connected=False,
... geometric=False)
([(0, 0), (0, 1), (1, 1)], 16.0)
>>> # Larger array where we display the path that is selected
>>> image = np.arange((36)).reshape((6, 6))
>>> image
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]])
>>> # Find the path with lowest cost
>>> indices, weight = route_through_array(image, (0, 0), (5, 5))
>>> indices = np.stack(indices, axis=-1)
>>> path = np.zeros_like(image)
>>> path[indices[0], indices[1]] = 1
>>> path
array([[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1]])
shortest_path(arr, reach=1, axis=-1, output_indexlist=False)
Find the shortest path through an n-d array from one side to another.
Parameters
----------
arr : ndarray of float64
reach : int, optional
By default (``reach = 1``), the shortest path can only move
one row up or down for every step it moves forward (i.e.,
the path gradient is limited to 1). `reach` defines the
number of elements that can be skipped along each non-axis
dimension at each step.
axis : int, optional
The axis along which the path must always move forward (default -1)
output_indexlist : bool, optional
See return value `p` for explanation.
Returns
-------
p : iterable of int
For each step along `axis`, the coordinate of the shortest path.
If `output_indexlist` is True, then the path is returned as a list of
n-d tuples that index into `arr`. If False, then the path is returned
as an array listing the coordinates of the path along the non-axis
dimensions for each step along the axis dimension. That is,
`p.shape == (arr.shape[axis], arr.ndim-1)` except that p is squeezed
before returning so if `arr.ndim == 2`, then
`p.shape == (arr.shape[axis],)`
cost : float
Cost of path. This is the absolute sum of all the
differences along the path.
show_rag(labels, rag, image, border_color='black', edge_width=1.5, edge_cmap='magma', img_cmap='bone', in_place=True, ax=None)
Show a Region Adjacency Graph on an image.
Given a labelled image and its corresponding RAG, show the nodes and edges
of the RAG on the image with the specified colors. Edges are displayed between
the centroid of the 2 adjacent regions in the image.
Parameters
----------
labels : ndarray, shape (M, N)
The labelled image.
rag : RAG
The Region Adjacency Graph.
image : ndarray, shape (M, N[, 3])
Input image. If `colormap` is `None`, the image should be in RGB
format.
border_color : color spec, optional
Color with which the borders between regions are drawn.
edge_width : float, optional
The thickness with which the RAG edges are drawn.
edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional
Any matplotlib colormap with which the edges are drawn.
img_cmap : :py:class:`matplotlib.colors.Colormap`, optional
Any matplotlib colormap with which the image is draw. If set to `None`
the image is drawn as it is.
in_place : bool, optional
If set, the RAG is modified in place. For each node `n` the function
will set a new attribute ``rag.nodes[n]['centroid']``.
ax : :py:class:`matplotlib.axes.Axes`, optional
The axes to draw on. If not specified, new axes are created and drawn
on.
Returns
-------
lc : :py:class:`matplotlib.collections.LineCollection`
A collection of lines that represent the edges of the graph. It can be
passed to the :meth:`matplotlib.figure.Figure.colorbar` function.
Examples
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('matplotlib')
>>> from skimage import data, segmentation, graph
>>> import matplotlib.pyplot as plt
>>>
>>> img = data.coffee()
>>> labels = segmentation.slic(img)
>>> g = graph.rag_mean_color(img, labels)
>>> lc = graph.show_rag(labels, g, img)
>>> cbar = plt.colorbar(lc)
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\graph\__init__.py
scikit-image.io
Python Library Documentation: package skimage.io in skimage
NAME
skimage.io - Reading and saving of images and videos.
PACKAGE CONTENTS
_image_stack
_io
_plugins (package)
collection
manage_plugins
sift
tests (package)
util
CLASSES
builtins.object
skimage.io.collection.ImageCollection
skimage.io.collection.MultiImage
class ImageCollection(builtins.object)
| ImageCollection(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)
|
| Load and manage a collection of image files.
|
| Parameters
| ----------
| load_pattern : str or list of str
| Pattern string or list of strings to load. The filename path can be
| absolute or relative.
| conserve_memory : bool, optional
| If True, :class:`skimage.io.ImageCollection` does not keep more than one in
| memory at a specific time. Otherwise, images will be cached once they are loaded.
|
| Other parameters
| ----------------
| load_func : callable
| ``imread`` by default. See Notes below.
| **load_func_kwargs : dict
| Any other keyword arguments are passed to `load_func`.
|
| Attributes
| ----------
| files : list of str
| If a pattern string is given for `load_pattern`, this attribute
| stores the expanded file list. Otherwise, this is equal to
| `load_pattern`.
|
| Notes
| -----
| Note that files are always returned in alphanumerical order. Also note that slicing
| returns a new :class:`skimage.io.ImageCollection`, *not* a view into the data.
|
| ImageCollection image loading can be customized through
| `load_func`. For an ImageCollection ``ic``, ``ic[5]`` calls
| ``load_func(load_pattern[5])`` to load that image.
|
| For example, here is an ImageCollection that, for each video provided,
| loads every second frame::
|
| import imageio.v3 as iio3
| import itertools
|
| def vidread_step(f, step):
| vid = iio3.imiter(f)
| return list(itertools.islice(vid, None, None, step)
|
| video_file = 'no_time_for_that_tiny.gif'
| ic = ImageCollection(video_file, load_func=vidread_step, step=2)
|
| ic # is an ImageCollection object of length 1 because 1 video is provided
|
| x = ic[0]
| x[5] # the 10th frame of the first video
|
| Alternatively, if `load_func` is provided and `load_pattern` is a
| sequence, an :class:`skimage.io.ImageCollection` of corresponding length will
| be created, and the individual images will be loaded by calling `load_func` with the
| matching element of the `load_pattern` as its first argument. In this
| case, the elements of the sequence do not need to be names of existing
| files (or strings at all). For example, to create an :class:`skimage.io.ImageCollection`
| containing 500 images from a video::
|
| class FrameReader:
| def __init__ (self, f):
| self.f = f
| def __call__ (self, index):
| return iio3.imread(self.f, index=index)
|
| ic = ImageCollection(range(500), load_func=FrameReader('movie.mp4'))
|
| ic # is an ImageCollection object of length 500
|
| Another use of `load_func` would be to convert all images to ``uint8``::
|
| def imread_convert(f):
| return imread(f).astype(np.uint8)
|
| ic = ImageCollection('/tmp/*.png', load_func=imread_convert)
|
| Examples
| --------
| >>> import imageio.v3 as iio3
| >>> import skimage.io as io
|
| # Where your images are located
| >>> data_dir = os.path.join(os.path.dirname(__file__), '../data')
|
| >>> coll = io.ImageCollection(data_dir + '/chess*.png')
| >>> len(coll)
| 2
| >>> coll[0].shape
| (200, 200)
|
| >>> image_col = io.ImageCollection([f'{data_dir}/*.png', '{data_dir}/*.jpg'])
|
| >>> class MultiReader:
| ... def __init__ (self, f):
| ... self.f = f
| ... def __call__ (self, index):
| ... return iio3.imread(self.f, index=index)
| ...
| >>> filename = data_dir + '/no_time_for_that_tiny.gif'
| >>> ic = io.ImageCollection(range(24), load_func=MultiReader(filename))
| >>> len(image_col)
| 23
| >>> isinstance(ic[0], np.ndarray)
| True
|
| Methods defined here:
|
| __getitem__(self, n)
| Return selected image(s) in the collection.
|
| Loading is done on demand.
|
| Parameters
| ----------
| n : int or slice
| The image number to be returned, or a slice selecting the images
| and ordering to be returned in a new ImageCollection.
|
| Returns
| -------
| img : ndarray or :class:`skimage.io.ImageCollection`
| The `n`-th image in the collection, or a new ImageCollection with
| the selected images.
|
| __init__(self, load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)
| Load and manage a collection of images.
|
| __iter__(self)
| Iterate over the images.
|
| __len__(self)
| Number of images in collection.
|
| __str__(self)
| Return str(self).
|
| concatenate(self)
| Concatenate all images in the collection into an array.
|
| Returns
| -------
| ar : np.ndarray
| An array having one more dimension than the images in `self`.
|
| See Also
| --------
| skimage.io.concatenate_images
|
| Raises
| ------
| ValueError
| If images in the :class:`skimage.io.ImageCollection` do not have identical
| shapes.
|
| reload(self, n=None)
| Clear the image cache.
|
| Parameters
| ----------
| n : None or int
| Clear the cache for this image only. By default, the
| entire cache is erased.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| conserve_memory
|
| files
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class MultiImage(ImageCollection)
| MultiImage(filename, conserve_memory=True, dtype=None, **imread_kwargs)
|
| A class containing all frames from multi-frame TIFF images.
|
| Parameters
| ----------
| load_pattern : str or list of str
| Pattern glob or filenames to load. The path can be absolute or
| relative.
| conserve_memory : bool, optional
| Whether to conserve memory by only caching the frames of a single
| image. Default is True.
|
| Notes
| -----
| `MultiImage` returns a list of image-data arrays. In this
| regard, it is very similar to `ImageCollection`, but the two differ in
| their treatment of multi-frame images.
|
| For a TIFF image containing N frames of size WxH, `MultiImage` stores
| all frames of that image as a single element of shape `(N, W, H)` in the
| list. `ImageCollection` instead creates N elements of shape `(W, H)`.
|
| For an animated GIF image, `MultiImage` reads only the first frame, while
| `ImageCollection` reads all frames by default.
|
| Examples
| --------
| # Where your images are located
| >>> data_dir = os.path.join(os.path.dirname(__file__), '../data')
|
| >>> multipage_tiff = data_dir + '/multipage.tif'
| >>> multi_img = MultiImage(multipage_tiff)
| >>> len(multi_img) # multi_img contains one element
| 1
| >>> multi_img[0].shape # this element is a two-frame image of shape:
| (2, 15, 10)
|
| >>> image_col = ImageCollection(multipage_tiff)
| >>> len(image_col) # image_col contains two elements
| 2
| >>> for frame in image_col:
| ... print(frame.shape) # each element is a frame of shape (15, 10)
| ...
| (15, 10)
| (15, 10)
|
| Method resolution order:
| MultiImage
| ImageCollection
| builtins.object
|
| Methods defined here:
|
| __init__(self, filename, conserve_memory=True, dtype=None, **imread_kwargs)
| Load a multi-img.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| filename
|
| ----------------------------------------------------------------------
| Methods inherited from ImageCollection:
|
| __getitem__(self, n)
| Return selected image(s) in the collection.
|
| Loading is done on demand.
|
| Parameters
| ----------
| n : int or slice
| The image number to be returned, or a slice selecting the images
| and ordering to be returned in a new ImageCollection.
|
| Returns
| -------
| img : ndarray or :class:`skimage.io.ImageCollection`
| The `n`-th image in the collection, or a new ImageCollection with
| the selected images.
|
| __iter__(self)
| Iterate over the images.
|
| __len__(self)
| Number of images in collection.
|
| __str__(self)
| Return str(self).
|
| concatenate(self)
| Concatenate all images in the collection into an array.
|
| Returns
| -------
| ar : np.ndarray
| An array having one more dimension than the images in `self`.
|
| See Also
| --------
| skimage.io.concatenate_images
|
| Raises
| ------
| ValueError
| If images in the :class:`skimage.io.ImageCollection` do not have identical
| shapes.
|
| reload(self, n=None)
| Clear the image cache.
|
| Parameters
| ----------
| n : None or int
| Clear the cache for this image only. By default, the
| entire cache is erased.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ImageCollection:
|
| conserve_memory
|
| files
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ImageCollection:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
__getattr__(name)
concatenate_images(ic)
Concatenate all images in the image collection into an array.
Parameters
----------
ic : an iterable of images
The images to be concatenated.
Returns
-------
array_cat : ndarray
An array having one more dimension than the images in `ic`.
See Also
--------
ImageCollection.concatenate
MultiImage.concatenate
Raises
------
ValueError
If images in `ic` don't have identical shapes.
Notes
-----
``concatenate_images`` receives any iterable object containing images,
including ImageCollection and MultiImage, and returns a NumPy array.
imread(fname, as_gray=False, plugin=<DEPRECATED>, **plugin_args)
Load an image from file.
Parameters
----------
fname : str or pathlib.Path
Image file name, e.g. ``test.jpg`` or URL.
as_gray : bool, optional
If True, convert color images to gray-scale (64-bit floats).
Images that are already in gray-scale format are not converted.
Other Parameters
----------------
plugin_args : DEPRECATED
The plugin infrastructure is deprecated.
Returns
-------
img_array : ndarray
The different color bands/channels are stored in the
third dimension, such that a gray-image is MxN, an
RGB-image MxNx3 and an RGBA-image MxNx4.
imread_collection(load_pattern, conserve_memory=True, plugin=<DEPRECATED>, **plugin_args)
Load a collection of images.
Parameters
----------
load_pattern : str or list
List of objects to load. These are usually filenames, but may
vary depending on the currently active plugin. See :class:`ImageCollection`
for the default behaviour of this parameter.
conserve_memory : bool, optional
If True, never keep more than one in memory at a specific
time. Otherwise, images will be cached once they are loaded.
Returns
-------
ic : :class:`ImageCollection`
Collection of images.
Other Parameters
----------------
plugin_args : DEPRECATED
The plugin infrastructure is deprecated.
imread_collection_wrapper(imread)
imsave(fname, arr, plugin=<DEPRECATED>, *, check_contrast=True, **plugin_args)
Save an image to file.
Parameters
----------
fname : str or pathlib.Path
Target filename.
arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4)
Image data.
check_contrast : bool, optional
Check for low contrast and print warning (default: True).
Other Parameters
----------------
plugin_args : DEPRECATED
The plugin infrastructure is deprecated.
load_sift(f)
Read SIFT or SURF features from externally generated file.
This routine reads SIFT or SURF files generated by binary utilities from
http://people.cs.ubc.ca/~lowe/keypoints/ and
http://www.vision.ee.ethz.ch/~surf/.
This routine *does not* generate SIFT/SURF features from an image. These
algorithms are patent encumbered. Please use :obj:`skimage.feature.CENSURE`
instead.
Parameters
----------
filelike : string or open file
Input file generated by the feature detectors from
http://people.cs.ubc.ca/~lowe/keypoints/ or
http://www.vision.ee.ethz.ch/~surf/ .
mode : {'SIFT', 'SURF'}, optional
Kind of descriptor used to generate `filelike`.
Returns
-------
data : record array with fields
- row: int
row position of feature
- column: int
column position of feature
- scale: float
feature scale
- orientation: float
feature orientation
- data: array
feature values
load_surf(f)
Read SIFT or SURF features from externally generated file.
This routine reads SIFT or SURF files generated by binary utilities from
http://people.cs.ubc.ca/~lowe/keypoints/ and
http://www.vision.ee.ethz.ch/~surf/.
This routine *does not* generate SIFT/SURF features from an image. These
algorithms are patent encumbered. Please use :obj:`skimage.feature.CENSURE`
instead.
Parameters
----------
filelike : string or open file
Input file generated by the feature detectors from
http://people.cs.ubc.ca/~lowe/keypoints/ or
http://www.vision.ee.ethz.ch/~surf/ .
mode : {'SIFT', 'SURF'}, optional
Kind of descriptor used to generate `filelike`.
Returns
-------
data : record array with fields
- row: int
row position of feature
- column: int
column position of feature
- scale: float
feature scale
- orientation: float
feature orientation
- data: array
feature values
pop()
Pop an image from the shared image stack.
Returns
-------
img : ndarray
Image popped from the stack.
push(img)
Push an image onto the shared image stack.
Parameters
----------
img : ndarray
Image to push.
DATA
__all__ = ['concatenate_images', 'imread', 'imread_collection', 'imrea...
__warningregistry__ = {'version': 84}
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\io\__init__.py
scikit-image.measure
Python Library Documentation: package skimage.measure in skimage
NAME
skimage.measure - Measurement of image properties, e.g., region properties, contours.
PACKAGE CONTENTS
_blur_effect
_ccomp
_colocalization
_find_contours
_find_contours_cy
_label
_marching_cubes_lewiner
_marching_cubes_lewiner_cy
_marching_cubes_lewiner_luts
_moments
_moments_analytical
_moments_cy
_pnpoly
_polygon
_regionprops
_regionprops_utils
block
entropy
fit
pnpoly
profile
tests (package)
CLASSES
skimage.measure.fit.BaseModel(builtins.object)
skimage.measure.fit.CircleModel
skimage.measure.fit.EllipseModel
skimage.measure.fit.LineModelND
class CircleModel(BaseModel)
| Total least squares estimator for 2D circles.
|
| The functional model of the circle is::
|
| r**2 = (x - xc)**2 + (y - yc)**2
|
| This estimator minimizes the squared distances from all points to the
| circle::
|
| min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) }
|
| A minimum number of 3 points is required to solve for the parameters.
|
| Attributes
| ----------
| params : tuple
| Circle model parameters in the following order `xc`, `yc`, `r`.
|
| Notes
| -----
| The estimation is carried out using a 2D version of the spherical
| estimation given in [1]_.
|
| References
| ----------
| .. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models
| for pvc-coated polyester via inverse bubble inflation.
| Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87.
| https://hdl.handle.net/10019.1/98627
|
| Examples
| --------
| >>> t = np.linspace(0, 2 * np.pi, 25)
| >>> xy = CircleModel().predict_xy(t, params=(2, 3, 4))
| >>> model = CircleModel()
| >>> model.estimate(xy)
| True
| >>> tuple(np.round(model.params, 5))
| (2.0, 3.0, 4.0)
| >>> res = model.residuals(xy)
| >>> np.abs(np.round(res, 9))
| array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
| 0., 0., 0., 0., 0., 0., 0., 0.])
|
| Method resolution order:
| CircleModel
| BaseModel
| builtins.object
|
| Methods defined here:
|
| estimate(self, data)
| Estimate circle model from data using total least squares.
|
| Parameters
| ----------
| data : (N, 2) array
| N points with ``(x, y)`` coordinates, respectively.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| predict_xy(self, t, params=None)
| Predict x- and y-coordinates using the estimated model.
|
| Parameters
| ----------
| t : array
| Angles in circle in radians. Angles start to count from positive
| x-axis to positive y-axis in a right-handed system.
| params : (3,) array, optional
| Optional custom parameter set.
|
| Returns
| -------
| xy : (..., 2) array
| Predicted x- and y-coordinates.
|
| residuals(self, data)
| Determine residuals of data to model.
|
| For each point the shortest distance to the circle is returned.
|
| Parameters
| ----------
| data : (N, 2) array
| N points with ``(x, y)`` coordinates, respectively.
|
| Returns
| -------
| residuals : (N,) array
| Residual for each data point.
|
| ----------------------------------------------------------------------
| Methods inherited from BaseModel:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class EllipseModel(BaseModel)
| Total least squares estimator for 2D ellipses.
|
| The functional model of the ellipse is::
|
| xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t)
| yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t)
| d = sqrt((x - xt)**2 + (y - yt)**2)
|
| where ``(xt, yt)`` is the closest point on the ellipse to ``(x, y)``. Thus
| d is the shortest distance from the point to the ellipse.
|
| The estimator is based on a least squares minimization. The optimal
| solution is computed directly, no iterations are required. This leads
| to a simple, stable and robust fitting method.
|
| The ``params`` attribute contains the parameters in the following order::
|
| xc, yc, a, b, theta
|
| Attributes
| ----------
| params : tuple
| Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`,
| `theta`.
|
| Examples
| --------
|
| >>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25),
| ... params=(10, 15, 8, 4, np.deg2rad(30)))
| >>> ellipse = EllipseModel()
| >>> ellipse.estimate(xy)
| True
| >>> np.round(ellipse.params, 2)
| array([10. , 15. , 8. , 4. , 0.52])
| >>> np.round(abs(ellipse.residuals(xy)), 5)
| array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
| 0., 0., 0., 0., 0., 0., 0., 0.])
|
| Method resolution order:
| EllipseModel
| BaseModel
| builtins.object
|
| Methods defined here:
|
| estimate(self, data)
| Estimate ellipse model from data using total least squares.
|
| Parameters
| ----------
| data : (N, 2) array
| N points with ``(x, y)`` coordinates, respectively.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
|
| References
| ----------
| .. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares
| fitting of ellipses". In Proc. 6th International Conference in
| Central Europe on Computer Graphics and Visualization.
| WSCG (Vol. 98, pp. 125-132).
|
| predict_xy(self, t, params=None)
| Predict x- and y-coordinates using the estimated model.
|
| Parameters
| ----------
| t : array
| Angles in circle in radians. Angles start to count from positive
| x-axis to positive y-axis in a right-handed system.
| params : (5,) array, optional
| Optional custom parameter set.
|
| Returns
| -------
| xy : (..., 2) array
| Predicted x- and y-coordinates.
|
| residuals(self, data)
| Determine residuals of data to model.
|
| For each point the shortest distance to the ellipse is returned.
|
| Parameters
| ----------
| data : (N, 2) array
| N points with ``(x, y)`` coordinates, respectively.
|
| Returns
| -------
| residuals : (N,) array
| Residual for each data point.
|
| ----------------------------------------------------------------------
| Methods inherited from BaseModel:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class LineModelND(BaseModel)
| Total least squares estimator for N-dimensional lines.
|
| In contrast to ordinary least squares line estimation, this estimator
| minimizes the orthogonal distances of points to the estimated line.
|
| Lines are defined by a point (origin) and a unit vector (direction)
| according to the following vector equation::
|
| X = origin + lambda * direction
|
| Attributes
| ----------
| params : tuple
| Line model parameters in the following order `origin`, `direction`.
|
| Examples
| --------
| >>> x = np.linspace(1, 2, 25)
| >>> y = 1.5 * x + 3
| >>> lm = LineModelND()
| >>> lm.estimate(np.stack([x, y], axis=-1))
| True
| >>> tuple(np.round(lm.params, 5))
| (array([1.5 , 5.25]), array([0.5547 , 0.83205]))
| >>> res = lm.residuals(np.stack([x, y], axis=-1))
| >>> np.abs(np.round(res, 9))
| array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
| 0., 0., 0., 0., 0., 0., 0., 0.])
| >>> np.round(lm.predict_y(x[:5]), 3)
| array([4.5 , 4.562, 4.625, 4.688, 4.75 ])
| >>> np.round(lm.predict_x(y[:5]), 3)
| array([1. , 1.042, 1.083, 1.125, 1.167])
|
| Method resolution order:
| LineModelND
| BaseModel
| builtins.object
|
| Methods defined here:
|
| estimate(self, data)
| Estimate line model from data.
|
| This minimizes the sum of shortest (orthogonal) distances
| from the given data points to the estimated line.
|
| Parameters
| ----------
| data : (N, dim) array
| N points in a space of dimensionality dim >= 2.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| predict(self, x, axis=0, params=None)
| Predict intersection of the estimated line model with a hyperplane
| orthogonal to a given axis.
|
| Parameters
| ----------
| x : (n, 1) array
| Coordinates along an axis.
| axis : int
| Axis orthogonal to the hyperplane intersecting the line.
| params : (2,) array, optional
| Optional custom parameter set in the form (`origin`, `direction`).
|
| Returns
| -------
| data : (n, m) array
| Predicted coordinates.
|
| Raises
| ------
| ValueError
| If the line is parallel to the given axis.
|
| predict_x(self, y, params=None)
| Predict x-coordinates for 2D lines using the estimated model.
|
| Alias for::
|
| predict(y, axis=1)[:, 0]
|
| Parameters
| ----------
| y : array
| y-coordinates.
| params : (2,) array, optional
| Optional custom parameter set in the form (`origin`, `direction`).
|
| Returns
| -------
| x : array
| Predicted x-coordinates.
|
| predict_y(self, x, params=None)
| Predict y-coordinates for 2D lines using the estimated model.
|
| Alias for::
|
| predict(x, axis=0)[:, 1]
|
| Parameters
| ----------
| x : array
| x-coordinates.
| params : (2,) array, optional
| Optional custom parameter set in the form (`origin`, `direction`).
|
| Returns
| -------
| y : array
| Predicted y-coordinates.
|
| residuals(self, data, params=None)
| Determine residuals of data to model.
|
| For each point, the shortest (orthogonal) distance to the line is
| returned. It is obtained by projecting the data onto the line.
|
| Parameters
| ----------
| data : (N, dim) array
| N points in a space of dimension dim.
| params : (2,) array, optional
| Optional custom parameter set in the form (`origin`, `direction`).
|
| Returns
| -------
| residuals : (N,) array
| Residual for each data point.
|
| ----------------------------------------------------------------------
| Methods inherited from BaseModel:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
approximate_polygon(coords, tolerance)
Approximate a polygonal chain with the specified tolerance.
It is based on the Douglas-Peucker algorithm.
Note that the approximated polygon is always within the convex hull of the
original polygon.
Parameters
----------
coords : (K, 2) array
Coordinate array.
tolerance : float
Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array
is returned.
Returns
-------
coords : (L, 2) array
Approximated polygonal chain where L <= K.
References
----------
.. [1] https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
block_reduce(image, block_size=2, func=<function sum at 0x00000253FF24EE70>, cval=0, func_kwargs=None)
Downsample image by applying function `func` to local blocks.
This function is useful for max and mean pooling, for example.
Parameters
----------
image : (M[, ...]) ndarray
N-dimensional input image.
block_size : array_like or int
Array containing down-sampling integer factor along each axis.
Default block_size is 2.
func : callable
Function object which is used to calculate the return value for each
local block. This function must implement an ``axis`` parameter.
Primary functions are ``numpy.sum``, ``numpy.min``, ``numpy.max``,
``numpy.mean`` and ``numpy.median``. See also `func_kwargs`.
cval : float
Constant padding value if image is not perfectly divisible by the
block size.
func_kwargs : dict
Keyword arguments passed to `func`. Notably useful for passing dtype
argument to ``np.mean``. Takes dictionary of inputs, e.g.:
``func_kwargs={'dtype': np.float16})``.
Returns
-------
image : ndarray
Down-sampled image with same number of dimensions as input image.
Examples
--------
>>> from skimage.measure import block_reduce
>>> image = np.arange(3*3*4).reshape(3, 3, 4)
>>> image # doctest: +NORMALIZE_WHITESPACE
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]],
[[24, 25, 26, 27],
[28, 29, 30, 31],
[32, 33, 34, 35]]])
>>> block_reduce(image, block_size=(3, 3, 1), func=np.mean)
array([[[16., 17., 18., 19.]]])
>>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=np.max)
>>> image_max1 # doctest: +NORMALIZE_WHITESPACE
array([[[11]],
[[23]],
[[35]]])
>>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max)
>>> image_max2 # doctest: +NORMALIZE_WHITESPACE
array([[[27],
[31],
[35]]])
blur_effect(image, h_size=11, channel_axis=None, reduce_func=<function max at 0x00000253FF24FEF0>)
Compute a metric that indicates the strength of blur in an image
(0 for no blur, 1 for maximal blur).
Parameters
----------
image : ndarray
RGB or grayscale nD image. The input image is converted to grayscale
before computing the blur metric.
h_size : int, optional
Size of the re-blurring filter.
channel_axis : int or None, optional
If None, the image is assumed to be grayscale (single-channel).
Otherwise, this parameter indicates which axis of the array
corresponds to color channels.
reduce_func : callable, optional
Function used to calculate the aggregation of blur metrics along all
axes. If set to None, the entire list is returned, where the i-th
element is the blur metric along the i-th axis.
Returns
-------
blur : float (0 to 1) or list of floats
Blur metric: by default, the maximum of blur metrics along all axes.
Notes
-----
`h_size` must keep the same value in order to compare results between
images. Most of the time, the default size (11) is enough. This means that
the metric can clearly discriminate blur up to an average 11x11 filter; if
blur is higher, the metric still gives good results but its values tend
towards an asymptote.
References
----------
.. [1] Frederique Crete, Thierry Dolmiere, Patricia Ladret, and Marina
Nicolas "The blur effect: perception and estimation with a new
no-reference perceptual blur metric" Proc. SPIE 6492, Human Vision and
Electronic Imaging XII, 64920I (2007)
https://hal.archives-ouvertes.fr/hal-00232709
:DOI:`10.1117/12.702790`
centroid(image, *, spacing=None)
Return the (weighted) centroid of an image.
Parameters
----------
image : array
The input image.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
center : tuple of float, length ``image.ndim``
The centroid of the (nonzero) pixels in ``image``.
Examples
--------
>>> image = np.zeros((20, 20), dtype=np.float64)
>>> image[13:17, 13:17] = 0.5
>>> image[10:12, 10:12] = 1
>>> centroid(image)
array([13.16666667, 13.16666667])
euler_number(image, connectivity=None)
Calculate the Euler characteristic in binary image.
For 2D objects, the Euler number is the number of objects minus the number
of holes. For 3D objects, the Euler number is obtained as the number of
objects plus the number of holes, minus the number of tunnels, or loops.
Parameters
----------
image: (M, N[, P]) ndarray
Input image. If image is not binary, all values greater than zero
are considered as the object.
connectivity : int, optional
Maximum number of orthogonal hops to consider a pixel/voxel
as a neighbor.
Accepted values are ranging from 1 to input.ndim. If ``None``, a full
connectivity of ``input.ndim`` is used.
4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2,
respectively).
6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3,
respectively). Connectivity 2 is not defined.
Returns
-------
euler_number : int
Euler characteristic of the set of all objects in the image.
Notes
-----
The Euler characteristic is an integer number that describes the
topology of the set of all objects in the input image. If object is
4-connected, then background is 8-connected, and conversely.
The computation of the Euler characteristic is based on an integral
geometry formula in discretized space. In practice, a neighborhood
configuration is constructed, and a LUT is applied for each
configuration. The coefficients used are the ones of Ohser et al.
It can be useful to compute the Euler characteristic for several
connectivities. A large relative difference between results
for different connectivities suggests that the image resolution
(with respect to the size of objects and holes) is too low.
References
----------
.. [1] S. Rivollier. Analyse d’image geometrique et morphometrique par
diagrammes de forme et voisinages adaptatifs generaux. PhD thesis,
2010. Ecole Nationale Superieure des Mines de Saint-Etienne.
https://tel.archives-ouvertes.fr/tel-00560838
.. [2] Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of
Discretized Sets - On the Choice of Adjacency in Homogeneous
Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed
Matter. Lecture Notes in Physics, vol 600. Springer, Berlin,
Heidelberg.
Examples
--------
>>> import numpy as np
>>> SAMPLE = np.zeros((100,100,100));
>>> SAMPLE[40:60, 40:60, 40:60]=1
>>> euler_number(SAMPLE) # doctest: +ELLIPSIS
1...
>>> SAMPLE[45:55,45:55,45:55] = 0;
>>> euler_number(SAMPLE) # doctest: +ELLIPSIS
2...
>>> SAMPLE = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
... [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0],
... [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],
... [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]])
>>> euler_number(SAMPLE) # doctest:
0
>>> euler_number(SAMPLE, connectivity=1) # doctest:
2
find_contours(image, level=None, fully_connected='low', positive_orientation='low', *, mask=None)
Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute the iso-valued contours of
the input 2D array for a particular level value. Array values are linearly
interpolated to provide better precision for the output contours.
Parameters
----------
image : (M, N) ndarray of double
Input image in which to find contours.
level : float, optional
Value along which to find contours in the array. By default, the level
is set to (max(image) + min(image)) / 2
.. versionchanged:: 0.18
This parameter is now optional.
fully_connected : str, {'low', 'high'}
Indicates whether array elements below the given level value are to be
considered fully-connected (and hence elements above the value will
only be face connected), or vice-versa. (See notes below for details.)
positive_orientation : str, {'low', 'high'}
Indicates whether the output contours will produce positively-oriented
polygons around islands of low- or high-valued elements. If 'low' then
contours will wind counter-clockwise around elements below the
iso-value. Alternately, this means that low-valued elements are always
on the left of the contour. (See below for details.)
mask : (M, N) ndarray of bool or None
A boolean mask, True where we want to draw contours.
Note that NaN values are always excluded from the considered region
(``mask`` is set to ``False`` wherever ``array`` is ``NaN``).
Returns
-------
contours : list of (K, 2) ndarrays
Each contour is a ndarray of ``(row, column)`` coordinates along the contour.
See Also
--------
skimage.measure.marching_cubes
Notes
-----
The marching squares algorithm is a special case of the marching cubes
algorithm [1]_. A simple explanation is available here:
https://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html
There is a single ambiguous case in the marching squares algorithm: when
a given ``2 x 2``-element square has two high-valued and two low-valued
elements, each pair diagonally adjacent. (Where high- and low-valued is
with respect to the contour value sought.) In this case, either the
high-valued elements can be 'connected together' via a thin isthmus that
separates the low-valued elements, or vice-versa. When elements are
connected together across a diagonal, they are considered 'fully
connected' (also known as 'face+vertex-connected' or '8-connected'). Only
high-valued or low-valued elements can be fully-connected, the other set
will be considered as 'face-connected' or '4-connected'. By default,
low-valued elements are considered fully-connected; this can be altered
with the 'fully_connected' parameter.
Output contours are not guaranteed to be closed: contours which intersect
the array edge or a masked-off region (either where mask is False or where
array is NaN) will be left open. All other contours will be closed. (The
closed-ness of a contours can be tested by checking whether the beginning
point is the same as the end point.)
Contours are oriented. By default, array values lower than the contour
value are to the left of the contour and values greater than the contour
value are to the right. This means that contours will wind
counter-clockwise (i.e. in 'positive orientation') around islands of
low-valued pixels. This behavior can be altered with the
'positive_orientation' parameter.
The order of the contours in the output list is determined by the position
of the smallest ``x,y`` (in lexicographical order) coordinate in the
contour. This is a side effect of how the input array is traversed, but
can be relied upon.
.. warning::
Array coordinates/values are assumed to refer to the *center* of the
array element. Take a simple example input: ``[0, 1]``. The interpolated
position of 0.5 in this array is midway between the 0-element (at
``x=0``) and the 1-element (at ``x=1``), and thus would fall at
``x=0.5``.
This means that to find reasonable contours, it is best to find contours
midway between the expected "light" and "dark" values. In particular,
given a binarized array, *do not* choose to find contours at the low or
high value of the array. This will often yield degenerate contours,
especially around structures that are a single array element wide. Instead,
choose a middle value, as above.
References
----------
.. [1] Lorensen, William and Harvey E. Cline. Marching Cubes: A High
Resolution 3D Surface Construction Algorithm. Computer Graphics
(SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170).
:DOI:`10.1145/37401.37422`
Examples
--------
>>> a = np.zeros((3, 3))
>>> a[0, 0] = 1
>>> a
array([[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>> find_contours(a, 0.5)
[array([[0. , 0.5],
[0.5, 0. ]])]
grid_points_in_poly(shape, verts, binarize=True)
Test whether points on a specified grid are inside a polygon.
For each ``(r, c)`` coordinate on a grid, i.e. ``(0, 0)``, ``(0, 1)`` etc.,
test whether that point lies inside a polygon.
You can control the output type with the `binarize` flag. Please refer to its
documentation for further details.
Parameters
----------
shape : tuple (M, N)
Shape of the grid.
verts : (V, 2) array
Specify the V vertices of the polygon, sorted either clockwise
or anti-clockwise. The first point may (but does not need to be)
duplicated.
binarize: bool
If `True`, the output of the function is a boolean mask.
Otherwise, it is a labeled array. The labels are:
O - outside, 1 - inside, 2 - vertex, 3 - edge.
See Also
--------
points_in_poly
Returns
-------
mask : (M, N) ndarray
If `binarize` is True, the output is a boolean mask. True means the
corresponding pixel falls inside the polygon.
If `binarize` is False, the output is a labeled array, with pixels
having a label between 0 and 3. The meaning of the values is:
O - outside, 1 - inside, 2 - vertex, 3 - edge.
inertia_tensor(image, mu=None, *, spacing=None)
Compute the inertia tensor of the input image.
Parameters
----------
image : array
The input image.
mu : array, optional
The pre-computed central moments of ``image``. The inertia tensor
computation requires the central moments of the image. If an
application requires both the central moments and the inertia tensor
(for example, `skimage.measure.regionprops`), then it is more
efficient to pre-compute them and pass them to the inertia tensor
call.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
T : array, shape ``(image.ndim, image.ndim)``
The inertia tensor of the input image. :math:`T_{i, j}` contains
the covariance of image intensity along axes :math:`i` and :math:`j`.
References
----------
.. [1] https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor
.. [2] Bernd Jähne. Spatio-Temporal Image Processing: Theory and
Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993.
inertia_tensor_eigvals(image, mu=None, T=None, *, spacing=None)
Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along
the image axes. (See `inertia_tensor`.) The relative magnitude of the
eigenvalues of the tensor is thus a measure of the elongation of a
(bright) object in the image.
Parameters
----------
image : array
The input image.
mu : array, optional
The pre-computed central moments of ``image``.
T : array, shape ``(image.ndim, image.ndim)``
The pre-computed inertia tensor. If ``T`` is given, ``mu`` and
``image`` are ignored.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
eigvals : list of float, length ``image.ndim``
The eigenvalues of the inertia tensor of ``image``, in descending
order.
Notes
-----
Computing the eigenvalues requires the inertia tensor of the input image.
This is much faster if the central moments (``mu``) are provided, or,
alternatively, one can provide the inertia tensor (``T``) directly.
intersection_coeff(image0_mask, image1_mask, mask=None)
Fraction of a channel's segmented binary mask that overlaps with a
second channel's segmented binary mask.
Parameters
----------
image0_mask : (M, N) ndarray of dtype bool
Image mask of channel A.
image1_mask : (M, N) ndarray of dtype bool
Image mask of channel B.
Must have same dimensions as `image0_mask`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0_mask` and `image1_mask` pixels within this region of
interest
mask are included in the calculation.
Must have same dimensions as `image0_mask`.
Returns
-------
Intersection coefficient, float
Fraction of `image0_mask` that overlaps with `image1_mask`.
label(label_image, background=None, return_num=False, connectivity=None)
Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value.
In 2D, they can be neighbors either in a 1- or 2-connected sense.
The value refers to the maximum number of orthogonal hops to consider a
pixel/voxel a neighbor::
1-connectivity 2-connectivity diagonal connection close-up
[ ] [ ] [ ] [ ] [ ]
| \ | / | <- hop 2
[ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ]
| / | \ hop 1
[ ] [ ] [ ] [ ]
Parameters
----------
label_image : ndarray of dtype int
Image to label.
background : int, optional
Consider all pixels with this value as background pixels, and label
them as 0. By default, 0-valued pixels are considered as background
pixels.
return_num : bool, optional
Whether to return the number of assigned labels.
connectivity : int, optional
Maximum number of orthogonal hops to consider a pixel/voxel
as a neighbor.
Accepted values are ranging from 1 to input.ndim. If ``None``, a full
connectivity of ``input.ndim`` is used.
Returns
-------
labels : ndarray of dtype int
Labeled array, where all connected regions are assigned the
same integer value.
num : int, optional
Number of labels, which equals the maximum label index and is only
returned if return_num is `True`.
See Also
--------
skimage.measure.regionprops
skimage.measure.regionprops_table
References
----------
.. [1] Christophe Fiorio and Jens Gustedt, "Two linear time Union-Find
strategies for image processing", Theoretical Computer Science
154 (1996), pp. 165-181.
.. [2] Kensheng Wu, Ekow Otoo and Arie Shoshani, "Optimizing connected
component labeling algorithms", Paper LBNL-56864, 2005,
Lawrence Berkeley National Laboratory (University of California),
http://repositories.cdlib.org/lbnl/LBNL-56864
Examples
--------
>>> import numpy as np
>>> x = np.eye(3).astype(int)
>>> print(x)
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, connectivity=1))
[[1 0 0]
[0 2 0]
[0 0 3]]
>>> print(label(x, connectivity=2))
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, background=-1))
[[1 2 2]
[2 1 2]
[2 2 1]]
>>> x = np.array([[1, 0, 0],
... [1, 1, 5],
... [0, 0, 0]])
>>> print(label(x))
[[1 0 0]
[1 1 2]
[0 0 0]]
manders_coloc_coeff(image0, image1_mask, mask=None)
Manders' colocalization coefficient between two channels.
Parameters
----------
image0 : (M, N) ndarray
Image of channel A. All pixel values should be non-negative.
image1_mask : (M, N) ndarray of dtype bool
Binary mask with segmented regions of interest in channel B.
Must have same dimensions as `image0`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0` pixel values within this region of interest mask are
included in the calculation.
Must have same dimensions as `image0`.
Returns
-------
mcc : float
Manders' colocalization coefficient.
Notes
-----
Manders' Colocalization Coefficient (MCC) is the fraction of total
intensity of a certain channel (channel A) that is within the segmented
region of a second channel (channel B) [1]_. It ranges from 0 for no
colocalisation to 1 for complete colocalization. It is also referred to
as M1 and M2.
MCC is commonly used to measure the colocalization of a particular protein
in a subceullar compartment. Typically a segmentation mask for channel B
is generated by setting a threshold that the pixel values must be above
to be included in the MCC calculation. In this implementation,
the channel B mask is provided as the argument `image1_mask`, allowing
the exact segmentation method to be decided by the user beforehand.
The implemented equation is:
.. math::
r = \frac{\sum A_{i,coloc}}{\sum A_i}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`A_{i,coloc} = A_i` if :math:`Bmask_i > 0`
:math:`Bmask_i` is the value of the :math:`i^{th}` pixel in
`mask`
MCC is sensitive to noise, with diffuse signal in the first channel
inflating its value. Images should be processed to remove out of focus and
background light before the MCC is calculated [2]_.
References
----------
.. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of
co-localization of objects in dual-colour confocal images. Journal
of Microscopy, 169: 375-382.
https://doi.org/10.1111/j.1365-2818.1993.tb03313.x
https://imagej.net/media/manders.pdf
.. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
manders_overlap_coeff(image0, image1, mask=None)
Manders' overlap coefficient
Parameters
----------
image0 : (M, N) ndarray
Image of channel A. All pixel values should be non-negative.
image1 : (M, N) ndarray
Image of channel B. All pixel values should be non-negative.
Must have same dimensions as `image0`
mask : (M, N) ndarray of dtype bool, optional
Only `image0` and `image1` pixel values within this region of interest
mask are included in the calculation.
Must have ♣same dimensions as `image0`.
Returns
-------
moc: float
Manders' Overlap Coefficient of pixel intensities between the two
images.
Notes
-----
Manders' Overlap Coefficient (MOC) is given by the equation [1]_:
.. math::
r = \frac{\sum A_i B_i}{\sqrt{\sum A_i^2 \sum B_i^2}}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`
It ranges between 0 for no colocalization and 1 for complete colocalization
of all pixels.
MOC does not take into account pixel intensities, just the fraction of
pixels that have positive values for both channels[2]_ [3]_. Its usefulness
has been criticized as it changes in response to differences in both
co-occurence and correlation and so a particular MOC value could indicate
a wide range of colocalization patterns [4]_ [5]_.
References
----------
.. [1] Manders, E.M.M., Verbeek, F.J. and Aten, J.A. (1993), Measurement of
co-localization of objects in dual-colour confocal images. Journal
of Microscopy, 169: 375-382.
https://doi.org/10.1111/j.1365-2818.1993.tb03313.x
https://imagej.net/media/manders.pdf
.. [2] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
.. [3] Bolte, S. and Cordelières, F.P. (2006), A guided tour into
subcellular colocalization analysis in light microscopy. Journal of
Microscopy, 224: 213-232.
https://doi.org/10.1111/j.1365-2818.2006.01
.. [4] Adler J, Parmryd I. (2010), Quantifying colocalization by
correlation: the Pearson correlation coefficient is
superior to the Mander's overlap coefficient. Cytometry A.
Aug;77(8):733-42.https://doi.org/10.1002/cyto.a.20896
.. [5] Adler, J, Parmryd, I. Quantifying colocalization: The case for
discarding the Manders overlap coefficient. Cytometry. 2021; 99:
910– 920. https://doi.org/10.1002/cyto.a.24336
marching_cubes(volume, level=None, *, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, method='lewiner', mask=None)
Marching cubes algorithm to find surfaces in 3d volumetric data.
In contrast with Lorensen et al. approach [2]_, Lewiner et
al. algorithm is faster, resolves ambiguities, and guarantees
topologically correct results. Therefore, this algorithm generally
a better choice.
Parameters
----------
volume : (M, N, P) ndarray
Input data volume to find isosurfaces. Will internally be
converted to float32 if necessary.
level : float, optional
Contour value to search for isosurfaces in `volume`. If not
given or None, the average of the min and max of vol is used.
spacing : length-3 tuple of floats, optional
Voxel spacing in spatial dimensions corresponding to numpy array
indexing dimensions (M, N, P) as in `volume`.
gradient_direction : string, optional
Controls if the mesh was generated from an isosurface with gradient
descent toward objects of interest (the default), or the opposite,
considering the *left-hand* rule.
The two options are:
* descent : Object was greater than exterior
* ascent : Exterior was greater than object
step_size : int, optional
Step size in voxels. Default 1. Larger steps yield faster but
coarser results. The result will always be topologically correct
though.
allow_degenerate : bool, optional
Whether to allow degenerate (i.e. zero-area) triangles in the
end-result. Default True. If False, degenerate triangles are
removed, at the cost of making the algorithm slower.
method: {'lewiner', 'lorensen'}, optional
Whether the method of Lewiner et al. or Lorensen et al. will be used.
mask : (M, N, P) array, optional
Boolean array. The marching cube algorithm will be computed only on
True elements. This will save computational time when interfaces
are located within certain region of the volume M, N, P-e.g. the top
half of the cube-and also allow to compute finite surfaces-i.e. open
surfaces that do not end at the border of the cube.
Returns
-------
verts : (V, 3) array
Spatial coordinates for V unique mesh vertices. Coordinate order
matches input `volume` (M, N, P). If ``allow_degenerate`` is set to
True, then the presence of degenerate triangles in the mesh can make
this array have duplicate vertices.
faces : (F, 3) array
Define triangular faces via referencing vertex indices from ``verts``.
This algorithm specifically outputs triangles, so each face has
exactly three indices.
normals : (V, 3) array
The normal direction at each vertex, as calculated from the
data.
values : (V,) array
Gives a measure for the maximum value of the data in the local region
near each vertex. This can be used by visualization tools to apply
a colormap to the mesh.
See Also
--------
skimage.measure.mesh_surface_area
skimage.measure.find_contours
Notes
-----
The algorithm [1]_ is an improved version of Chernyaev's Marching
Cubes 33 algorithm. It is an efficient algorithm that relies on
heavy use of lookup tables to handle the many different cases,
keeping the algorithm relatively easy. This implementation is
written in Cython, ported from Lewiner's C++ implementation.
To quantify the area of an isosurface generated by this algorithm, pass
verts and faces to `skimage.measure.mesh_surface_area`.
Regarding visualization of algorithm output, to contour a volume
named `myvolume` about the level 0.0, using the ``mayavi`` package::
>>>
>> from mayavi import mlab
>> verts, faces, _, _ = marching_cubes(myvolume, 0.0)
>> mlab.triangular_mesh([vert[0] for vert in verts],
[vert[1] for vert in verts],
[vert[2] for vert in verts],
faces)
>> mlab.show()
Similarly using the ``visvis`` package::
>>>
>> import visvis as vv
>> verts, faces, normals, values = marching_cubes(myvolume, 0.0)
>> vv.mesh(np.fliplr(verts), faces, normals, values)
>> vv.use().Run()
To reduce the number of triangles in the mesh for better performance,
see this `example
<https://docs.enthought.com/mayavi/mayavi/auto/example_julia_set_decimation.html#example-julia-set-decimation>`_
using the ``mayavi`` package.
References
----------
.. [1] Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan
Tavares. Efficient implementation of Marching Cubes' cases with
topological guarantees. Journal of Graphics Tools 8(2)
pp. 1-15 (december 2003).
:DOI:`10.1080/10867651.2003.10487582`
.. [2] Lorensen, William and Harvey E. Cline. Marching Cubes: A High
Resolution 3D Surface Construction Algorithm. Computer Graphics
(SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170).
:DOI:`10.1145/37401.37422`
mesh_surface_area(verts, faces)
Compute surface area, given vertices and triangular faces.
Parameters
----------
verts : (V, 3) array of floats
Array containing coordinates for V unique mesh vertices.
faces : (F, 3) array of ints
List of length-3 lists of integers, referencing vertex coordinates as
provided in `verts`.
Returns
-------
area : float
Surface area of mesh. Units now [coordinate units] ** 2.
Notes
-----
The arguments expected by this function are the first two outputs from
`skimage.measure.marching_cubes`. For unit correct output, ensure correct
`spacing` was passed to `skimage.measure.marching_cubes`.
This algorithm works properly only if the ``faces`` provided are all
triangles.
See Also
--------
skimage.measure.marching_cubes
moments(image, order=3, *, spacing=None)
Calculate all raw image moments up to a certain order.
The following properties can be calculated from raw image moments:
* Area as: ``M[0, 0]``.
* Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}.
Note that raw moments are neither translation, scale nor rotation
invariant.
Parameters
----------
image : (N[, ...]) double or uint8 array
Rasterized shape as image.
order : int, optional
Maximum order of moments. Default is 3.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
m : (``order + 1``, ``order + 1``) array
Raw image moments.
References
----------
.. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:
Core Algorithms. Springer-Verlag, London, 2009.
.. [2] B. Jähne. Digital Image Processing. Springer-Verlag,
Berlin-Heidelberg, 6. edition, 2005.
.. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image
Features, from Lecture notes in computer science, p. 676. Springer,
Berlin, 1993.
.. [4] https://en.wikipedia.org/wiki/Image_moment
Examples
--------
>>> image = np.zeros((20, 20), dtype=np.float64)
>>> image[13:17, 13:17] = 1
>>> M = moments(image)
>>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0])
>>> centroid
(14.5, 14.5)
moments_central(image, center=None, order=3, *, spacing=None, **kwargs)
Calculate all central image moments up to a certain order.
The center coordinates (cr, cc) can be calculated from the raw moments as:
{``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}.
Note that central moments are translation invariant but not scale and
rotation invariant.
Parameters
----------
image : (N[, ...]) double or uint8 array
Rasterized shape as image.
center : tuple of float, optional
Coordinates of the image centroid. This will be computed if it
is not provided.
order : int, optional
The maximum order of moments computed.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
mu : (``order + 1``, ``order + 1``) array
Central image moments.
References
----------
.. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:
Core Algorithms. Springer-Verlag, London, 2009.
.. [2] B. Jähne. Digital Image Processing. Springer-Verlag,
Berlin-Heidelberg, 6. edition, 2005.
.. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image
Features, from Lecture notes in computer science, p. 676. Springer,
Berlin, 1993.
.. [4] https://en.wikipedia.org/wiki/Image_moment
Examples
--------
>>> image = np.zeros((20, 20), dtype=np.float64)
>>> image[13:17, 13:17] = 1
>>> M = moments(image)
>>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0])
>>> moments_central(image, centroid)
array([[16., 0., 20., 0.],
[ 0., 0., 0., 0.],
[20., 0., 25., 0.],
[ 0., 0., 0., 0.]])
moments_coords(coords, order=3)
Calculate all raw image moments up to a certain order.
The following properties can be calculated from raw image moments:
* Area as: ``M[0, 0]``.
* Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}.
Note that raw moments are neither translation, scale, nor rotation
invariant.
Parameters
----------
coords : (N, D) double or uint8 array
Array of N points that describe an image of D dimensionality in
Cartesian space.
order : int, optional
Maximum order of moments. Default is 3.
Returns
-------
M : (``order + 1``, ``order + 1``, ...) array
Raw image moments. (D dimensions)
References
----------
.. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham
University, version 0.2, Durham, 2001.
Examples
--------
>>> coords = np.array([[row, col]
... for row in range(13, 17)
... for col in range(14, 18)], dtype=np.float64)
>>> M = moments_coords(coords)
>>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0])
>>> centroid
(14.5, 15.5)
moments_coords_central(coords, center=None, order=3)
Calculate all central image moments up to a certain order.
The following properties can be calculated from raw image moments:
* Area as: ``M[0, 0]``.
* Centroid as: {``M[1, 0] / M[0, 0]``, ``M[0, 1] / M[0, 0]``}.
Note that raw moments are neither translation, scale nor rotation
invariant.
Parameters
----------
coords : (N, D) double or uint8 array
Array of N points that describe an image of D dimensionality in
Cartesian space. A tuple of coordinates as returned by
``np.nonzero`` is also accepted as input.
center : tuple of float, optional
Coordinates of the image centroid. This will be computed if it
is not provided.
order : int, optional
Maximum order of moments. Default is 3.
Returns
-------
Mc : (``order + 1``, ``order + 1``, ...) array
Central image moments. (D dimensions)
References
----------
.. [1] Johannes Kilian. Simple Image Analysis By Moments. Durham
University, version 0.2, Durham, 2001.
Examples
--------
>>> coords = np.array([[row, col]
... for row in range(13, 17)
... for col in range(14, 18)])
>>> moments_coords_central(coords)
array([[16., 0., 20., 0.],
[ 0., 0., 0., 0.],
[20., 0., 25., 0.],
[ 0., 0., 0., 0.]])
As seen above, for symmetric objects, odd-order moments (columns 1 and 3,
rows 1 and 3) are zero when centered on the centroid, or center of mass,
of the object (the default). If we break the symmetry by adding a new
point, this no longer holds:
>>> coords2 = np.concatenate((coords, [[17, 17]]), axis=0)
>>> np.round(moments_coords_central(coords2),
... decimals=2) # doctest: +NORMALIZE_WHITESPACE
array([[17. , 0. , 22.12, -2.49],
[ 0. , 3.53, 1.73, 7.4 ],
[25.88, 6.02, 36.63, 8.83],
[ 4.15, 19.17, 14.8 , 39.6 ]])
Image moments and central image moments are equivalent (by definition)
when the center is (0, 0):
>>> np.allclose(moments_coords(coords),
... moments_coords_central(coords, (0, 0)))
True
moments_hu(nu)
Calculate Hu's set of image moments (2D-only).
Note that this set of moments is proved to be translation, scale and
rotation invariant.
Parameters
----------
nu : (M, M) array
Normalized central image moments, where M must be >= 4.
Returns
-------
nu : (7,) array
Hu's set of image moments.
References
----------
.. [1] M. K. Hu, "Visual Pattern Recognition by Moment Invariants",
IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
.. [2] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:
Core Algorithms. Springer-Verlag, London, 2009.
.. [3] B. Jähne. Digital Image Processing. Springer-Verlag,
Berlin-Heidelberg, 6. edition, 2005.
.. [4] T. H. Reiss. Recognizing Planar Objects Using Invariant Image
Features, from Lecture notes in computer science, p. 676. Springer,
Berlin, 1993.
.. [5] https://en.wikipedia.org/wiki/Image_moment
Examples
--------
>>> image = np.zeros((20, 20), dtype=np.float64)
>>> image[13:17, 13:17] = 0.5
>>> image[10:12, 10:12] = 1
>>> mu = moments_central(image)
>>> nu = moments_normalized(mu)
>>> moments_hu(nu)
array([0.74537037, 0.35116598, 0.10404918, 0.04064421, 0.00264312,
0.02408546, 0. ])
moments_normalized(mu, order=3, spacing=None)
Calculate all normalized central image moments up to a certain order.
Note that normalized central moments are translation and scale invariant
but not rotation invariant.
Parameters
----------
mu : (M[, ...], M) array
Central image moments, where M must be greater than or equal
to ``order``.
order : int, optional
Maximum order of moments. Default is 3.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
nu : (``order + 1``[, ...], ``order + 1``) array
Normalized central image moments.
References
----------
.. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:
Core Algorithms. Springer-Verlag, London, 2009.
.. [2] B. Jähne. Digital Image Processing. Springer-Verlag,
Berlin-Heidelberg, 6. edition, 2005.
.. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image
Features, from Lecture notes in computer science, p. 676. Springer,
Berlin, 1993.
.. [4] https://en.wikipedia.org/wiki/Image_moment
Examples
--------
>>> image = np.zeros((20, 20), dtype=np.float64)
>>> image[13:17, 13:17] = 1
>>> m = moments(image)
>>> centroid = (m[0, 1] / m[0, 0], m[1, 0] / m[0, 0])
>>> mu = moments_central(image, centroid)
>>> moments_normalized(mu)
array([[ nan, nan, 0.078125 , 0. ],
[ nan, 0. , 0. , 0. ],
[0.078125 , 0. , 0.00610352, 0. ],
[0. , 0. , 0. , 0. ]])
pearson_corr_coeff(image0, image1, mask=None)
Calculate Pearson's Correlation Coefficient between pixel intensities
in channels.
Parameters
----------
image0 : (M, N) ndarray
Image of channel A.
image1 : (M, N) ndarray
Image of channel 2 to be correlated with channel B.
Must have same dimensions as `image0`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0` and `image1` pixels within this region of interest mask
are included in the calculation. Must have same dimensions as `image0`.
Returns
-------
pcc : float
Pearson's correlation coefficient of the pixel intensities between
the two images, within the mask if provided.
p-value : float
Two-tailed p-value.
Notes
-----
Pearson's Correlation Coefficient (PCC) measures the linear correlation
between the pixel intensities of the two images. Its value ranges from -1
for perfect linear anti-correlation to +1 for perfect linear correlation.
The calculation of the p-value assumes that the intensities of pixels in
each input image are normally distributed.
Scipy's implementation of Pearson's correlation coefficient is used. Please
refer to it for further information and caveats [1]_.
.. math::
r = \frac{\sum (A_i - m_A_i) (B_i - m_B_i)}
{\sqrt{\sum (A_i - m_A_i)^2 \sum (B_i - m_B_i)^2}}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`,
:math:`m_A_i` is the mean of the pixel values in `image0`
:math:`m_B_i` is the mean of the pixel values in `image1`
A low PCC value does not necessarily mean that there is no correlation
between the two channel intensities, just that there is no linear
correlation. You may wish to plot the pixel intensities of each of the two
channels in a 2D scatterplot and use Spearman's rank correlation if a
non-linear correlation is visually identified [2]_. Also consider if you
are interested in correlation or co-occurence, in which case a method
involving segmentation masks (e.g. MCC or intersection coefficient) may be
more suitable [3]_ [4]_.
Providing the mask of only relevant sections of the image (e.g., cells, or
particular cellular compartments) and removing noise is important as the
PCC is sensitive to these measures [3]_ [4]_.
References
----------
.. [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html
.. [2] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html
.. [3] Dunn, K. W., Kamocka, M. M., & McDonald, J. H. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
.. [4] Bolte, S. and Cordelières, F.P. (2006), A guided tour into
subcellular colocalization analysis in light microscopy. Journal of
Microscopy, 224: 213-232.
https://doi.org/10.1111/j.1365-2818.2006.01706.x
perimeter(image, neighborhood=4)
Calculate total perimeter of all objects in binary image.
Parameters
----------
image : (M, N) ndarray
Binary input image.
neighborhood : 4 or 8, optional
Neighborhood connectivity for border pixel determination. It is used to
compute the contour. A higher neighborhood widens the border on which
the perimeter is computed.
Returns
-------
perimeter : float
Total perimeter of all objects in binary image.
References
----------
.. [1] K. Benkrid, D. Crookes. Design and FPGA Implementation of
a Perimeter Estimator. The Queen's University of Belfast.
http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc
Examples
--------
>>> from skimage import data, util
>>> from skimage.measure import label
>>> # coins image (binary)
>>> img_coins = data.coins() > 110
>>> # total perimeter of all objects in the image
>>> perimeter(img_coins, neighborhood=4) # doctest: +ELLIPSIS
7796.867...
>>> perimeter(img_coins, neighborhood=8) # doctest: +ELLIPSIS
8806.268...
perimeter_crofton(image, directions=4)
Calculate total Crofton perimeter of all objects in binary image.
Parameters
----------
image : (M, N) ndarray
Input image. If image is not binary, all values greater than zero
are considered as the object.
directions : 2 or 4, optional
Number of directions used to approximate the Crofton perimeter. By
default, 4 is used: it should be more accurate than 2.
Computation time is the same in both cases.
Returns
-------
perimeter : float
Total perimeter of all objects in binary image.
Notes
-----
This measure is based on Crofton formula [1], which is a measure from
integral geometry. It is defined for general curve length evaluation via
a double integral along all directions. In a discrete
space, 2 or 4 directions give a quite good approximation, 4 being more
accurate than 2 for more complex shapes.
Similar to :func:`~.measure.perimeter`, this function returns an
approximation of the perimeter in continuous space.
References
----------
.. [1] https://en.wikipedia.org/wiki/Crofton_formula
.. [2] S. Rivollier. Analyse d’image geometrique et morphometrique par
diagrammes de forme et voisinages adaptatifs generaux. PhD thesis,
2010.
Ecole Nationale Superieure des Mines de Saint-Etienne.
https://tel.archives-ouvertes.fr/tel-00560838
Examples
--------
>>> from skimage import data, util
>>> from skimage.measure import label
>>> # coins image (binary)
>>> img_coins = data.coins() > 110
>>> # total perimeter of all objects in the image
>>> perimeter_crofton(img_coins, directions=2) # doctest: +ELLIPSIS
8144.578...
>>> perimeter_crofton(img_coins, directions=4) # doctest: +ELLIPSIS
7837.077...
points_in_poly(points, verts)
Test whether points lie inside a polygon.
Parameters
----------
points : (K, 2) array
Input points, ``(x, y)``.
verts : (L, 2) array
Vertices of the polygon, sorted either clockwise or anti-clockwise.
The first point may (but does not need to be) duplicated.
See Also
--------
grid_points_in_poly
Returns
-------
mask : (K,) array of bool
True if corresponding point is inside the polygon.
profile_line(image, src, dst, linewidth=1, order=None, mode='reflect', cval=0.0, *, reduce_func=<function mean at 0x00000253FF250FF0>)
Return the intensity profile of an image measured along a scan line.
Parameters
----------
image : ndarray, shape (M, N[, C])
The image, either grayscale (2D array) or multichannel
(3D array, where the final axis contains the channel
information).
src : array_like, shape (2,)
The coordinates of the start point of the scan line.
dst : array_like, shape (2,)
The coordinates of the end point of the scan
line. The destination point is *included* in the profile, in
contrast to standard numpy indexing.
linewidth : int, optional
Width of the scan, perpendicular to the line
order : int in {0, 1, 2, 3, 4, 5}, optional
The order of the spline interpolation, default is 0 if
image.dtype is bool and 1 otherwise. The order has to be in
the range 0-5. See `skimage.transform.warp` for detail.
mode : {'constant', 'nearest', 'reflect', 'mirror', 'wrap'}, optional
How to compute any values falling outside of the image.
cval : float, optional
If `mode` is 'constant', what constant value to use outside the image.
reduce_func : callable, optional
Function used to calculate the aggregation of pixel values
perpendicular to the profile_line direction when `linewidth` > 1.
If set to None the unreduced array will be returned.
Returns
-------
return_value : array
The intensity profile along the scan line. The length of the profile
is the ceil of the computed length of the scan line.
Examples
--------
>>> x = np.array([[1, 1, 1, 2, 2, 2]])
>>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)])
>>> img
array([[0, 0, 0, 0, 0, 0],
[1, 1, 1, 2, 2, 2],
[1, 1, 1, 2, 2, 2],
[1, 1, 1, 2, 2, 2],
[0, 0, 0, 0, 0, 0]])
>>> profile_line(img, (2, 1), (2, 4))
array([1., 1., 2., 2.])
>>> profile_line(img, (1, 0), (1, 6), cval=4)
array([1., 1., 1., 2., 2., 2., 2.])
The destination point is included in the profile, in contrast to
standard numpy indexing.
For example:
>>> profile_line(img, (1, 0), (1, 6)) # The final point is out of bounds
array([1., 1., 1., 2., 2., 2., 2.])
>>> profile_line(img, (1, 0), (1, 5)) # This accesses the full first row
array([1., 1., 1., 2., 2., 2.])
For different reduce_func inputs:
>>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.mean)
array([0.66666667, 0.66666667, 0.66666667, 1.33333333])
>>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.max)
array([1, 1, 1, 2])
>>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sum)
array([2, 2, 2, 4])
The unreduced array will be returned when `reduce_func` is None or when
`reduce_func` acts on each pixel value individually.
>>> profile_line(img, (1, 2), (4, 2), linewidth=3, order=0,
... reduce_func=None)
array([[1, 1, 2],
[1, 1, 2],
[1, 1, 2],
[0, 0, 0]])
>>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sqrt)
array([[1. , 1. , 0. ],
[1. , 1. , 0. ],
[1. , 1. , 0. ],
[1.41421356, 1.41421356, 0. ]])
ransac(data, model_class, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_sample_num=inf, stop_residuals_sum=0, stop_probability=1, rng=None, initial_inliers=None)
Fit a model to data with the RANSAC (random sample consensus) algorithm.
RANSAC is an iterative algorithm for the robust estimation of parameters
from a subset of inliers from the complete data set. Each iteration
performs the following tasks:
1. Select `min_samples` random samples from the original data and check
whether the set of data is valid (see `is_data_valid`).
2. Estimate a model to the random subset
(`model_cls.estimate(*data[random_subset]`) and check whether the
estimated model is valid (see `is_model_valid`).
3. Classify all data as inliers or outliers by calculating the residuals
to the estimated model (`model_cls.residuals(*data)`) - all data samples
with residuals smaller than the `residual_threshold` are considered as
inliers.
4. Save estimated model as best model if number of inlier samples is
maximal. In case the current estimated model has the same number of
inliers, it is only considered as the best model if it has less sum of
residuals.
These steps are performed either a maximum number of times or until one of
the special stop criteria are met. The final model is estimated using all
inlier samples of the previously determined best model.
Parameters
----------
data : [list, tuple of] (N, ...) array
Data set to which the model is fitted, where N is the number of data
points and the remaining dimension are depending on model requirements.
If the model class requires multiple input data arrays (e.g. source and
destination coordinates of ``skimage.transform.AffineTransform``),
they can be optionally passed as tuple or list. Note, that in this case
the functions ``estimate(*data)``, ``residuals(*data)``,
``is_model_valid(model, *random_data)`` and
``is_data_valid(*random_data)`` must all take each data array as
separate arguments.
model_class : object
Object with the following object methods:
* ``success = estimate(*data)``
* ``residuals(*data)``
where `success` indicates whether the model estimation succeeded
(`True` or `None` for success, `False` for failure).
min_samples : int in range (0, N)
The minimum number of data points to fit a model to.
residual_threshold : float larger than 0
Maximum distance for a data point to be classified as an inlier.
is_data_valid : function, optional
This function is called with the randomly selected data before the
model is fitted to it: `is_data_valid(*random_data)`.
is_model_valid : function, optional
This function is called with the estimated model and the randomly
selected data: `is_model_valid(model, *random_data)`, .
max_trials : int, optional
Maximum number of iterations for random sample selection.
stop_sample_num : int, optional
Stop iteration if at least this number of inliers are found.
stop_residuals_sum : float, optional
Stop iteration if sum of residuals is less than or equal to this
threshold.
stop_probability : float in range [0, 1], optional
RANSAC iteration stops if at least one outlier-free set of the
training data is sampled with ``probability >= stop_probability``,
depending on the current best model's inlier ratio and the number
of trials. This requires to generate at least N samples (trials):
N >= log(1 - probability) / log(1 - e**m)
where the probability (confidence) is typically set to a high value
such as 0.99, e is the current fraction of inliers w.r.t. the
total number of samples, and m is the min_samples value.
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
initial_inliers : array-like of bool, shape (N,), optional
Initial samples selection for model estimation
Returns
-------
model : object
Best model with largest consensus set.
inliers : (N,) array
Boolean mask of inliers classified as ``True``.
References
----------
.. [1] "RANSAC", Wikipedia, https://en.wikipedia.org/wiki/RANSAC
Examples
--------
Generate ellipse data without tilt and add noise:
>>> t = np.linspace(0, 2 * np.pi, 50)
>>> xc, yc = 20, 30
>>> a, b = 5, 10
>>> x = xc + a * np.cos(t)
>>> y = yc + b * np.sin(t)
>>> data = np.column_stack([x, y])
>>> rng = np.random.default_rng(203560) # do not copy this value
>>> data += rng.normal(size=data.shape)
Add some faulty data:
>>> data[0] = (100, 100)
>>> data[1] = (110, 120)
>>> data[2] = (120, 130)
>>> data[3] = (140, 130)
Estimate ellipse model using all available data:
>>> model = EllipseModel()
>>> model.estimate(data)
True
>>> np.round(model.params) # doctest: +SKIP
array([ 72., 75., 77., 14., 1.])
Estimate ellipse model using RANSAC:
>>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50)
>>> abs(np.round(ransac_model.params)) # doctest: +SKIP
array([20., 30., 10., 6., 2.])
>>> inliers # doctest: +SKIP
array([False, False, False, False, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True], dtype=bool)
>>> sum(inliers) > 40
True
RANSAC can be used to robustly estimate a geometric
transformation. In this section, we also show how to use a
proportion of the total samples, rather than an absolute number.
>>> from skimage.transform import SimilarityTransform
>>> rng = np.random.default_rng()
>>> src = 100 * rng.random((50, 2))
>>> model0 = SimilarityTransform(scale=0.5, rotation=1,
... translation=(10, 20))
>>> dst = model0(src)
>>> dst[0] = (10000, 10000)
>>> dst[1] = (-100, 100)
>>> dst[2] = (50, 50)
>>> ratio = 0.5 # use half of the samples
>>> min_samples = int(ratio * len(src))
>>> model, inliers = ransac(
... (src, dst),
... SimilarityTransform,
... min_samples,
... 10,
... initial_inliers=np.ones(len(src), dtype=bool),
... ) # doctest: +SKIP
>>> inliers # doctest: +SKIP
array([False, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True])
regionprops(label_image, intensity_image=None, cache=True, *, extra_properties=None, spacing=None, offset=None)
Measure properties of labeled image regions.
Parameters
----------
label_image : (M, N[, P]) ndarray
Labeled input image. Labels with value 0 are ignored.
.. versionchanged:: 0.14.1
Previously, ``label_image`` was processed by ``numpy.squeeze`` and
so any number of singleton dimensions was allowed. This resulted in
inconsistent handling of images with singleton dimensions. To
recover the old behaviour, use
``regionprops(np.squeeze(label_image), ...)``.
intensity_image : (M, N[, P][, C]) ndarray, optional
Intensity (i.e., input) image with same size as labeled image, plus
optionally an extra dimension for multichannel data. Currently,
this extra channel dimension, if present, must be the last axis.
Default is None.
.. versionchanged:: 0.18.0
The ability to provide an extra dimension for channels was added.
cache : bool, optional
Determine whether to cache calculated properties. The computation is
much faster for cached properties, whereas the memory consumption
increases.
extra_properties : Iterable of callables
Add extra property computation functions that are not included with
skimage. The name of the property is derived from the function name,
the dtype is inferred by calling the function on a small sample.
If the name of an extra property clashes with the name of an existing
property the extra property will not be visible and a UserWarning is
issued. A property computation function must take a region mask as its
first argument. If the property requires an intensity image, it must
accept the intensity image as the second argument.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
offset : array-like of int, shape `(label_image.ndim,)`, optional
Coordinates of the origin ("top-left" corner) of the label image.
Normally this is ([0, ]0, 0), but it might be different if one wants
to obtain regionprops of subvolumes within a larger volume.
Returns
-------
properties : list of RegionProperties
Each item describes one labeled region, and can be accessed using the
attributes listed below.
Notes
-----
The following properties can be accessed as attributes or keys:
**area** : float
Area of the region i.e. number of pixels of the region scaled by pixel-area.
**area_bbox** : float
Area of the bounding box i.e. number of pixels of bounding box scaled by pixel-area.
**area_convex** : float
Area of the convex hull image, which is the smallest convex
polygon that encloses the region.
**area_filled** : float
Area of the region with all the holes filled in.
**axis_major_length** : float
The length of the major axis of the ellipse that has the same
normalized second central moments as the region.
**axis_minor_length** : float
The length of the minor axis of the ellipse that has the same
normalized second central moments as the region.
**bbox** : tuple
Bounding box ``(min_row, min_col, max_row, max_col)``.
Pixels belonging to the bounding box are in the half-open interval
``[min_row; max_row)`` and ``[min_col; max_col)``.
**centroid** : array
Centroid coordinate tuple ``(row, col)``.
**centroid_local** : array
Centroid coordinate tuple ``(row, col)``, relative to region bounding
box.
**centroid_weighted** : array
Centroid coordinate tuple ``(row, col)`` weighted with intensity
image.
**centroid_weighted_local** : array
Centroid coordinate tuple ``(row, col)``, relative to region bounding
box, weighted with intensity image.
**coords_scaled** : (K, 2) ndarray
Coordinate list ``(row, col)`` of the region scaled by ``spacing``.
**coords** : (K, 2) ndarray
Coordinate list ``(row, col)`` of the region.
**eccentricity** : float
Eccentricity of the ellipse that has the same second-moments as the
region. The eccentricity is the ratio of the focal distance
(distance between focal points) over the major axis length.
The value is in the interval [0, 1).
When it is 0, the ellipse becomes a circle.
**equivalent_diameter_area** : float
The diameter of a circle with the same area as the region.
**euler_number** : int
Euler characteristic of the set of non-zero pixels.
Computed as number of connected components subtracted by number of
holes (input.ndim connectivity). In 3D, number of connected
components plus number of holes subtracted by number of tunnels.
**extent** : float
Ratio of pixels in the region to pixels in the total bounding box.
Computed as ``area / (rows * cols)``
**feret_diameter_max** : float
Maximum Feret's diameter computed as the longest distance between
points around a region's convex hull contour as determined by
``find_contours``. [5]_
**image** : (H, J) ndarray
Sliced binary region image which has the same size as bounding box.
**image_convex** : (H, J) ndarray
Binary convex hull image which has the same size as bounding box.
**image_filled** : (H, J) ndarray
Binary region image with filled holes which has the same size as
bounding box.
**image_intensity** : ndarray
Image inside region bounding box.
**inertia_tensor** : ndarray
Inertia tensor of the region for the rotation around its mass.
**inertia_tensor_eigvals** : tuple
The eigenvalues of the inertia tensor in decreasing order.
**intensity_max** : float
Value with the greatest intensity in the region.
**intensity_mean** : float
Value with the mean intensity in the region.
**intensity_min** : float
Value with the least intensity in the region.
**intensity_std** : float
Standard deviation of the intensity in the region.
**label** : int
The label in the labeled input image.
**moments** : (3, 3) ndarray
Spatial moments up to 3rd order::
m_ij = sum{ array(row, col) * row^i * col^j }
where the sum is over the `row`, `col` coordinates of the region.
**moments_central** : (3, 3) ndarray
Central moments (translation invariant) up to 3rd order::
mu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j }
where the sum is over the `row`, `col` coordinates of the region,
and `row_c` and `col_c` are the coordinates of the region's centroid.
**moments_hu** : tuple
Hu moments (translation, scale and rotation invariant).
**moments_normalized** : (3, 3) ndarray
Normalized moments (translation and scale invariant) up to 3rd order::
nu_ij = mu_ij / m_00^[(i+j)/2 + 1]
where `m_00` is the zeroth spatial moment.
**moments_weighted** : (3, 3) ndarray
Spatial moments of intensity image up to 3rd order::
wm_ij = sum{ array(row, col) * row^i * col^j }
where the sum is over the `row`, `col` coordinates of the region.
**moments_weighted_central** : (3, 3) ndarray
Central moments (translation invariant) of intensity image up to
3rd order::
wmu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j }
where the sum is over the `row`, `col` coordinates of the region,
and `row_c` and `col_c` are the coordinates of the region's weighted
centroid.
**moments_weighted_hu** : tuple
Hu moments (translation, scale and rotation invariant) of intensity
image.
**moments_weighted_normalized** : (3, 3) ndarray
Normalized moments (translation and scale invariant) of intensity
image up to 3rd order::
wnu_ij = wmu_ij / wm_00^[(i+j)/2 + 1]
where ``wm_00`` is the zeroth spatial moment (intensity-weighted area).
**num_pixels** : int
Number of foreground pixels.
**orientation** : float
Angle between the 0th axis (rows) and the major
axis of the ellipse that has the same second moments as the region,
ranging from `-pi/2` to `pi/2` counter-clockwise.
**perimeter** : float
Perimeter of object which approximates the contour as a line
through the centers of border pixels using a 4-connectivity.
**perimeter_crofton** : float
Perimeter of object approximated by the Crofton formula in 4
directions.
**slice** : tuple of slices
A slice to extract the object from the source image.
**solidity** : float
Ratio of pixels in the region to pixels of the convex hull image.
Each region also supports iteration, so that you can do::
for prop in region:
print(prop, region[prop])
See Also
--------
label
References
----------
.. [1] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:
Core Algorithms. Springer-Verlag, London, 2009.
.. [2] B. Jähne. Digital Image Processing. Springer-Verlag,
Berlin-Heidelberg, 6. edition, 2005.
.. [3] T. H. Reiss. Recognizing Planar Objects Using Invariant Image
Features, from Lecture notes in computer science, p. 676. Springer,
Berlin, 1993.
.. [4] https://en.wikipedia.org/wiki/Image_moment
.. [5] W. Pabst, E. Gregorová. Characterization of particles and particle
systems, pp. 27-28. ICT Prague, 2007.
https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf
Examples
--------
>>> from skimage import data, util
>>> from skimage.measure import label, regionprops
>>> img = util.img_as_ubyte(data.coins()) > 110
>>> label_img = label(img, connectivity=img.ndim)
>>> props = regionprops(label_img)
>>> # centroid of first labeled object
>>> props[0].centroid
(22.72987986048314, 81.91228523446583)
>>> # centroid of first labeled object
>>> props[0]['centroid']
(22.72987986048314, 81.91228523446583)
Add custom measurements by passing functions as ``extra_properties``
>>> from skimage import data, util
>>> from skimage.measure import label, regionprops
>>> import numpy as np
>>> img = util.img_as_ubyte(data.coins()) > 110
>>> label_img = label(img, connectivity=img.ndim)
>>> def pixelcount(regionmask):
... return np.sum(regionmask)
>>> props = regionprops(label_img, extra_properties=(pixelcount,))
>>> props[0].pixelcount
7741
>>> props[1]['pixelcount']
42
regionprops_table(label_image, intensity_image=None, properties=('label', 'bbox'), *, cache=True, separator='-', extra_properties=None, spacing=None)
Compute image properties and return them as a pandas-compatible table.
The table is a dictionary mapping column names to value arrays. See Notes
section below for details.
.. versionadded:: 0.16
Parameters
----------
label_image : (M, N[, P]) ndarray
Labeled input image. Labels with value 0 are ignored.
intensity_image : (M, N[, P][, C]) ndarray, optional
Intensity (i.e., input) image with same size as labeled image, plus
optionally an extra dimension for multichannel data. The channel dimension,
if present, must be the last axis. Default is None.
.. versionchanged:: 0.18.0
The ability to provide an extra dimension for channels was added.
properties : tuple or list of str, optional
Properties that will be included in the resulting dictionary
For a list of available properties, please see :func:`regionprops`.
Users should remember to add "label" to keep track of region
identities.
cache : bool, optional
Determine whether to cache calculated properties. The computation is
much faster for cached properties, whereas the memory consumption
increases.
separator : str, optional
For non-scalar properties not listed in OBJECT_COLUMNS, each element
will appear in its own column, with the index of that element separated
from the property name by this separator. For example, the inertia
tensor of a 2D region will appear in four columns:
``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``,
and ``inertia_tensor-1-1`` (where the separator is ``-``).
Object columns are those that cannot be split in this way because the
number of columns would change depending on the object. For example,
``image`` and ``coords``.
extra_properties : Iterable of callables
Add extra property computation functions that are not included with
skimage. The name of the property is derived from the function name,
the dtype is inferred by calling the function on a small sample.
If the name of an extra property clashes with the name of an existing
property the extra property will not be visible and a UserWarning is
issued. A property computation function must take a region mask as its
first argument. If the property requires an intensity image, it must
accept the intensity image as the second argument.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
out_dict : dict
Dictionary mapping property names to an array of values of that
property, one value per region. This dictionary can be used as input to
pandas ``DataFrame`` to map property names to columns in the frame and
regions to rows. If the image has no regions,
the arrays will have length 0, but the correct type.
Notes
-----
Each column contains either a scalar property, an object property, or an
element in a multidimensional array.
Properties with scalar values for each region, such as "eccentricity", will
appear as a float or int array with that property name as key.
Multidimensional properties *of fixed size* for a given image dimension,
such as "centroid" (every centroid will have three elements in a 3D image,
no matter the region size), will be split into that many columns, with the
name {property_name}{separator}{element_num} (for 1D properties),
{property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D
properties), and so on.
For multidimensional properties that don't have a fixed size, such as
"image" (the image of a region varies in size depending on the region
size), an object array will be used, with the corresponding property name
as the key.
Examples
--------
>>> from skimage import data, util, measure
>>> image = data.coins()
>>> label_image = measure.label(image > 110, connectivity=image.ndim)
>>> props = measure.regionprops_table(label_image, image,
... properties=['label', 'inertia_tensor',
... 'inertia_tensor_eigvals'])
>>> props # doctest: +ELLIPSIS +SKIP
{'label': array([ 1, 2, ...]), ...
'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ...
...,
'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])}
The resulting dictionary can be directly passed to pandas, if installed, to
obtain a clean DataFrame:
>>> import pandas as pd # doctest: +SKIP
>>> data = pd.DataFrame(props) # doctest: +SKIP
>>> data.head() # doctest: +SKIP
label inertia_tensor-0-0 ... inertia_tensor_eigvals-1
0 1 4012.909888 ... 267.065503
1 2 8.514739 ... 2.834806
2 3 0.666667 ... 0.000000
3 4 0.000000 ... 0.000000
4 5 0.222222 ... 0.111111
[5 rows x 7 columns]
If we want to measure a feature that does not come as a built-in
property, we can define custom functions and pass them as
``extra_properties``. For example, we can create a custom function
that measures the intensity quartiles in a region:
>>> from skimage import data, util, measure
>>> import numpy as np
>>> def quartiles(regionmask, intensity):
... return np.percentile(intensity[regionmask], q=(25, 50, 75))
>>>
>>> image = data.coins()
>>> label_image = measure.label(image > 110, connectivity=image.ndim)
>>> props = measure.regionprops_table(label_image, intensity_image=image,
... properties=('label',),
... extra_properties=(quartiles,))
>>> import pandas as pd # doctest: +SKIP
>>> pd.DataFrame(props).head() # doctest: +SKIP
label quartiles-0 quartiles-1 quartiles-2
0 1 117.00 123.0 130.0
1 2 111.25 112.0 114.0
2 3 111.00 111.0 111.0
3 4 111.00 111.5 112.5
4 5 112.50 113.0 114.0
shannon_entropy(image, base=2)
Calculate the Shannon entropy of an image.
The Shannon entropy is defined as S = -sum(pk * log(pk)),
where pk are frequency/probability of pixels of value k.
Parameters
----------
image : (M, N) ndarray
Grayscale input image.
base : float, optional
The logarithmic base to use.
Returns
-------
entropy : float
Notes
-----
The returned value is measured in bits or shannon (Sh) for base=2, natural
unit (nat) for base=np.e and hartley (Hart) for base=10.
References
----------
.. [1] `https://en.wikipedia.org/wiki/Entropy_(information_theory) <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_
.. [2] https://en.wiktionary.org/wiki/Shannon_entropy
Examples
--------
>>> from skimage import data
>>> from skimage.measure import shannon_entropy
>>> shannon_entropy(data.camera())
7.231695011055706
subdivide_polygon(coords, degree=2, preserve_ends=False)
Subdivision of polygonal curves using B-Splines.
Note that the resulting curve is always within the convex hull of the
original polygon. Circular polygons stay closed after subdivision.
Parameters
----------
coords : (K, 2) array
Coordinate array.
degree : {1, 2, 3, 4, 5, 6, 7}, optional
Degree of B-Spline. Default is 2.
preserve_ends : bool, optional
Preserve first and last coordinate of non-circular polygon. Default is
False.
Returns
-------
coords : (L, 2) array
Subdivided coordinate array.
References
----------
.. [1] http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\measure\__init__.py
scikit-image.metrics
Python Library Documentation: package skimage.metrics in skimage
NAME
skimage.metrics - Metrics corresponding to images, e.g., distance metrics, similarity, etc.
PACKAGE CONTENTS
_adapted_rand_error
_contingency_table
_structural_similarity
_variation_of_information
set_metrics
simple_metrics
tests (package)
FUNCTIONS
adapted_rand_error(image_true=None, image_test=None, *, table=None, ignore_labels=(0,), alpha=0.5)
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`
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`.
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
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]))
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``.
normalized_mutual_information(image0, image1, *, bins=100)
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}{x \log x}` is the entropy.
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`
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
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
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`
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`.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\metrics\__init__.py
scikit-image.morphology
Python Library Documentation: package skimage.morphology in skimage
NAME
skimage.morphology - Morphological algorithms, e.g., closing, opening, skeletonization.
PACKAGE CONTENTS
_convex_hull
_extrema_cy
_flood_fill
_flood_fill_cy
_grayreconstruct
_max_tree
_misc_cy
_skeletonize
_skeletonize_lee_cy
_skeletonize_various_cy
_util
binary
convex_hull
extrema
footprints
gray
grayreconstruct
isotropic
max_tree
misc
tests (package)
FUNCTIONS
area_closing(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)
Perform an area closing of the image.
Area closing removes all dark structures of an image with
a surface smaller than area_threshold.
The output image is larger than or equal to the input image
for every pixel and all local minima have at least a surface of
area_threshold pixels.
Area closings are similar to morphological closings, but
they do not use a fixed footprint, but rather a deformable
one, with surface = area_threshold.
In the binary case, area closings are equivalent to
remove_small_holes; this operator is thus extended to gray-level images.
Technically, this operator is based on the max-tree representation of
the image.
Parameters
----------
image : ndarray
The input image for which the area_closing is to be calculated.
This image can be of any type.
area_threshold : unsigned int
The size parameter (number of pixels). The default value is arbitrarily
chosen to be 64.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
parent : ndarray, int64, optional
Parent image representing the max tree of the inverted image. The
value of each pixel is the index of its parent in the ravelled array.
See Note for further details.
tree_traverser : 1D array, int64, optional
The ordered pixel indices (referring to the ravelled array). The pixels
are ordered such that every pixel is preceded by its parent (except for
the root which has no parent).
Returns
-------
output : ndarray
Output image of the same shape and type as input image.
See Also
--------
skimage.morphology.area_opening
skimage.morphology.diameter_opening
skimage.morphology.diameter_closing
skimage.morphology.max_tree
skimage.morphology.remove_small_objects
skimage.morphology.remove_small_holes
References
----------
.. [1] Vincent L., Proc. "Grayscale area openings and closings,
their efficient implementation and applications",
EURASIP Workshop on Mathematical Morphology and its
Applications to Signal Processing, Barcelona, Spain, pp.22-27,
May 1993.
.. [2] Soille, P., "Morphological Image Analysis: Principles and
Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883.
:DOI:`10.1007/978-3-662-05088-0`
.. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive
Connected Operators for Image and Sequence Processing.
IEEE Transactions on Image Processing, 7(4), 555-570.
:DOI:`10.1109/83.663500`
.. [4] Najman, L., & Couprie, M. (2006). Building the component tree in
quasi-linear time. IEEE Transactions on Image Processing, 15(11),
3531-3539.
:DOI:`10.1109/TIP.2006.877518`
.. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create an image (quadratic function with a minimum in the center and
4 additional local minima.
>>> w = 12
>>> x, y = np.mgrid[0:w,0:w]
>>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2)
>>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120
>>> f[9:10,9:11] = 100; f[10,10] = 100
>>> f = f.astype(int)
We can calculate the area closing:
>>> closed = area_closing(f, 8, connectivity=1)
All small minima are removed, and the remaining minima have at least
a size of 8.
Notes
-----
If a max-tree representation (parent and tree_traverser) are given to the
function, they must be calculated from the inverted image for this
function, i.e.:
>>> P, S = max_tree(invert(f))
>>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S)
area_opening(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)
Perform an area opening of the image.
Area opening removes all bright structures of an image with
a surface smaller than area_threshold.
The output image is thus the largest image smaller than the input
for which all local maxima have at least a surface of
area_threshold pixels.
Area openings are similar to morphological openings, but
they do not use a fixed footprint, but rather a deformable
one, with surface = area_threshold. Consequently, the area_opening
with area_threshold=1 is the identity.
In the binary case, area openings are equivalent to
remove_small_objects; this operator is thus extended to gray-level images.
Technically, this operator is based on the max-tree representation of
the image.
Parameters
----------
image : ndarray
The input image for which the area_opening is to be calculated.
This image can be of any type.
area_threshold : unsigned int
The size parameter (number of pixels). The default value is arbitrarily
chosen to be 64.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
parent : ndarray, int64, optional
Parent image representing the max tree of the image. The
value of each pixel is the index of its parent in the ravelled array.
tree_traverser : 1D array, int64, optional
The ordered pixel indices (referring to the ravelled array). The pixels
are ordered such that every pixel is preceded by its parent (except for
the root which has no parent).
Returns
-------
output : ndarray
Output image of the same shape and type as the input image.
See Also
--------
skimage.morphology.area_closing
skimage.morphology.diameter_opening
skimage.morphology.diameter_closing
skimage.morphology.max_tree
skimage.morphology.remove_small_objects
skimage.morphology.remove_small_holes
References
----------
.. [1] Vincent L., Proc. "Grayscale area openings and closings,
their efficient implementation and applications",
EURASIP Workshop on Mathematical Morphology and its
Applications to Signal Processing, Barcelona, Spain, pp.22-27,
May 1993.
.. [2] Soille, P., "Morphological Image Analysis: Principles and
Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883.
:DOI:`10.1007/978-3-662-05088-0`
.. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive
Connected Operators for Image and Sequence Processing.
IEEE Transactions on Image Processing, 7(4), 555-570.
:DOI:`10.1109/83.663500`
.. [4] Najman, L., & Couprie, M. (2006). Building the component tree in
quasi-linear time. IEEE Transactions on Image Processing, 15(11),
3531-3539.
:DOI:`10.1109/TIP.2006.877518`
.. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create an image (quadratic function with a maximum in the center and
4 additional local maxima.
>>> w = 12
>>> x, y = np.mgrid[0:w,0:w]
>>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2)
>>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80
>>> f[9:10,9:11] = 100; f[10,10] = 100
>>> f = f.astype(int)
We can calculate the area opening:
>>> open = area_opening(f, 8, connectivity=1)
The peaks with a surface smaller than 8 are removed.
ball(radius, dtype=<class 'numpy.uint8'>, *, strict_radius=True, decomposition=None)
Generates a ball-shaped footprint.
This is the 3D equivalent of a disk.
A pixel is within the neighborhood if the Euclidean distance between
it and the origin is no greater than radius.
Parameters
----------
radius : float
The radius of the ball-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
strict_radius : bool, optional
If False, extend the radius by 0.5. This allows the circle to expand
further within a cube that remains of size ``2 * radius + 1`` along
each axis. This parameter is ignored if decomposition is not None.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given a result equivalent to a single, larger footprint, but with
better computational performance. For ball footprints, the sequence
decomposition is not exactly equivalent to decomposition=None.
See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
Notes
-----
The disk produced by the decomposition='sequence' mode is not identical
to that with decomposition=None. Here we extend the approach taken in [1]_
for disks to the 3D case, using 3-dimensional extensions of the "square",
"diamond" and "t-shaped" elements from that publication. All of these
elementary elements have size ``(3,) * ndim``. We numerically computed the
number of repetitions of each element that gives the closest match to the
ball computed with kwargs ``strict_radius=False, decomposition=None``.
Empirically, the equivalent composite footprint to the sequence
decomposition approaches a rhombicuboctahedron (26-faces [2]_).
References
----------
.. [1] Park, H and Chin R.T. Decomposition of structuring elements for
optimal implementation of morphological operations. In Proceedings:
1997 IEEE Workshop on Nonlinear Signal and Image Processing, London,
UK.
https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf
.. [2] https://en.wikipedia.org/wiki/Rhombicuboctahedron
binary_closing(image, footprint=None, out=None, *, mode='ignore')
Return fast binary morphological closing of an image.
This function returns the same result as grayscale closing but performs
faster for binary images.
The morphological closing on an image is defined as a dilation followed by
an erosion. Closing can remove small dark spots (i.e. "pepper") and connect
small bright cracks. This tends to "close" up (dark) gaps between (bright)
features.
Parameters
----------
image : ndarray
Binary input image.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray of bool, optional
The array to store the result of the morphology. If None,
is passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'max', 'min', 'ignore'.
If 'ignore', pixels outside the image domain are assumed to be `True`
for the erosion and `False` for the dilation, which causes them to not
influence the result. Default is 'ignore'.
.. versionadded:: 0.23
`mode` was added in 0.23.
Returns
-------
closing : ndarray of bool
The result of the morphological closing.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate a
footprint sequence of this type.
See also
--------
skimage.morphology.isotropic_closing
binary_dilation(image, footprint=None, out=None, *, mode='ignore')
Return fast binary morphological dilation of an image.
This function returns the same result as grayscale dilation but performs
faster for binary images.
Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all
pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright
regions and shrinks dark regions.
Parameters
----------
image : ndarray
Binary input image.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray of bool, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'max', 'min', 'ignore'.
If 'min' or 'ignore', pixels outside the image domain are assumed
to be `False`, which causes them to not influence the result.
Default is 'ignore'.
.. versionadded:: 0.23
`mode` was added in 0.23.
Returns
-------
dilated : ndarray of bool or uint
The result of the morphological dilation with values in
``[False, True]``.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate a
footprint sequence of this type.
For non-symmetric footprints, :func:`skimage.morphology.binary_dilation`
and :func:`skimage.morphology.dilation` produce an output that differs:
`binary_dilation` mirrors the footprint, whereas `dilation` does not.
See also
--------
skimage.morphology.isotropic_dilation
binary_erosion(image, footprint=None, out=None, *, mode='ignore')
Return fast binary morphological erosion of an image.
This function returns the same result as grayscale erosion but performs
faster for binary images.
Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all
pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright
regions and enlarges dark regions.
Parameters
----------
image : ndarray
Binary input image.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray of bool, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'max', 'min', 'ignore'.
If 'max' or 'ignore', pixels outside the image domain are assumed
to be `True`, which causes them to not influence the result.
Default is 'ignore'.
.. versionadded:: 0.23
`mode` was added in 0.23.
Returns
-------
eroded : ndarray of bool or uint
The result of the morphological erosion taking values in
``[False, True]``.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate a
footprint sequence of this type.
For even-sized footprints, :func:`skimage.morphology.erosion` and
this function produce an output that differs: one is shifted by one pixel
compared to the other.
See also
--------
skimage.morphology.isotropic_erosion
binary_opening(image, footprint=None, out=None, *, mode='ignore')
Return fast binary morphological opening of an image.
This function returns the same result as grayscale opening but performs
faster for binary images.
The morphological opening on an image is defined as an erosion followed by
a dilation. Opening can remove small bright spots (i.e. "salt") and connect
small dark cracks. This tends to "open" up (dark) gaps between (bright)
features.
Parameters
----------
image : ndarray
Binary input image.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray of bool, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'max', 'min', 'ignore'.
If 'ignore', pixels outside the image domain are assumed to be `True`
for the erosion and `False` for the dilation, which causes them to not
influence the result. Default is 'ignore'.
.. versionadded:: 0.23
`mode` was added in 0.23.
Returns
-------
opening : ndarray of bool
The result of the morphological opening.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate a
footprint sequence of this type.
See also
--------
skimage.morphology.isotropic_opening
black_tophat(image, footprint=None, out=None, *, mode='reflect', cval=0.0)
Return black top hat of an image.
The black top hat of an image is defined as its morphological closing minus
the original image. This operation returns the dark spots of the image that
are smaller than the footprint. Note that dark spots in the
original image are bright spots after the black top hat.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'. See :func:`skimage.morphology.closing`.
Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
out : array, same shape and type as `image`
The result of the morphological black top hat.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
See Also
--------
white_tophat
References
----------
.. [1] https://en.wikipedia.org/wiki/Top-hat_transform
Examples
--------
>>> # Change dark peak to bright peak and subtract background
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
... [6, 5, 4, 5, 6],
... [6, 4, 0, 4, 6],
... [6, 5, 4, 5, 6],
... [7, 6, 6, 6, 7]], dtype=np.uint8)
>>> black_tophat(dark_on_gray, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 5, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
closing(image, footprint=None, out=None, *, mode='reflect', cval=0.0)
Return grayscale morphological closing of an image.
The morphological closing of an image is defined as a dilation followed by
an erosion. Closing can remove small dark spots (i.e. "pepper") and connect
small bright cracks. This tends to "close" up (dark) gaps between (bright)
features.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray, optional
The array to store the result of the morphology. If None,
a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'.
If 'ignore', pixels outside the image domain are assumed
to be the maximum for the image's dtype in the erosion, and minimum
in the dilation, which causes them to not influence the result.
Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
closing : array, same shape and type as `image`
The result of the morphological closing.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
Examples
--------
>>> # Close a gap between two bright lines
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> broken_line = np.array([[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [1, 1, 0, 1, 1],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> closing(broken_line, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
convex_hull_image(image, offset_coordinates=True, tolerance=1e-10, include_borders=True)
Compute the convex hull image of a binary image.
The convex hull is the set of pixels included in the smallest convex
polygon that surround all white pixels in the input image.
Parameters
----------
image : array
Binary input image. This array is cast to bool before processing.
offset_coordinates : bool, optional
If ``True``, a pixel at coordinate, e.g., (4, 7) will be represented
by coordinates (3.5, 7), (4.5, 7), (4, 6.5), and (4, 7.5). This adds
some "extent" to a pixel when computing the hull.
tolerance : float, optional
Tolerance when determining whether a point is inside the hull. Due
to numerical floating point errors, a tolerance of 0 can result in
some points erroneously being classified as being outside the hull.
include_borders: bool, optional
If ``False``, vertices/edges are excluded from the final hull mask.
Returns
-------
hull : (M, N) array of bool
Binary image with pixels in convex hull set to True.
References
----------
.. [1] https://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/
convex_hull_object(image, *, connectivity=2)
Compute the convex hull image of individual objects in a binary image.
The convex hull is the set of pixels included in the smallest convex
polygon that surround all white pixels in the input image.
Parameters
----------
image : (M, N) ndarray
Binary input image.
connectivity : {1, 2}, int, optional
Determines the neighbors of each pixel. Adjacent elements
within a squared distance of ``connectivity`` from pixel center
are considered neighbors.::
1-connectivity 2-connectivity
[ ] [ ] [ ] [ ]
| \ | /
[ ]--[x]--[ ] [ ]--[x]--[ ]
| / | \
[ ] [ ] [ ] [ ]
Returns
-------
hull : ndarray of bool
Binary image with pixels inside convex hull set to ``True``.
Notes
-----
This function uses ``skimage.morphology.label`` to define unique objects,
finds the convex hull of each using ``convex_hull_image``, and combines
these regions with logical OR. Be aware the convex hulls of unconnected
objects may overlap in the result. If this is suspected, consider using
convex_hull_image separately on each object or adjust ``connectivity``.
diameter_closing(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)
Perform a diameter closing of the image.
Diameter closing removes all dark structures of an image with
maximal extension smaller than diameter_threshold. The maximal
extension is defined as the maximal extension of the bounding box.
The operator is also called Bounding Box Closing. In practice,
the result is similar to a morphological closing, but long and thin
structures are not removed.
Technically, this operator is based on the max-tree representation of
the image.
Parameters
----------
image : ndarray
The input image for which the diameter_closing is to be calculated.
This image can be of any type.
diameter_threshold : unsigned int
The maximal extension parameter (number of pixels). The default value
is 8.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
parent : ndarray, int64, optional
Precomputed parent image representing the max tree of the inverted
image. This function is fast, if precomputed parent and tree_traverser
are provided. See Note for further details.
tree_traverser : 1D array, int64, optional
Precomputed traverser, where the pixels are ordered such that every
pixel is preceded by its parent (except for the root which has no
parent). This function is fast, if precomputed parent and
tree_traverser are provided. See Note for further details.
Returns
-------
output : ndarray
Output image of the same shape and type as input image.
See Also
--------
skimage.morphology.area_opening
skimage.morphology.area_closing
skimage.morphology.diameter_opening
skimage.morphology.max_tree
References
----------
.. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of
Microaneurysms in Color Fundus Images of the Human Retina by Means
of the Bounding Box Closing. In A. Colosimo, P. Sirabella,
A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer
Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg.
:DOI:`10.1007/3-540-36104-9_23`
.. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create an image (quadratic function with a minimum in the center and
4 additional local minima.
>>> w = 12
>>> x, y = np.mgrid[0:w,0:w]
>>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2)
>>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120
>>> f[9:10,9:11] = 100; f[10,10] = 100
>>> f = f.astype(int)
We can calculate the diameter closing:
>>> closed = diameter_closing(f, 3, connectivity=1)
All small minima with a maximal extension of 2 or less are removed.
The remaining minima have all a maximal extension of at least 3.
Notes
-----
If a max-tree representation (parent and tree_traverser) are given to the
function, they must be calculated from the inverted image for this
function, i.e.:
>>> P, S = max_tree(invert(f))
>>> closed = diameter_closing(f, 3, parent=P, tree_traverser=S)
diameter_opening(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)
Perform a diameter opening of the image.
Diameter opening removes all bright structures of an image with
maximal extension smaller than diameter_threshold. The maximal
extension is defined as the maximal extension of the bounding box.
The operator is also called Bounding Box Opening. In practice,
the result is similar to a morphological opening, but long and thin
structures are not removed.
Technically, this operator is based on the max-tree representation of
the image.
Parameters
----------
image : ndarray
The input image for which the area_opening is to be calculated.
This image can be of any type.
diameter_threshold : unsigned int
The maximal extension parameter (number of pixels). The default value
is 8.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
parent : ndarray, int64, optional
Parent image representing the max tree of the image. The
value of each pixel is the index of its parent in the ravelled array.
tree_traverser : 1D array, int64, optional
The ordered pixel indices (referring to the ravelled array). The pixels
are ordered such that every pixel is preceded by its parent (except for
the root which has no parent).
Returns
-------
output : ndarray
Output image of the same shape and type as the input image.
See Also
--------
skimage.morphology.area_opening
skimage.morphology.area_closing
skimage.morphology.diameter_closing
skimage.morphology.max_tree
References
----------
.. [1] Walter, T., & Klein, J.-C. (2002). Automatic Detection of
Microaneurysms in Color Fundus Images of the Human Retina by Means
of the Bounding Box Closing. In A. Colosimo, P. Sirabella,
A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer
Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg.
:DOI:`10.1007/3-540-36104-9_23`
.. [2] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create an image (quadratic function with a maximum in the center and
4 additional local maxima.
>>> w = 12
>>> x, y = np.mgrid[0:w,0:w]
>>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2)
>>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80
>>> f[9:10,9:11] = 100; f[10,10] = 100
>>> f = f.astype(int)
We can calculate the diameter opening:
>>> open = diameter_opening(f, 3, connectivity=1)
The peaks with a maximal extension of 2 or less are removed.
The remaining peaks have all a maximal extension of at least 3.
diamond(radius, dtype=<class 'numpy.uint8'>, *, decomposition=None)
Generates a flat, diamond-shaped footprint.
A pixel is part of the neighborhood (i.e. labeled 1) if
the city block/Manhattan distance between it and the center of
the neighborhood is no greater than radius.
Parameters
----------
radius : int
The radius of the diamond-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
dilation(image, footprint=None, out=None, shift_x=<DEPRECATED>, shift_y=<DEPRECATED>, *, mode='reflect', cval=0.0)
Return grayscale morphological dilation of an image.
Morphological dilation sets the value of a pixel to the maximum over all
pixel values within a local neighborhood centered about it. The values
where the footprint is 1 define this neighborhood.
Dilation enlarges bright regions and shrinks dark regions.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'.
If 'min' or 'ignore', pixels outside the image domain are assumed
to be the maximum for the image's dtype, which causes them to not
influence the result. Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
dilated : uint8 array, same shape and type as `image`
The result of the morphological dilation.
Other Parameters
----------------
shift_x, shift_y : DEPRECATED
.. deprecated:: 0.23
Notes
-----
For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the lower
algorithm complexity makes the :func:`skimage.filters.rank.maximum`
function more efficient for larger images and footprints.
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
For non-symmetric footprints, :func:`skimage.morphology.binary_dilation`
and :func:`skimage.morphology.dilation` produce an output that differs:
`binary_dilation` mirrors the footprint, whereas `dilation` does not.
Examples
--------
>>> # Dilation enlarges bright regions
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> bright_pixel = np.array([[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> dilation(bright_pixel, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
disk(radius, dtype=<class 'numpy.uint8'>, *, strict_radius=True, decomposition=None)
Generates a flat, disk-shaped footprint.
A pixel is within the neighborhood if the Euclidean distance between
it and the origin is no greater than radius (This is only approximately
True, when `decomposition == 'sequence'`).
Parameters
----------
radius : int
The radius of the disk-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
strict_radius : bool, optional
If False, extend the radius by 0.5. This allows the circle to expand
further within a cube that remains of size ``2 * radius + 1`` along
each axis. This parameter is ignored if decomposition is not None.
decomposition : {None, 'sequence', 'crosses'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given a result equivalent to a single, larger footprint, but with
better computational performance. For disk footprints, the 'sequence'
or 'crosses' decompositions are not always exactly equivalent to
``decomposition=None``. See Notes for more details.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
The disk produced by the ``decomposition='sequence'`` mode may not be
identical to that with ``decomposition=None``. A disk footprint can be
approximated by applying a series of smaller footprints of extent 3 along
each axis. Specific solutions for this are given in [1]_ for the case of
2D disks with radius 2 through 10. Here, we numerically computed the number
of repetitions of each element that gives the closest match to the disk
computed with kwargs ``strict_radius=False, decomposition=None``.
Empirically, the series decomposition at large radius approaches a
hexadecagon (a 16-sided polygon [2]_). In [3]_, the authors demonstrate
that a hexadecagon is the closest approximation to a disk that can be
achieved for decomposition with footprints of shape (3, 3).
The disk produced by the ``decomposition='crosses'`` is often but not
always identical to that with ``decomposition=None``. It tends to give a
closer approximation than ``decomposition='sequence'``, at a performance
that is fairly comparable. The individual cross-shaped elements are not
limited to extent (3, 3) in size. Unlike the 'seqeuence' decomposition, the
'crosses' decomposition can also accurately approximate the shape of disks
with ``strict_radius=True``. The method is based on an adaption of
algorithm 1 given in [4]_.
References
----------
.. [1] Park, H and Chin R.T. Decomposition of structuring elements for
optimal implementation of morphological operations. In Proceedings:
1997 IEEE Workshop on Nonlinear Signal and Image Processing, London,
UK.
https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf
.. [2] https://en.wikipedia.org/wiki/Hexadecagon
.. [3] Vanrell, M and Vitrià, J. Optimal 3 × 3 decomposable disks for
morphological transformations. Image and Vision Computing, Vol. 15,
Issue 11, 1997.
:DOI:`10.1016/S0262-8856(97)00026-7`
.. [4] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric
Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological
Image Processing, (1 November 1990).
:DOI:`10.1117/12.23608`
ellipse(width, height, dtype=<class 'numpy.uint8'>, *, decomposition=None)
Generates a flat, ellipse-shaped footprint.
Every pixel along the perimeter of ellipse satisfies
the equation ``(x/width+1)**2 + (y/height+1)**2 = 1``.
Parameters
----------
width : int
The width of the ellipse-shaped footprint.
height : int
The height of the ellipse-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'crosses'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
The footprint will have shape ``(2 * height + 1, 2 * width + 1)``.
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
The ellipse produced by the ``decomposition='crosses'`` is often but not
always identical to that with ``decomposition=None``. The method is based
on an adaption of algorithm 1 given in [1]_.
References
----------
.. [1] Li, D. and Ritter, G.X. Decomposition of Separable and Symmetric
Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological
Image Processing, (1 November 1990).
:DOI:`10.1117/12.23608`
Examples
--------
>>> from skimage.morphology import footprints
>>> footprints.ellipse(5, 3)
array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=uint8)
erosion(image, footprint=None, out=None, shift_x=<DEPRECATED>, shift_y=<DEPRECATED>, *, mode='reflect', cval=0.0)
Return grayscale morphological erosion of an image.
Morphological erosion sets a pixel at (i,j) to the minimum over all pixels
in the neighborhood centered at (i,j). Erosion shrinks bright regions and
enlarges dark regions.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarrays, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'.
If 'max' or 'ignore', pixels outside the image domain are assumed
to be the maximum for the image's dtype, which causes them to not
influence the result. Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
eroded : array, same shape as `image`
The result of the morphological erosion.
Other Parameters
----------------
shift_x, shift_y : DEPRECATED
.. deprecated:: 0.23
Notes
-----
For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, the
lower algorithm complexity makes the :func:`skimage.filters.rank.minimum`
function more efficient for larger images and footprints.
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
For even-sized footprints, :func:`skimage.morphology.binary_erosion` and
this function produce an output that differs: one is shifted by one pixel
compared to the other.
Examples
--------
>>> # Erosion shrinks bright regions
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> bright_square = np.array([[0, 0, 0, 0, 0],
... [0, 1, 1, 1, 0],
... [0, 1, 1, 1, 0],
... [0, 1, 1, 1, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> erosion(bright_square, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
flood(image, seed_point, *, footprint=None, connectivity=None, tolerance=None)
Mask corresponding to a flood fill.
Starting at a specific `seed_point`, connected points equal or within
`tolerance` of the seed value are found.
Parameters
----------
image : ndarray
An n-dimensional array.
seed_point : tuple or int
The point in `image` used as the starting point for the flood fill. If
the image is 1D, this point may be given as an integer.
footprint : ndarray, optional
The footprint (structuring element) used to determine the neighborhood
of each evaluated pixel. It must contain only 1's and 0's, have the
same number of dimensions as `image`. If not given, all adjacent pixels
are considered as part of the neighborhood (fully connected).
connectivity : int, optional
A number used to determine the neighborhood of each evaluated pixel.
Adjacent pixels whose squared distance from the center is less than or
equal to `connectivity` are considered neighbors. Ignored if
`footprint` is not None.
tolerance : float or int, optional
If None (default), adjacent values must be strictly equal to the
initial value of `image` at `seed_point`. This is fastest. If a value
is given, a comparison will be done at every point and if within
tolerance of the initial value will also be filled (inclusive).
Returns
-------
mask : ndarray
A Boolean array with the same shape as `image` is returned, with True
values for areas connected to and equal (or within tolerance of) the
seed point. All other values are False.
Notes
-----
The conceptual analogy of this operation is the 'paint bucket' tool in many
raster graphics programs. This function returns just the mask
representing the fill.
If indices are desired rather than masks for memory reasons, the user can
simply run `numpy.nonzero` on the result, save the indices, and discard
this mask.
Examples
--------
>>> from skimage.morphology import flood
>>> image = np.zeros((4, 7), dtype=int)
>>> image[1:3, 1:3] = 1
>>> image[3, 0] = 1
>>> image[1:3, 4:6] = 2
>>> image[3, 6] = 3
>>> image
array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 0],
[0, 1, 1, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, with full connectivity (diagonals included):
>>> mask = flood(image, (1, 1))
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[5, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, excluding diagonal points (connectivity 1):
>>> mask = flood(image, (1, 1), connectivity=1)
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill with a tolerance:
>>> mask = flood(image, (0, 0), tolerance=1)
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 5, 5, 3]])
flood_fill(image, seed_point, new_value, *, footprint=None, connectivity=None, tolerance=None, in_place=False)
Perform flood filling on an image.
Starting at a specific `seed_point`, connected points equal or within
`tolerance` of the seed value are found, then set to `new_value`.
Parameters
----------
image : ndarray
An n-dimensional array.
seed_point : tuple or int
The point in `image` used as the starting point for the flood fill. If
the image is 1D, this point may be given as an integer.
new_value : `image` type
New value to set the entire fill. This must be chosen in agreement
with the dtype of `image`.
footprint : ndarray, optional
The footprint (structuring element) used to determine the neighborhood
of each evaluated pixel. It must contain only 1's and 0's, have the
same number of dimensions as `image`. If not given, all adjacent pixels
are considered as part of the neighborhood (fully connected).
connectivity : int, optional
A number used to determine the neighborhood of each evaluated pixel.
Adjacent pixels whose squared distance from the center is less than or
equal to `connectivity` are considered neighbors. Ignored if
`footprint` is not None.
tolerance : float or int, optional
If None (default), adjacent values must be strictly equal to the
value of `image` at `seed_point` to be filled. This is fastest.
If a tolerance is provided, adjacent points with values within plus or
minus tolerance from the seed point are filled (inclusive).
in_place : bool, optional
If True, flood filling is applied to `image` in place. If False, the
flood filled result is returned without modifying the input `image`
(default).
Returns
-------
filled : ndarray
An array with the same shape as `image` is returned, with values in
areas connected to and equal (or within tolerance of) the seed point
replaced with `new_value`.
Notes
-----
The conceptual analogy of this operation is the 'paint bucket' tool in many
raster graphics programs.
Examples
--------
>>> from skimage.morphology import flood_fill
>>> image = np.zeros((4, 7), dtype=int)
>>> image[1:3, 1:3] = 1
>>> image[3, 0] = 1
>>> image[1:3, 4:6] = 2
>>> image[3, 6] = 3
>>> image
array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 0],
[0, 1, 1, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, with full connectivity (diagonals included):
>>> flood_fill(image, (1, 1), 5)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[5, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, excluding diagonal points (connectivity 1):
>>> flood_fill(image, (1, 1), 5, connectivity=1)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill with a tolerance:
>>> flood_fill(image, (0, 0), 5, tolerance=1)
array([[5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 5, 5, 3]])
footprint_from_sequence(footprints)
Convert a footprint sequence into an equivalent ndarray.
Parameters
----------
footprints : tuple of 2-tuples
A sequence of footprint tuples where the first element of each tuple
is an array corresponding to a footprint and the second element is the
number of times it is to be applied. Currently, all footprints should
have odd size.
Returns
-------
footprint : ndarray
An single array equivalent to applying the sequence of ``footprints``.
footprint_rectangle(shape, *, dtype=<class 'numpy.uint8'>, decomposition=None)
Generate a rectangular or hyper-rectangular footprint.
Generates, depending on the length and dimensions requested with `shape`,
a square, rectangle, cube, cuboid, or even higher-dimensional versions
of these shapes.
Parameters
----------
shape : tuple[int, ...]
The length of the footprint in each dimension. The length of the
sequence determines the number of dimensions of the footprint.
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'separable', 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
give an identical result to a single, larger footprint, but often with
better computational performance. See Notes for more details.
With 'separable', this function uses separable 1D footprints for each
axis. Whether 'sequence' or 'separable' is computationally faster may
be architecture-dependent.
Returns
-------
footprint : array or tuple[tuple[ndarray, int], ...]
A footprint consisting only of ones, i.e. every pixel belongs to the
neighborhood. When `decomposition` is None, this is just an array.
Otherwise, this will be a tuple whose length is equal to the number of
unique structuring elements to apply (see Examples for more detail).
Examples
--------
>>> import skimage as ski
>>> ski.morphology.footprint_rectangle((3, 5))
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]], dtype=uint8)
Decomposition will return multiple footprints that combine into a simple
footprint of the requested shape.
>>> ski.morphology.footprint_rectangle((9, 9), decomposition="sequence")
((array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=uint8),
4),)
`"sequence"` makes sure that the decomposition only returns 1D footprints.
>>> ski.morphology.footprint_rectangle((3, 5), decomposition="separable")
((array([[1],
[1],
[1]], dtype=uint8),
1),
(array([[1, 1, 1, 1, 1]], dtype=uint8), 1))
Generate a 5-dimensional hypercube with 3 samples in each dimension
>>> ski.morphology.footprint_rectangle((3,) * 5).shape
(3, 3, 3, 3, 3)
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.
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.
isotropic_closing(image, radius, out=None, spacing=None)
Return binary morphological closing of an image.
This function returns the same result as binary :func:`skimage.morphology.binary_closing`
but performs faster for large circular structuring elements.
This works by thresholding the exact Euclidean distance map [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius with which the regions should be closed.
out : ndarray of bool, optional
The array to store the result of the morphology. If None,
is passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
closed : ndarray of bool
The result of the morphological closing.
References
----------
.. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
isotropic_dilation(image, radius, out=None, spacing=None)
Return binary morphological dilation of an image.
This function returns the same result as :func:`skimage.morphology.binary_dilation`
but performs faster for large circular structuring elements.
This works by applying a threshold to the exact Euclidean distance map
of the inverted image [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius by which regions should be dilated.
out : ndarray of bool, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
dilated : ndarray of bool
The result of the morphological dilation with values in
``[False, True]``.
References
----------
.. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
isotropic_erosion(image, radius, out=None, spacing=None)
Return binary morphological erosion of an image.
This function returns the same result as :func:`skimage.morphology.binary_erosion`
but performs faster for large circular structuring elements.
This works by applying a threshold to the exact Euclidean distance map
of the image [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius by which regions should be eroded.
out : ndarray of bool, optional
The array to store the result of the morphology. If None,
a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
eroded : ndarray of bool
The result of the morphological erosion taking values in
``[False, True]``.
References
----------
.. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
isotropic_opening(image, radius, out=None, spacing=None)
Return binary morphological opening of an image.
This function returns the same result as :func:`skimage.morphology.binary_opening`
but performs faster for large circular structuring elements.
This works by thresholding the exact Euclidean distance map [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius with which the regions should be opened.
out : ndarray of bool, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
opened : ndarray of bool
The result of the morphological opening.
References
----------
.. [1] Cuisenaire, O. and Macq, B., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] Ingemar Ragnemalm, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
label(label_image, background=None, return_num=False, connectivity=None)
Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value.
In 2D, they can be neighbors either in a 1- or 2-connected sense.
The value refers to the maximum number of orthogonal hops to consider a
pixel/voxel a neighbor::
1-connectivity 2-connectivity diagonal connection close-up
[ ] [ ] [ ] [ ] [ ]
| \ | / | <- hop 2
[ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ]
| / | \ hop 1
[ ] [ ] [ ] [ ]
Parameters
----------
label_image : ndarray of dtype int
Image to label.
background : int, optional
Consider all pixels with this value as background pixels, and label
them as 0. By default, 0-valued pixels are considered as background
pixels.
return_num : bool, optional
Whether to return the number of assigned labels.
connectivity : int, optional
Maximum number of orthogonal hops to consider a pixel/voxel
as a neighbor.
Accepted values are ranging from 1 to input.ndim. If ``None``, a full
connectivity of ``input.ndim`` is used.
Returns
-------
labels : ndarray of dtype int
Labeled array, where all connected regions are assigned the
same integer value.
num : int, optional
Number of labels, which equals the maximum label index and is only
returned if return_num is `True`.
See Also
--------
skimage.measure.regionprops
skimage.measure.regionprops_table
References
----------
.. [1] Christophe Fiorio and Jens Gustedt, "Two linear time Union-Find
strategies for image processing", Theoretical Computer Science
154 (1996), pp. 165-181.
.. [2] Kensheng Wu, Ekow Otoo and Arie Shoshani, "Optimizing connected
component labeling algorithms", Paper LBNL-56864, 2005,
Lawrence Berkeley National Laboratory (University of California),
http://repositories.cdlib.org/lbnl/LBNL-56864
Examples
--------
>>> import numpy as np
>>> x = np.eye(3).astype(int)
>>> print(x)
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, connectivity=1))
[[1 0 0]
[0 2 0]
[0 0 3]]
>>> print(label(x, connectivity=2))
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, background=-1))
[[1 2 2]
[2 1 2]
[2 2 1]]
>>> x = np.array([[1, 0, 0],
... [1, 1, 5],
... [0, 0, 0]])
>>> print(label(x))
[[1 0 0]
[1 1 2]
[0 0 0]]
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]])
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]])
max_tree(image, connectivity=1)
Build the max tree from an image.
Component trees represent the hierarchical structure of the connected
components resulting from sequential thresholding operations applied to an
image. A connected component at one level is parent of a component at a
higher level if the latter is included in the first. A max-tree is an
efficient representation of a component tree. A connected component at
one level is represented by one reference pixel at this level, which is
parent to all other pixels at that level and to the reference pixel at the
level above. The max-tree is the basis for many morphological operators,
namely connected operators.
Parameters
----------
image : ndarray
The input image for which the max-tree is to be calculated.
This image can be of any type.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
Returns
-------
parent : ndarray, int64
Array of same shape as image. The value of each pixel is the index of
its parent in the ravelled array.
tree_traverser : 1D array, int64
The ordered pixel indices (referring to the ravelled array). The pixels
are ordered such that every pixel is preceded by its parent (except for
the root which has no parent).
References
----------
.. [1] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive
Connected Operators for Image and Sequence Processing.
IEEE Transactions on Image Processing, 7(4), 555-570.
:DOI:`10.1109/83.663500`
.. [2] Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A.,
Bertin, E. (2007). Effective Component Tree Computation with
Application to Pattern Recognition in Astronomical Imaging.
In International Conference on Image Processing (ICIP) (pp. 41-44).
:DOI:`10.1109/ICIP.2007.4379949`
.. [3] Najman, L., & Couprie, M. (2006). Building the component tree in
quasi-linear time. IEEE Transactions on Image Processing, 15(11),
3531-3539.
:DOI:`10.1109/TIP.2006.877518`
.. [4] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create a small sample image (Figure 1 from [4]) and build the max-tree.
>>> image = np.array([[15, 13, 16], [12, 12, 10], [16, 12, 14]])
>>> P, S = max_tree(image, connectivity=2)
max_tree_local_maxima(image, connectivity=1, parent=None, tree_traverser=None)
Determine all local maxima of the image.
The local maxima are defined as connected sets of pixels with equal
gray level strictly greater than the gray levels of all pixels in direct
neighborhood of the set. The function labels the local maxima.
Technically, the implementation is based on the max-tree representation
of an image. The function is very efficient if the max-tree representation
has already been computed. Otherwise, it is preferable to use
the function local_maxima.
Parameters
----------
image : ndarray
The input image for which the maxima are to be calculated.
connectivity : unsigned int, optional
The neighborhood connectivity. The integer represents the maximum
number of orthogonal steps to reach a neighbor. In 2D, it is 1 for
a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1.
parent : ndarray, int64, optional
The value of each pixel is the index of its parent in the ravelled
array.
tree_traverser : 1D array, int64, optional
The ordered pixel indices (referring to the ravelled array). The pixels
are ordered such that every pixel is preceded by its parent (except for
the root which has no parent).
Returns
-------
local_max : ndarray, uint64
Labeled local maxima of the image.
See Also
--------
skimage.morphology.local_maxima
skimage.morphology.max_tree
References
----------
.. [1] Vincent L., Proc. "Grayscale area openings and closings,
their efficient implementation and applications",
EURASIP Workshop on Mathematical Morphology and its
Applications to Signal Processing, Barcelona, Spain, pp.22-27,
May 1993.
.. [2] Soille, P., "Morphological Image Analysis: Principles and
Applications" (Chapter 6), 2nd edition (2003), ISBN 3540429883.
:DOI:`10.1007/978-3-662-05088-0`
.. [3] Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive
Connected Operators for Image and Sequence Processing.
IEEE Transactions on Image Processing, 7(4), 555-570.
:DOI:`10.1109/83.663500`
.. [4] Najman, L., & Couprie, M. (2006). Building the component tree in
quasi-linear time. IEEE Transactions on Image Processing, 15(11),
3531-3539.
:DOI:`10.1109/TIP.2006.877518`
.. [5] Carlinet, E., & Geraud, T. (2014). A Comparative Review of
Component Tree Computation Algorithms. IEEE Transactions on Image
Processing, 23(9), 3885-3895.
:DOI:`10.1109/TIP.2014.2336551`
Examples
--------
We create an image (quadratic function with a maximum in the center and
4 additional constant maxima.
>>> w = 10
>>> x, y = np.mgrid[0:w,0:w]
>>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2)
>>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100
>>> f = f.astype(int)
We can calculate all local maxima:
>>> maxima = max_tree_local_maxima(f)
The resulting image contains the labeled local maxima.
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)
mirror_footprint(footprint)
Mirror each dimension in the footprint.
Parameters
----------
footprint : ndarray or tuple
The input footprint or sequence of footprints
Returns
-------
inverted : ndarray or tuple
The footprint, mirrored along each dimension.
Examples
--------
>>> footprint = np.array([[0, 0, 0],
... [0, 1, 1],
... [0, 1, 1]], np.uint8)
>>> mirror_footprint(footprint)
array([[1, 1, 0],
[1, 1, 0],
[0, 0, 0]], dtype=uint8)
octagon(m, n, dtype=<class 'numpy.uint8'>, *, decomposition=None)
Generates an octagon shaped footprint.
For a given size of (m) horizontal and vertical sides
and a given (n) height or width of slanted sides octagon is generated.
The slanted sides are 45 or 135 degrees to the horizontal axis
and hence the widths and heights are equal. The overall size of the
footprint along a single axis will be ``m + 2 * n``.
Parameters
----------
m : int
The size of the horizontal and vertical sides.
n : int
The height or width of the slanted sides.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
octahedron(radius, dtype=<class 'numpy.uint8'>, *, decomposition=None)
Generates a octahedron-shaped footprint.
This is the 3D equivalent of a diamond.
A pixel is part of the neighborhood (i.e. labeled 1) if
the city block/Manhattan distance between it and the center of
the neighborhood is no greater than radius.
Parameters
----------
radius : int
The radius of the octahedron-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
opening(image, footprint=None, out=None, *, mode='reflect', cval=0.0)
Return grayscale morphological opening of an image.
The morphological opening of an image is defined as an erosion followed by
a dilation. Opening can remove small bright spots (i.e. "salt") and connect
small dark cracks. This tends to "open" up (dark) gaps between (bright)
features.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'.
If 'ignore', pixels outside the image domain are assumed
to be the maximum for the image's dtype in the erosion, and minimum
in the dilation, which causes them to not influence the result.
Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
opening : array, same shape and type as `image`
The result of the morphological opening.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
Examples
--------
>>> # Open up gap between two bright regions (but also shrink regions)
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> bad_connection = np.array([[1, 0, 0, 0, 1],
... [1, 1, 0, 1, 1],
... [1, 1, 1, 1, 1],
... [1, 1, 0, 1, 1],
... [1, 0, 0, 0, 1]], dtype=np.uint8)
>>> opening(bad_connection, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0]], dtype=uint8)
pad_footprint(footprint, *, pad_end=True)
Pad the footprint to an odd size along each dimension.
Parameters
----------
footprint : ndarray or tuple
The input footprint or sequence of footprints
pad_end : bool, optional
If ``True``, pads at the end of each dimension (right side), otherwise
pads on the front (left side).
Returns
-------
padded : ndarray or tuple
The footprint, padded to an odd size along each dimension.
Examples
--------
>>> footprint = np.array([[0, 0],
... [1, 1],
... [1, 1]], np.uint8)
>>> pad_footprint(footprint)
array([[0, 0, 0],
[1, 1, 0],
[1, 1, 0]], dtype=uint8)
reconstruction(seed, mask, method='dilation', footprint=None, offset=None)
Perform a morphological reconstruction of an image.
Morphological reconstruction by dilation is similar to basic morphological
dilation: high-intensity values will replace nearby low-intensity values.
The basic dilation operator, however, uses a footprint to
determine how far a value in the input image can spread. In contrast,
reconstruction uses two images: a "seed" image, which specifies the values
that spread, and a "mask" image, which gives the maximum allowed value at
each pixel. The mask image, like the footprint, limits the spread
of high-intensity values. Reconstruction by erosion is simply the inverse:
low-intensity values spread from the seed image and are limited by the mask
image, which represents the minimum allowed value.
Alternatively, you can think of reconstruction as a way to isolate the
connected regions of an image. For dilation, reconstruction connects
regions marked by local maxima in the seed image: neighboring pixels
less-than-or-equal-to those seeds are connected to the seeded region.
Local maxima with values larger than the seed image will get truncated to
the seed value.
Parameters
----------
seed : ndarray
The seed image (a.k.a. marker image), which specifies the values that
are dilated or eroded.
mask : ndarray
The maximum (dilation) / minimum (erosion) allowed value at each pixel.
method : {'dilation'|'erosion'}, optional
Perform reconstruction by dilation or erosion. In dilation (or
erosion), the seed image is dilated (or eroded) until limited by the
mask image. For dilation, each seed value must be less than or equal
to the corresponding mask value; for erosion, the reverse is true.
Default is 'dilation'.
footprint : ndarray, optional
The neighborhood expressed as an n-D array of 1's and 0's.
Default is the n-D square of radius equal to 1 (i.e. a 3x3 square
for 2D images, a 3x3x3 cube for 3D images, etc.)
offset : ndarray, optional
The coordinates of the center of the footprint.
Default is located on the geometrical center of the footprint, in that
case footprint dimensions must be odd.
Returns
-------
reconstructed : ndarray
The result of morphological reconstruction.
Examples
--------
>>> import numpy as np
>>> from skimage.morphology import reconstruction
First, we create a sinusoidal mask image with peaks at middle and ends.
>>> x = np.linspace(0, 4 * np.pi)
>>> y_mask = np.cos(x)
Then, we create a seed image initialized to the minimum mask value (for
reconstruction by dilation, min-intensity values don't spread) and add
"seeds" to the left and right peak, but at a fraction of peak value (1).
>>> y_seed = y_mask.min() * np.ones_like(x)
>>> y_seed[0] = 0.5
>>> y_seed[-1] = 0
>>> y_rec = reconstruction(y_seed, y_mask)
The reconstructed image (or curve, in this case) is exactly the same as the
mask image, except that the peaks are truncated to 0.5 and 0. The middle
peak disappears completely: Since there were no seed values in this peak
region, its reconstructed value is truncated to the surrounding value (-1).
As a more practical example, we try to extract the bright features of an
image by subtracting a background image created by reconstruction.
>>> y, x = np.mgrid[:20:0.5, :20:0.5]
>>> bumps = np.sin(x) + np.sin(y)
To create the background image, set the mask image to the original image,
and the seed image to the original image with an intensity offset, `h`.
>>> h = 0.3
>>> seed = bumps - h
>>> background = reconstruction(seed, bumps)
The resulting reconstructed image looks exactly like the original image,
but with the peaks of the bumps cut off. Subtracting this reconstructed
image from the original image leaves just the peaks of the bumps
>>> hdome = bumps - background
This operation is known as the h-dome of the image and leaves features
of height `h` in the subtracted image.
Notes
-----
The algorithm is taken from [1]_. Applications for grayscale reconstruction
are discussed in [2]_ and [3]_.
References
----------
.. [1] Robinson, "Efficient morphological reconstruction: a downhill
filter", Pattern Recognition Letters 25 (2004) 1759-1767.
.. [2] Vincent, L., "Morphological Grayscale Reconstruction in Image
Analysis: Applications and Efficient Algorithms", IEEE Transactions
on Image Processing (1993)
.. [3] Soille, P., "Morphological Image Analysis: Principles and
Applications", Chapter 6, 2nd edition (2003), ISBN 3540429883.
remove_objects_by_distance(label_image, min_distance, *, priority=None, p_norm=2, spacing=None, out=None)
Remove objects, in specified order, until remaining are a minimum distance apart.
Remove labeled objects from an image until the remaining ones are spaced
more than a given distance from one another. By default, smaller objects
are removed first.
Parameters
----------
label_image : ndarray of integers
An n-dimensional array containing object labels, e.g. as returned by
:func:`~.label`. A value of zero is considered background, all other
object IDs must be positive integers.
min_distance : int or float
Remove objects whose distance to other objects is not greater than this
positive value. Objects with a lower `priority` are removed first.
priority : ndarray, optional
Defines the priority with which objects are removed. Expects a
1-dimensional array of length
:func:`np.amax(label_image) + 1 <numpy.amax>` that contains the priority
for each object's label at the respective index. Objects with a lower value
are removed first until all remaining objects fulfill the distance
requirement. If not given, priority is given to objects with a higher
number of samples and their label value second.
p_norm : int or float, optional
The Minkowski distance of order p, used to calculate the distance
between objects. The default ``2`` corresponds to the Euclidean
distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the
Chebyshev distance.
spacing : sequence of float, optional
The pixel spacing along each axis of `label_image`. If not specified,
a grid spacing of unity (1) is implied.
out : ndarray, optional
Array of the same shape and dtype as `image`, into which the output is
placed. By default, a new array is created.
Returns
-------
out : ndarray
Array of the same shape as `label_image`, for which objects that violate
the `min_distance` condition were removed.
See Also
--------
skimage.morphology.remove_small_objects
Remove objects smaller than the specified size.
Notes
-----
The basic steps of this algorithm work as follows:
1. Find the indices for of all given objects and separate them depending on
if they point to an object's border or not.
2. Sort indices by their label value, ensuring that indices which point to
the same object are next to each other. This optimization allows finding
all parts of an object, simply by stepping to the neighboring indices.
3. Sort boundary indices by `priority`. Use a stable-sort to preserve the
ordering from the previous sorting step. If `priority` is not given,
use :func:`numpy.bincount` as a fallback.
4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices.
5. Iterate across boundary indices in priority-sorted order, and query the
kd-tree for objects that are too close. Remove ones that are and don't
take them into account when evaluating other objects later on.
The performance of this algorithm depends on the number of samples in
`label_image` that belong to an object's border.
Examples
--------
>>> import skimage as ski
>>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2)
array([0, 0, 1, 1])
>>> ski.morphology.remove_objects_by_distance(
... np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9])
... )
array([2, 0, 0, 0])
>>> label_image = np.array(
... [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
... [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
... [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
... [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0],
... [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]]
... )
>>> ski.morphology.remove_objects_by_distance(
... label_image, min_distance=3
... )
array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
[8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]])
remove_small_holes(ar, area_threshold=64, connectivity=1, *, out=None)
Remove contiguous holes smaller than the specified size.
Parameters
----------
ar : ndarray (arbitrary shape, int or bool type)
The array containing the connected components of interest.
area_threshold : int, optional (default: 64)
The maximum area, in pixels, of a contiguous hole that will be filled.
Replaces `min_size`.
connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
The connectivity defining the neighborhood of a pixel.
out : ndarray
Array of the same shape as `ar` and bool dtype, into which the
output is placed. By default, a new array is created.
Raises
------
TypeError
If the input array is of an invalid type, such as float or string.
ValueError
If the input array contains negative values.
Returns
-------
out : ndarray, same shape and type as input `ar`
The input array with small holes within connected components removed.
Examples
--------
>>> from skimage import morphology
>>> a = np.array([[1, 1, 1, 1, 1, 0],
... [1, 1, 1, 0, 1, 0],
... [1, 0, 0, 1, 1, 0],
... [1, 1, 1, 1, 1, 0]], bool)
>>> b = morphology.remove_small_holes(a, 2)
>>> b
array([[ True, True, True, True, True, False],
[ True, True, True, True, True, False],
[ True, False, False, True, True, False],
[ True, True, True, True, True, False]])
>>> c = morphology.remove_small_holes(a, 2, connectivity=2)
>>> c
array([[ True, True, True, True, True, False],
[ True, True, True, False, True, False],
[ True, False, False, True, True, False],
[ True, True, True, True, True, False]])
>>> d = morphology.remove_small_holes(a, 2, out=a)
>>> d is a
True
Notes
-----
If the array type is int, it is assumed that it contains already-labeled
objects. The labels are not kept in the output image (this function always
outputs a bool image). It is suggested that labeling is completed after
using this function.
remove_small_objects(ar, min_size=64, connectivity=1, *, out=None)
Remove objects smaller than the specified size.
Expects ar to be an array with labeled objects, and removes objects
smaller than min_size. If `ar` is bool, the image is first labeled.
This leads to potentially different behavior for bool and 0-and-1
arrays.
Parameters
----------
ar : ndarray (arbitrary shape, int or bool type)
The array containing the objects of interest. If the array type is
int, the ints must be non-negative.
min_size : int, optional (default: 64)
The smallest allowable object size.
connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
The connectivity defining the neighborhood of a pixel. Used during
labelling if `ar` is bool.
out : ndarray
Array of the same shape as `ar`, into which the output is
placed. By default, a new array is created.
Raises
------
TypeError
If the input array is of an invalid type, such as float or string.
ValueError
If the input array contains negative values.
Returns
-------
out : ndarray, same shape and type as input `ar`
The input array with small connected components removed.
See Also
--------
skimage.morphology.remove_objects_by_distance
Examples
--------
>>> from skimage import morphology
>>> a = np.array([[0, 0, 0, 1, 0],
... [1, 1, 1, 0, 0],
... [1, 1, 1, 0, 1]], bool)
>>> b = morphology.remove_small_objects(a, 6)
>>> b
array([[False, False, False, False, False],
[ True, True, True, False, False],
[ True, True, True, False, False]])
>>> c = morphology.remove_small_objects(a, 7, connectivity=2)
>>> c
array([[False, False, False, True, False],
[ True, True, True, False, False],
[ True, True, True, False, False]])
>>> d = morphology.remove_small_objects(a, 6, out=a)
>>> d is a
True
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)
star(a, dtype=<class 'numpy.uint8'>)
Generates a star shaped footprint.
Start has 8 vertices and is an overlap of square of size `2*a + 1`
with its 45 degree rotated version.
The slanted sides are 45 or 135 degrees to the horizontal axis.
Parameters
----------
a : int
Parameter deciding the size of the star structural element. The side
of the square array returned is `2*a + 1 + 2*floor(a / 2)`.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
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)
white_tophat(image, footprint=None, out=None, *, mode='reflect', cval=0.0)
Return white top hat of an image.
The white top hat of an image is defined as the image minus its
morphological opening. This operation returns the bright spots of the image
that are smaller than the footprint.
Parameters
----------
image : ndarray
Image array.
footprint : ndarray or tuple, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use a cross-shaped footprint (connectivity=1). The footprint
can also be provided as a sequence of smaller footprints as described
in the notes below.
out : ndarray, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
mode : str, optional
The `mode` parameter determines how the array borders are handled.
Valid modes are: 'reflect', 'constant', 'nearest', 'mirror', 'wrap',
'max', 'min', or 'ignore'. See :func:`skimage.morphology.opening`.
Default is 'reflect'.
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.
.. versionadded:: 0.23
`mode` and `cval` were added in 0.23.
Returns
-------
out : array, same shape and type as `image`
The result of the morphological white top hat.
Notes
-----
The footprint can also be a provided as a sequence of 2-tuples where the
first element of each 2-tuple is a footprint ndarray and the second element
is an integer describing the number of times it should be iterated. For
example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
computational cost. Most of the builtin footprints such as
:func:`skimage.morphology.disk` provide an option to automatically generate
a footprint sequence of this type.
See Also
--------
black_tophat
References
----------
.. [1] https://en.wikipedia.org/wiki/Top-hat_transform
Examples
--------
>>> # Subtract gray background from bright peak
>>> import numpy as np
>>> from skimage.morphology import footprint_rectangle
>>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
... [3, 4, 5, 4, 3],
... [3, 5, 9, 5, 3],
... [3, 4, 5, 4, 3],
... [2, 3, 3, 3, 2]], dtype=np.uint8)
>>> white_tophat(bright_on_gray, footprint_rectangle((3, 3)))
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 5, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
DATA
__all__ = ['area_closing', 'area_opening', 'ball', 'binary_closing', '...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\morphology\__init__.py
scikit-image.registration
Python Library Documentation: package skimage.registration in skimage
NAME
skimage.registration - Image registration algorithms, e.g., optical flow or phase cross correlation.
PACKAGE CONTENTS
_masked_phase_cross_correlation
_optical_flow
_optical_flow_utils
_phase_cross_correlation
tests (package)
FUNCTIONS
optical_flow_ilk(reference_image, moving_image, *, radius=7, num_warp=10, gaussian=False, prefilter=False, dtype=<class 'numpy.float32'>)
Coarse to fine optical flow estimator.
The iterative Lucas-Kanade (iLK) solver is applied at each level
of the image pyramid. iLK [1]_ is a fast and robust alternative to
TVL1 algorithm although less accurate for rendering flat surfaces
and object boundaries (see [2]_).
Parameters
----------
reference_image : ndarray, shape (M, N[, P[, ...]])
The first grayscale image of the sequence.
moving_image : ndarray, shape (M, N[, P[, ...]])
The second grayscale image of the sequence.
radius : int, optional
Radius of the window considered around each pixel.
num_warp : int, optional
Number of times moving_image is warped.
gaussian : bool, optional
If True, a Gaussian kernel is used for the local
integration. Otherwise, a uniform kernel is used.
prefilter : bool, optional
Whether to prefilter the estimated optical flow before each
image warp. When True, a median filter with window size 3
along each axis is applied. This helps to remove potential
outliers.
dtype : dtype, optional
Output data type: must be floating point. Single precision
provides good results and saves memory usage and computation
time compared to double precision.
Returns
-------
flow : ndarray, shape (reference_image.ndim, M, N[, P[, ...]])
The estimated optical flow components for each axis.
Notes
-----
- The implemented algorithm is described in **Table2** of [1]_.
- Color images are not supported.
References
----------
.. [1] Le Besnerais, G., & Champagnat, F. (2005, September). Dense
optical flow by iterative local window registration. In IEEE
International Conference on Image Processing 2005 (Vol. 1,
pp. I-137). IEEE. :DOI:`10.1109/ICIP.2005.1529706`
.. [2] Plyer, A., Le Besnerais, G., & Champagnat,
F. (2016). Massively parallel Lucas Kanade optical flow for
real-time video processing applications. Journal of Real-Time
Image Processing, 11(4), 713-730. :DOI:`10.1007/s11554-014-0423-0`
Examples
--------
>>> from skimage.color import rgb2gray
>>> from skimage.data import stereo_motorcycle
>>> from skimage.registration import optical_flow_ilk
>>> reference_image, moving_image, disp = stereo_motorcycle()
>>> # --- Convert the images to gray level: color is not supported.
>>> reference_image = rgb2gray(reference_image)
>>> moving_image = rgb2gray(moving_image)
>>> flow = optical_flow_ilk(moving_image, reference_image)
optical_flow_tvl1(reference_image, moving_image, *, attachment=15, tightness=0.3, num_warp=5, num_iter=10, tol=0.0001, prefilter=False, dtype=<class 'numpy.float32'>)
Coarse to fine optical flow estimator.
The TV-L1 solver is applied at each level of the image
pyramid. TV-L1 is a popular algorithm for optical flow estimation
introduced by Zack et al. [1]_, improved in [2]_ and detailed in [3]_.
Parameters
----------
reference_image : ndarray, shape (M, N[, P[, ...]])
The first grayscale image of the sequence.
moving_image : ndarray, shape (M, N[, P[, ...]])
The second grayscale image of the sequence.
attachment : float, optional
Attachment parameter (:math:`\lambda` in [1]_). The smaller
this parameter is, the smoother the returned result will be.
tightness : float, optional
Tightness parameter (:math:`\theta` in [1]_). It should have
a small value in order to maintain attachment and
regularization parts in correspondence.
num_warp : int, optional
Number of times moving_image is warped.
num_iter : int, optional
Number of fixed point iteration.
tol : float, optional
Tolerance used as stopping criterion based on the L² distance
between two consecutive values of (u, v).
prefilter : bool, optional
Whether to prefilter the estimated optical flow before each
image warp. When True, a median filter with window size 3
along each axis is applied. This helps to remove potential
outliers.
dtype : dtype, optional
Output data type: must be floating point. Single precision
provides good results and saves memory usage and computation
time compared to double precision.
Returns
-------
flow : ndarray, shape (image0.ndim, M, N[, P[, ...]])
The estimated optical flow components for each axis.
Notes
-----
Color images are not supported.
References
----------
.. [1] Zach, C., Pock, T., & Bischof, H. (2007, September). A
duality based approach for realtime TV-L 1 optical flow. In Joint
pattern recognition symposium (pp. 214-223). Springer, Berlin,
Heidelberg. :DOI:`10.1007/978-3-540-74936-3_22`
.. [2] Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers,
D. (2009). An improved algorithm for TV-L 1 optical flow. In
Statistical and geometrical approaches to visual motion analysis
(pp. 23-45). Springer, Berlin, Heidelberg.
:DOI:`10.1007/978-3-642-03061-1_2`
.. [3] Pérez, J. S., Meinhardt-Llopis, E., & Facciolo,
G. (2013). TV-L1 optical flow estimation. Image Processing On
Line, 2013, 137-150. :DOI:`10.5201/ipol.2013.26`
Examples
--------
>>> from skimage.color import rgb2gray
>>> from skimage.data import stereo_motorcycle
>>> from skimage.registration import optical_flow_tvl1
>>> image0, image1, disp = stereo_motorcycle()
>>> # --- Convert the images to gray level: color is not supported.
>>> image0 = rgb2gray(image0)
>>> image1 = rgb2gray(image1)
>>> flow = optical_flow_tvl1(image1, image0)
phase_cross_correlation(reference_image, moving_image, *, upsample_factor=1, space='real', disambiguate=False, reference_mask=None, moving_mask=None, overlap_ratio=0.3, normalization='phase')
Efficient subpixel image translation registration by cross-correlation.
This code gives the same precision as the FFT upsampled cross-correlation
in a fraction of the computation time and with reduced memory requirements.
It obtains an initial estimate of the cross-correlation peak by an FFT and
then refines the shift estimation by upsampling the DFT only in a small
neighborhood of that estimate by means of a matrix-multiply DFT [1]_.
Parameters
----------
reference_image : array
Reference image.
moving_image : array
Image to register. Must be same dimensionality as
``reference_image``.
upsample_factor : int, optional
Upsampling factor. Images will be registered to within
``1 / upsample_factor`` of a pixel. For example
``upsample_factor == 20`` means the images will be registered
within 1/20th of a pixel. Default is 1 (no upsampling).
Not used if any of ``reference_mask`` or ``moving_mask`` is not None.
space : string, one of "real" or "fourier", optional
Defines how the algorithm interprets input data. "real" means
data will be FFT'd to compute the correlation, while "fourier"
data will bypass FFT of input data. Case insensitive. Not
used if any of ``reference_mask`` or ``moving_mask`` is not
None.
disambiguate : bool
The shift returned by this function is only accurate *modulo* the
image shape, due to the periodic nature of the Fourier transform. If
this parameter is set to ``True``, the *real* space cross-correlation
is computed for each possible shift, and the shift with the highest
cross-correlation within the overlapping area is returned.
reference_mask : ndarray
Boolean mask for ``reference_image``. The mask should evaluate
to ``True`` (or 1) on valid pixels. ``reference_mask`` should
have the same shape as ``reference_image``.
moving_mask : ndarray or None, optional
Boolean mask for ``moving_image``. The mask should evaluate to ``True``
(or 1) on valid pixels. ``moving_mask`` should have the same shape
as ``moving_image``. If ``None``, ``reference_mask`` will be used.
overlap_ratio : float, optional
Minimum allowed overlap ratio between images. The correlation for
translations corresponding with an overlap ratio lower than this
threshold will be ignored. A lower `overlap_ratio` leads to smaller
maximum translation, while a higher `overlap_ratio` leads to greater
robustness against spurious matches due to small overlap between
masked images. Used only if one of ``reference_mask`` or
``moving_mask`` is not None.
normalization : {"phase", None}
The type of normalization to apply to the cross-correlation. This
parameter is unused when masks (`reference_mask` and `moving_mask`) are
supplied.
Returns
-------
shift : ndarray
Shift vector (in pixels) required to register ``moving_image``
with ``reference_image``. Axis ordering is consistent with
the axis order of the input array.
error : float
Translation invariant normalized RMS error between
``reference_image`` and ``moving_image``. For masked cross-correlation
this error is not available and NaN is returned.
phasediff : float
Global phase difference between the two images (should be
zero if images are non-negative). For masked cross-correlation
this phase difference is not available and NaN is returned.
Notes
-----
The use of cross-correlation to estimate image translation has a long
history dating back to at least [2]_. The "phase correlation"
method (selected by ``normalization="phase"``) was first proposed in [3]_.
Publications [1]_ and [2]_ use an unnormalized cross-correlation
(``normalization=None``). Which form of normalization is better is
application-dependent. For example, the phase correlation method works
well in registering images under different illumination, but is not very
robust to noise. In a high noise scenario, the unnormalized method may be
preferable.
When masks are provided, a masked normalized cross-correlation algorithm is
used [5]_, [6]_.
References
----------
.. [1] Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,
"Efficient subpixel image registration algorithms,"
Optics Letters 33, 156-158 (2008). :DOI:`10.1364/OL.33.000156`
.. [2] P. Anuta, Spatial registration of multispectral and multitemporal
digital imagery using fast Fourier transform techniques, IEEE Trans.
Geosci. Electron., vol. 8, no. 4, pp. 353–368, Oct. 1970.
:DOI:`10.1109/TGE.1970.271435`.
.. [3] C. D. Kuglin D. C. Hines. The phase correlation image alignment
method, Proceeding of IEEE International Conference on Cybernetics
and Society, pp. 163-165, New York, NY, USA, 1975, pp. 163–165.
.. [4] James R. Fienup, "Invariant error metrics for image reconstruction"
Optics Letters 36, 8352-8357 (1997). :DOI:`10.1364/AO.36.008352`
.. [5] Dirk Padfield. Masked Object Registration in the Fourier Domain.
IEEE Transactions on Image Processing, vol. 21(5),
pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402`
.. [6] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and
Pattern Recognition, pp. 2918-2925 (2010).
:DOI:`10.1109/CVPR.2010.5540032`
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\registration\__init__.py
scikit-image.restoration
Python Library Documentation: package skimage.restoration in skimage
NAME
skimage.restoration - Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.
PACKAGE CONTENTS
_cycle_spin
_denoise
_denoise_cy
_inpaint
_nl_means_denoising
_rolling_ball
_rolling_ball_cy
_unwrap_1d
_unwrap_2d
_unwrap_3d
deconvolution
inpaint
j_invariant
non_local_means
tests (package)
uft
unwrap
FUNCTIONS
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
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)
cycle_spin(x, func, max_shifts, shift_steps=1, num_workers=None, func_kw=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.
num_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
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)
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)
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)
denoise_tv_bregman(image, weight=5.0, max_num_iter=100, eps=0.001, isotropic=True, *, channel_axis=None)
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 : boolean, 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
denoise_tv_chambolle(image, weight=0.1, eps=0.0002, max_num_iter=200, *, channel_axis=None)
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)
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 : string, 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
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('pywt')
>>> 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)
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
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
--------
.. testsetup::
>>> import pytest; _ = pytest.importorskip('pywt')
>>> 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)
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 : boolean, 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)
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 : boolean, 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
rolling_ball(image, *, radius=100, kernel=None, nansafe=False, num_threads=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.
num_threads: int, optional
The maximum number of threads to use. If ``None``, the function uses
the OpenMP default value; typically, it is 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.
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
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. See below.
clip : boolean, 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.
Other parameters
----------------
The keys of ``user_params`` 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 (None by default)
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.
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
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.
wiener(image, psf, balance, reg=None, is_real=True, clip=True)
Wiener-Hunt deconvolution
Return the deconvolution with a Wiener-Hunt approach (i.e. with
Fourier diagonalisation).
Parameters
----------
image : ndarray
Input degraded image (can be n-dimensional).
psf : ndarray
Point Spread Function. This is assumed to be the impulse
response (input image space) if the data-type is real, or the
transfer function (Fourier space) if the data-type is
complex. There is no constraints on the shape of the impulse
response. The transfer function must be of shape
`(N1, N2, ..., ND)` if `is_real is True`,
`(N1, N2, ..., ND // 2 + 1)` otherwise (see `np.fft.rfftn`).
balance : float
The regularisation parameter value that tunes the balance
between the data adequacy that improve frequency restoration
and the prior adequacy that reduce frequency restoration (to
avoid noise artifacts).
reg : ndarray, optional
The regularisation operator. The Laplacian by default. It can
be an impulse response or a transfer function, as for the
psf. Shape constraint is the same as for the `psf` parameter.
is_real : boolean, optional
True by default. Specify if ``psf`` and ``reg`` are provided
with hermitian hypothesis, that is only half of the frequency
plane is provided (due to the redundancy of Fourier transform
of real signal). It's apply only if ``psf`` and/or ``reg`` are
provided as transfer function. For the hermitian property see
``uft`` module or ``np.fft.rfftn``.
clip : boolean, optional
True by default. If True, pixel values of the result above 1 or
under -1 are thresholded for skimage pipeline compatibility.
Returns
-------
im_deconv : (M, N) ndarray
The deconvolved image.
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.wiener(img, psf, 0.1)
Notes
-----
This function applies the Wiener filter to a noisy and 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 [Hunt] below)
and :math:`\Lambda_D` the filter to penalize the restored image
frequencies (Laplacian by default, that is penalization of high
frequency). The parameter :math:`\lambda` tunes the balance
between the data (that tends to increase high frequency, even
those coming from noise), and the regularization.
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) introduce
image smoothness or pixel correlation. It can also be interpreted
as high-frequency penalization to compensate 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
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\restoration\__init__.py
scikit-image.segmentation
Python Library Documentation: package skimage.segmentation in skimage
NAME
skimage.segmentation - Algorithms to partition images into meaningful regions or boundaries.
PACKAGE CONTENTS
_chan_vese
_clear_border
_expand_labels
_felzenszwalb
_felzenszwalb_cy
_join
_quickshift
_quickshift_cy
_slic
_watershed
_watershed_cy
active_contour_model
boundaries
morphsnakes
random_walker_segmentation
slic_superpixels
tests (package)
FUNCTIONS
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 : string, 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
chan_vese(image, mu=0.25, lambda1=1.0, lambda2=1.0, tol=0.001, max_num_iter=500, dt=0.5, init_level_set='checkerboard', extended_output=False)
Chan-Vese segmentation algorithm.
Active contour model by evolving a level set. Can be used to
segment objects without clearly defined boundaries.
Parameters
----------
image : (M, N) ndarray
Grayscale image to be segmented.
mu : float, optional
'edge length' weight parameter. Higher `mu` values will
produce a 'round' edge, while values closer to zero will
detect smaller objects.
lambda1 : float, optional
'difference from average' weight parameter for the output
region with value 'True'. If it is lower than `lambda2`, this
region will have a larger range of values than the other.
lambda2 : float, optional
'difference from average' weight parameter for the output
region with value 'False'. If it is lower than `lambda1`, this
region will have a larger range of values than the other.
tol : float, positive, optional
Level set variation tolerance between iterations. If the
L2 norm difference between the level sets of successive
iterations normalized by the area of the image is below this
value, the algorithm will assume that the solution was
reached.
max_num_iter : uint, optional
Maximum number of iterations allowed before the algorithm
interrupts itself.
dt : float, optional
A multiplication factor applied at calculations for each step,
serves to accelerate the algorithm. While higher values may
speed up the algorithm, they may also lead to convergence
problems.
init_level_set : str or (M, N) ndarray, optional
Defines the starting level set used by the algorithm.
If a string is inputted, a level set that matches the image
size will automatically be generated. Alternatively, it is
possible to define a custom level set, which should be an
array of float values, with the same shape as 'image'.
Accepted string values are as follows.
'checkerboard'
the starting level set is defined as
sin(x/5*pi)*sin(y/5*pi), where x and y are pixel
coordinates. This level set has fast convergence, but may
fail to detect implicit edges.
'disk'
the starting level set is defined as the opposite
of the distance from the center of the image minus half of
the minimum value between image width and image height.
This is somewhat slower, but is more likely to properly
detect implicit edges.
'small disk'
the starting level set is defined as the
opposite of the distance from the center of the image
minus a quarter of the minimum value between image width
and image height.
extended_output : bool, optional
If set to True, the return value will be a tuple containing
the three return values (see below). If set to False which
is the default value, only the 'segmentation' array will be
returned.
Returns
-------
segmentation : (M, N) ndarray, bool
Segmentation produced by the algorithm.
phi : (M, N) ndarray of floats
Final level set computed by the algorithm.
energies : list of floats
Shows the evolution of the 'energy' for each step of the
algorithm. This should allow to check whether the algorithm
converged.
Notes
-----
The Chan-Vese Algorithm is designed to segment objects without
clearly defined boundaries. This algorithm is based on level sets
that are evolved iteratively to minimize an energy, which is
defined by weighted values corresponding to the sum of differences
intensity from the average value outside the segmented region, the
sum of differences from the average value inside the segmented
region, and a term which is dependent on the length of the
boundary of the segmented region.
This algorithm was first proposed by Tony Chan and Luminita Vese,
in a publication entitled "An Active Contour Model Without Edges"
[1]_.
This implementation of the algorithm is somewhat simplified in the
sense that the area factor 'nu' described in the original paper is
not implemented, and is only suitable for grayscale images.
Typical values for `lambda1` and `lambda2` are 1. If the
'background' is very different from the segmented object in terms
of distribution (for example, a uniform black image with figures
of varying intensity), then these values should be different from
each other.
Typical values for mu are between 0 and 1, though higher values
can be used when dealing with shapes with very ill-defined
contours.
The 'energy' which this algorithm tries to minimize is defined
as the sum of the differences from the average within the region
squared and weighed by the 'lambda' factors to which is added the
length of the contour multiplied by the 'mu' factor.
Supports 2D grayscale images only, and does not implement the area
term described in the original article.
References
----------
.. [1] An Active Contour Model without Edges, Tony Chan and
Luminita Vese, Scale-Space Theories in Computer Vision,
1999, :DOI:`10.1007/3-540-48236-9_13`
.. [2] Chan-Vese Segmentation, Pascal Getreuer Image Processing On
Line, 2 (2012), pp. 214-224,
:DOI:`10.5201/ipol.2012.g-cv`
.. [3] The Chan-Vese Algorithm - Project Report, Rami Cohen, 2011
:arXiv:`1107.2782`
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
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]])
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
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]])
felzenszwalb(image, scale=1, sigma=0.8, min_size=20, *, channel_axis=-1)
Computes Felsenszwalb's efficient graph based image segmentation.
Produces an oversegmentation of a multichannel (i.e. RGB) image
using a fast, minimum spanning tree based clustering on the image grid.
The parameter ``scale`` sets an observation level. Higher scale means
less and larger segments. ``sigma`` is the diameter of a Gaussian kernel,
used for smoothing the image prior to segmentation.
The number of produced segments as well as their size can only be
controlled indirectly through ``scale``. Segment size within an image can
vary greatly depending on local contrast.
For RGB images, the algorithm uses the euclidean distance between pixels in
color space.
Parameters
----------
image : (M, N[, 3]) ndarray
Input image.
scale : float
Free parameter. Higher means larger clusters.
sigma : float
Width (standard deviation) of Gaussian kernel used in preprocessing.
min_size : int
Minimum component size. Enforced using postprocessing.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
segment_mask : (M, N) ndarray
Integer mask indicating segment labels.
References
----------
.. [1] Efficient graph-based image segmentation, Felzenszwalb, P.F. and
Huttenlocher, D.P. International Journal of Computer Vision, 2004
Notes
-----
The `k` parameter used in the original paper renamed to `scale` here.
Examples
--------
>>> from skimage.segmentation import felzenszwalb
>>> from skimage.data import coffee
>>> img = coffee()
>>> segments = felzenszwalb(img, scale=3.0, sigma=0.95, min_size=5)
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]])
flood(image, seed_point, *, footprint=None, connectivity=None, tolerance=None)
Mask corresponding to a flood fill.
Starting at a specific `seed_point`, connected points equal or within
`tolerance` of the seed value are found.
Parameters
----------
image : ndarray
An n-dimensional array.
seed_point : tuple or int
The point in `image` used as the starting point for the flood fill. If
the image is 1D, this point may be given as an integer.
footprint : ndarray, optional
The footprint (structuring element) used to determine the neighborhood
of each evaluated pixel. It must contain only 1's and 0's, have the
same number of dimensions as `image`. If not given, all adjacent pixels
are considered as part of the neighborhood (fully connected).
connectivity : int, optional
A number used to determine the neighborhood of each evaluated pixel.
Adjacent pixels whose squared distance from the center is less than or
equal to `connectivity` are considered neighbors. Ignored if
`footprint` is not None.
tolerance : float or int, optional
If None (default), adjacent values must be strictly equal to the
initial value of `image` at `seed_point`. This is fastest. If a value
is given, a comparison will be done at every point and if within
tolerance of the initial value will also be filled (inclusive).
Returns
-------
mask : ndarray
A Boolean array with the same shape as `image` is returned, with True
values for areas connected to and equal (or within tolerance of) the
seed point. All other values are False.
Notes
-----
The conceptual analogy of this operation is the 'paint bucket' tool in many
raster graphics programs. This function returns just the mask
representing the fill.
If indices are desired rather than masks for memory reasons, the user can
simply run `numpy.nonzero` on the result, save the indices, and discard
this mask.
Examples
--------
>>> from skimage.morphology import flood
>>> image = np.zeros((4, 7), dtype=int)
>>> image[1:3, 1:3] = 1
>>> image[3, 0] = 1
>>> image[1:3, 4:6] = 2
>>> image[3, 6] = 3
>>> image
array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 0],
[0, 1, 1, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, with full connectivity (diagonals included):
>>> mask = flood(image, (1, 1))
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[5, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, excluding diagonal points (connectivity 1):
>>> mask = flood(image, (1, 1), connectivity=1)
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill with a tolerance:
>>> mask = flood(image, (0, 0), tolerance=1)
>>> image_flooded = image.copy()
>>> image_flooded[mask] = 5
>>> image_flooded
array([[5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 5, 5, 3]])
flood_fill(image, seed_point, new_value, *, footprint=None, connectivity=None, tolerance=None, in_place=False)
Perform flood filling on an image.
Starting at a specific `seed_point`, connected points equal or within
`tolerance` of the seed value are found, then set to `new_value`.
Parameters
----------
image : ndarray
An n-dimensional array.
seed_point : tuple or int
The point in `image` used as the starting point for the flood fill. If
the image is 1D, this point may be given as an integer.
new_value : `image` type
New value to set the entire fill. This must be chosen in agreement
with the dtype of `image`.
footprint : ndarray, optional
The footprint (structuring element) used to determine the neighborhood
of each evaluated pixel. It must contain only 1's and 0's, have the
same number of dimensions as `image`. If not given, all adjacent pixels
are considered as part of the neighborhood (fully connected).
connectivity : int, optional
A number used to determine the neighborhood of each evaluated pixel.
Adjacent pixels whose squared distance from the center is less than or
equal to `connectivity` are considered neighbors. Ignored if
`footprint` is not None.
tolerance : float or int, optional
If None (default), adjacent values must be strictly equal to the
value of `image` at `seed_point` to be filled. This is fastest.
If a tolerance is provided, adjacent points with values within plus or
minus tolerance from the seed point are filled (inclusive).
in_place : bool, optional
If True, flood filling is applied to `image` in place. If False, the
flood filled result is returned without modifying the input `image`
(default).
Returns
-------
filled : ndarray
An array with the same shape as `image` is returned, with values in
areas connected to and equal (or within tolerance of) the seed point
replaced with `new_value`.
Notes
-----
The conceptual analogy of this operation is the 'paint bucket' tool in many
raster graphics programs.
Examples
--------
>>> from skimage.morphology import flood_fill
>>> image = np.zeros((4, 7), dtype=int)
>>> image[1:3, 1:3] = 1
>>> image[3, 0] = 1
>>> image[1:3, 4:6] = 2
>>> image[3, 6] = 3
>>> image
array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 0],
[0, 1, 1, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, with full connectivity (diagonals included):
>>> flood_fill(image, (1, 1), 5)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[5, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, excluding diagonal points (connectivity 1):
>>> flood_fill(image, (1, 1), 5, connectivity=1)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill with a tolerance:
>>> flood_fill(image, (0, 0), 5, tolerance=1)
array([[5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 5, 5, 3]])
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`.
join_segmentations(s1, s2, return_mapping: bool = False)
Return the join of the two input segmentations.
The join J of S1 and S2 is defined as the segmentation in which two
voxels are in the same segment if and only if they are in the same
segment in *both* S1 and S2.
Parameters
----------
s1, s2 : numpy arrays
s1 and s2 are label fields of the same shape.
return_mapping : bool, optional
If true, return mappings for joined segmentation labels to the original labels.
Returns
-------
j : numpy array
The join segmentation of s1 and s2.
map_j_to_s1 : ArrayMap, optional
Mapping from labels of the joined segmentation j to labels of s1.
map_j_to_s2 : ArrayMap, optional
Mapping from labels of the joined segmentation j to labels of s2.
Examples
--------
>>> from skimage.segmentation import join_segmentations
>>> s1 = np.array([[0, 0, 1, 1],
... [0, 2, 1, 1],
... [2, 2, 2, 1]])
>>> s2 = np.array([[0, 1, 1, 0],
... [0, 1, 1, 0],
... [0, 1, 1, 1]])
>>> join_segmentations(s1, s2)
array([[0, 1, 3, 2],
[0, 5, 3, 2],
[4, 5, 5, 3]])
>>> j, m1, m2 = join_segmentations(s1, s2, return_mapping=True)
>>> m1
ArrayMap(array([0, 1, 2, 3, 4, 5]), array([0, 0, 1, 1, 2, 2]))
>>> np.all(m1[j] == s1)
True
>>> np.all(m2[j] == s2)
True
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
morphological_chan_vese(image, num_iter, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=<function <lambda> at 0x000002539A817B00>)
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`
morphological_geodesic_active_contour(gimage, num_iter, init_level_set='disk', smoothing=1, threshold='auto', balloon=0, iter_callback=<function <lambda> at 0x000002539A817C40>)
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`
quickshift(image, ratio=1.0, kernel_size=5, max_dist=10, return_tree=False, sigma=0, convert2lab=True, rng=42, *, channel_axis=-1)
Segment image using quickshift clustering in Color-(x,y) space.
Produces an oversegmentation of the image using the quickshift mode-seeking
algorithm.
Parameters
----------
image : (M, N, C) ndarray
Input image. The axis corresponding to color channels can be specified
via the `channel_axis` argument.
ratio : float, optional, between 0 and 1
Balances color-space proximity and image-space proximity.
Higher values give more weight to color-space.
kernel_size : float, optional
Width of Gaussian kernel used in smoothing the
sample density. Higher means fewer clusters.
max_dist : float, optional
Cut-off point for data distances.
Higher means fewer clusters.
return_tree : bool, optional
Whether to return the full segmentation hierarchy tree and distances.
sigma : float, optional
Width for Gaussian smoothing as preprocessing. Zero means no smoothing.
convert2lab : bool, optional
Whether the input should be converted to Lab colorspace prior to
segmentation. For this purpose, the input is assumed to be RGB.
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
The PRNG is used to break ties, and is seeded with 42 by default.
channel_axis : int, optional
The axis of `image` corresponding to color channels. Defaults to the
last axis.
Returns
-------
segment_mask : (M, N) ndarray
Integer mask indicating segment labels.
Notes
-----
The authors advocate to convert the image to Lab color space prior to
segmentation, though this is not strictly necessary. For this to work, the
image must be given in RGB format.
References
----------
.. [1] Quick shift and kernel methods for mode seeking,
Vedaldi, A. and Soatto, S.
European Conference on Computer Vision, 2008
random_walker(data, labels, beta=130, mode='cg_j', tol=0.001, copy=True, return_full_prob=False, spacing=None, *, prob_tol=0.001, channel_axis=None)
Random walker algorithm for segmentation from markers.
Random walker algorithm is implemented for gray-level or multichannel
images.
Parameters
----------
data : (M, N[, P][, C]) ndarray
Image to be segmented in phases. Gray-level `data` can be two- or
three-dimensional; multichannel data can be three- or four-
dimensional with `channel_axis` specifying the dimension containing
channels. Data spacing is assumed isotropic unless the `spacing`
keyword argument is used.
labels : (M, N[, P]) array of ints
Array of seed markers labeled with different positive integers
for different phases. Zero-labeled pixels are unlabeled pixels.
Negative labels correspond to inactive pixels that are not taken
into account (they are removed from the graph). If labels are not
consecutive integers, the labels array will be transformed so that
labels are consecutive. In the multichannel case, `labels` should have
the same shape as a single channel of `data`, i.e. without the final
dimension denoting channels.
beta : float, optional
Penalization coefficient for the random walker motion
(the greater `beta`, the more difficult the diffusion).
mode : string, available options {'cg', 'cg_j', 'cg_mg', 'bf'}
Mode for solving the linear system in the random walker algorithm.
- 'bf' (brute force): an LU factorization of the Laplacian is
computed. This is fast for small images (<1024x1024), but very slow
and memory-intensive for large images (e.g., 3-D volumes).
- 'cg' (conjugate gradient): the linear system is solved iteratively
using the Conjugate Gradient method from scipy.sparse.linalg. This is
less memory-consuming than the brute force method for large images,
but it is quite slow.
- 'cg_j' (conjugate gradient with Jacobi preconditionner): the
Jacobi preconditionner is applied during the Conjugate
gradient method iterations. This may accelerate the
convergence of the 'cg' method.
- 'cg_mg' (conjugate gradient with multigrid preconditioner): a
preconditioner is computed using a multigrid solver, then the
solution is computed with the Conjugate Gradient method. This mode
requires that the pyamg module is installed.
tol : float, optional
Tolerance to achieve when solving the linear system using
the conjugate gradient based modes ('cg', 'cg_j' and 'cg_mg').
copy : bool, optional
If copy is False, the `labels` array will be overwritten with
the result of the segmentation. Use copy=False if you want to
save on memory.
return_full_prob : bool, optional
If True, the probability that a pixel belongs to each of the
labels will be returned, instead of only the most likely
label.
spacing : iterable of floats, optional
Spacing between voxels in each spatial dimension. If `None`, then
the spacing between pixels/voxels in each dimension is assumed 1.
prob_tol : float, optional
Tolerance on the resulting probability to be in the interval [0, 1].
If the tolerance is not satisfied, a warning is displayed.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
output : ndarray
* If `return_full_prob` is False, array of ints of same shape
and data type as `labels`, in which each pixel has been
labeled according to the marker that reached the pixel first
by anisotropic diffusion.
* If `return_full_prob` is True, array of floats of shape
`(nlabels, labels.shape)`. `output[label_nb, i, j]` is the
probability that label `label_nb` reaches the pixel `(i, j)`
first.
See Also
--------
skimage.segmentation.watershed
A segmentation algorithm based on mathematical morphology
and "flooding" of regions from markers.
Notes
-----
Multichannel inputs are scaled with all channel data combined. Ensure all
channels are separately normalized prior to running this algorithm.
The `spacing` argument is specifically for anisotropic datasets, where
data points are spaced differently in one or more spatial dimensions.
Anisotropic data is commonly encountered in medical imaging.
The algorithm was first proposed in [1]_.
The algorithm solves the diffusion equation at infinite times for
sources placed on markers of each phase in turn. A pixel is labeled with
the phase that has the greatest probability to diffuse first to the pixel.
The diffusion equation is solved by minimizing x.T L x for each phase,
where L is the Laplacian of the weighted graph of the image, and x is
the probability that a marker of the given phase arrives first at a pixel
by diffusion (x=1 on markers of the phase, x=0 on the other markers, and
the other coefficients are looked for). Each pixel is attributed the label
for which it has a maximal value of x. The Laplacian L of the image
is defined as:
- L_ii = d_i, the number of neighbors of pixel i (the degree of i)
- L_ij = -w_ij if i and j are adjacent pixels
The weight w_ij is a decreasing function of the norm of the local gradient.
This ensures that diffusion is easier between pixels of similar values.
When the Laplacian is decomposed into blocks of marked and unmarked
pixels::
L = M B.T
B A
with first indices corresponding to marked pixels, and then to unmarked
pixels, minimizing x.T L x for one phase amount to solving::
A x = - B x_m
where x_m = 1 on markers of the given phase, and 0 on other markers.
This linear system is solved in the algorithm using a direct method for
small images, and an iterative method for larger images.
References
----------
.. [1] Leo Grady, Random walks for image segmentation, IEEE Trans Pattern
Anal Mach Intell. 2006 Nov;28(11):1768-83.
:DOI:`10.1109/TPAMI.2006.233`.
Examples
--------
>>> rng = np.random.default_rng()
>>> a = np.zeros((10, 10)) + 0.2 * rng.random((10, 10))
>>> a[5:8, 5:8] += 1
>>> b = np.zeros_like(a, dtype=np.int32)
>>> b[3, 3] = 1 # Marker for first phase
>>> b[6, 6] = 2 # Marker for second phase
>>> random_walker(a, b) # doctest: +SKIP
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
[1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
[1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32)
relabel_sequential(label_field, offset=1)
Relabel arbitrary labels to {`offset`, ... `offset` + number_of_labels}.
This function also returns the forward map (mapping the original labels to
the reduced labels) and the inverse map (mapping the reduced labels back
to the original ones).
Parameters
----------
label_field : numpy array of int, arbitrary shape
An array of labels, which must be non-negative integers.
offset : int, optional
The return labels will start at `offset`, which should be
strictly positive.
Returns
-------
relabeled : numpy array of int, same shape as `label_field`
The input label field with labels mapped to
{offset, ..., number_of_labels + offset - 1}.
The data type will be the same as `label_field`, except when
offset + number_of_labels causes overflow of the current data type.
forward_map : ArrayMap
The map from the original label space to the returned label
space. Can be used to re-apply the same mapping. See examples
for usage. The output data type will be the same as `relabeled`.
inverse_map : ArrayMap
The map from the new label space to the original space. This
can be used to reconstruct the original label field from the
relabeled one. The output data type will be the same as `label_field`.
Notes
-----
The label 0 is assumed to denote the background and is never remapped.
The forward map can be extremely big for some inputs, since its
length is given by the maximum of the label field. However, in most
situations, ``label_field.max()`` is much smaller than
``label_field.size``, and in these cases the forward map is
guaranteed to be smaller than either the input or output images.
Examples
--------
>>> from skimage.segmentation import relabel_sequential
>>> label_field = np.array([1, 1, 5, 5, 8, 99, 42])
>>> relab, fw, inv = relabel_sequential(label_field)
>>> relab
array([1, 1, 2, 2, 3, 5, 4])
>>> print(fw)
ArrayMap:
1 → 1
5 → 2
8 → 3
42 → 4
99 → 5
>>> np.array(fw)
array([0, 1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5])
>>> np.array(inv)
array([ 0, 1, 5, 8, 42, 99])
>>> (fw[label_field] == relab).all()
True
>>> (inv[relab] == label_field).all()
True
>>> relab, fw, inv = relabel_sequential(label_field, offset=5)
>>> relab
array([5, 5, 6, 6, 7, 9, 8])
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)
watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False)
Find watershed basins in an image flooded from given markers.
Parameters
----------
image : (M, N[, ...]) ndarray
Data array where the lowest value points are labeled first.
markers : int, or (M, N[, ...]) ndarray of int, optional
The desired number of basins, or an array marking the basins with the
values to be assigned in the label matrix. Zero means not a marker. If
None, the (default) markers are determined as the local minima of
`image`. Specifically, the computation is equivalent to applying
:func:`skimage.morphology.local_minima` onto `image`, followed by
:func:`skimage.measure.label` onto the result (with the same given
`connectivity`). Generally speaking, users are encouraged to pass
markers explicitly.
connectivity : int or ndarray, optional
The neighborhood connectivity. An integer is interpreted as in
``scipy.ndimage.generate_binary_structure``, as the maximum number
of orthogonal steps to reach a neighbor. An array is directly
interpreted as a footprint (structuring element). Default value is 1.
In 2D, 1 gives a 4-neighborhood while 2 gives an 8-neighborhood.
offset : array_like of shape image.ndim, optional
The coordinates of the center of the footprint.
mask : (M, N[, ...]) ndarray of bools or 0's and 1's, optional
Array of same shape as `image`. Only points at which mask == True
will be labeled.
compactness : float, optional
Use compact watershed [1]_ with given compactness parameter.
Higher values result in more regularly-shaped watershed basins.
watershed_line : bool, optional
If True, a one-pixel wide line separates the regions
obtained by the watershed algorithm. The line has the label 0.
Note that the method used for adding this line expects that
marker regions are not adjacent; the watershed line may not catch
borders between adjacent marker regions.
Returns
-------
out : ndarray
A labeled matrix of the same type and shape as `markers`.
See Also
--------
skimage.segmentation.random_walker
A segmentation algorithm based on anisotropic diffusion, usually
slower than the watershed but with good results on noisy data and
boundaries with holes.
Notes
-----
This function implements a watershed algorithm [2]_ [3]_ that apportions
pixels into marked basins. The algorithm uses a priority queue to hold
the pixels with the metric for the priority queue being pixel value, then
the time of entry into the queue -- this settles ties in favor of the
closest marker.
Some ideas are taken from [4]_.
The most important insight in the paper is that entry time onto the queue
solves two problems: a pixel should be assigned to the neighbor with the
largest gradient or, if there is no gradient, pixels on a plateau should
be split between markers on opposite sides.
This implementation converts all arguments to specific, lowest common
denominator types, then passes these to a C algorithm.
Markers can be determined manually, or automatically using for example
the local minima of the gradient of the image, or the local maxima of the
distance function to the background for separating overlapping objects
(see example).
References
----------
.. [1] P. Neubert and P. Protzel, "Compact Watershed and Preemptive SLIC:
On Improving Trade-offs of Superpixel Segmentation Algorithms,"
2014 22nd International Conference on Pattern Recognition,
Stockholm, Sweden, 2014, pp. 996-1001, :DOI:`10.1109/ICPR.2014.181`
https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf
.. [2] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29
.. [3] https://web.archive.org/web/20180702213110/http://cmm.ensmp.fr/~beucher/wtshed.html
.. [4] P. J. Soille and M. M. Ansoult, "Automated basin delineation from
digital elevation models using mathematical morphology," Signal
Processing, 20(2):171-182, :DOI:`10.1016/0165-1684(90)90127-K`
Examples
--------
The watershed algorithm is useful to separate overlapping objects.
We first generate an initial image with two overlapping circles:
>>> x, y = np.indices((80, 80))
>>> x1, y1, x2, y2 = 28, 28, 44, 52
>>> r1, r2 = 16, 20
>>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2
>>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2
>>> image = np.logical_or(mask_circle1, mask_circle2)
Next, we want to separate the two circles. We generate markers at the
maxima of the distance to the background:
>>> from scipy import ndimage as ndi
>>> distance = ndi.distance_transform_edt(image)
>>> from skimage.feature import peak_local_max
>>> max_coords = peak_local_max(distance, labels=image,
... footprint=np.ones((3, 3)))
>>> local_maxima = np.zeros_like(image, dtype=bool)
>>> local_maxima[tuple(max_coords.T)] = True
>>> markers = ndi.label(local_maxima)[0]
Finally, we run the watershed on the image and markers:
>>> labels = watershed(-distance, markers, mask=image)
The algorithm works also for 3D images, and can be used for example to
separate overlapping spheres.
DATA
__all__ = ['expand_labels', 'random_walker', 'active_contour', 'felzen...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\segmentation\__init__.py
scikit-image.transform
Python Library Documentation: package skimage.transform in skimage
NAME
skimage.transform - Geometric and other transformations, e.g., rotations, Radon transform.
DESCRIPTION
- Geometric transformation:
These transforms change the shape or position of an image.
They are useful for tasks such as image registration,
alignment, and geometric correction.
Examples: :class:`~skimage.transform.AffineTransform`,
:class:`~skimage.transform.ProjectiveTransform`,
:class:`~skimage.transform.EuclideanTransform`.
- Image resizing and rescaling:
These transforms change the size or resolution of an image.
They are useful for tasks such as down-sampling an image to
reduce its size or up-sampling an image to increase its resolution.
Examples: :func:`~skimage.transform.resize`,
:func:`~skimage.transform.rescale`.
- Feature detection and extraction:
These transforms identify and extract specific features or
patterns in an image. They are useful for tasks such as object
detection, image segmentation, and feature matching.
Examples: :func:`~skimage.transform.hough_circle`,
:func:`~skimage.transform.pyramid_expand`,
:func:`~skimage.transform.radon`.
- Image transformation:
These transforms change the appearance of an image without changing its
content. They are useful for tasks such a creating image mosaics,
applying artistic effects, and visualizing image data.
Examples: :func:`~skimage.transform.warp`,
:func:`~skimage.transform.iradon`.
PACKAGE CONTENTS
_geometric
_hough_transform
_radon_transform
_thin_plate_splines
_warps
_warps_cy
finite_radon_transform
hough_transform
integral
pyramids
radon_transform
tests (package)
CLASSES
builtins.object
skimage.transform._thin_plate_splines.ThinPlateSplineTransform
skimage.transform._geometric._GeometricTransform(abc.ABC)
skimage.transform._geometric.FundamentalMatrixTransform
skimage.transform._geometric.EssentialMatrixTransform
skimage.transform._geometric.PiecewiseAffineTransform
skimage.transform._geometric.PolynomialTransform
skimage.transform._geometric.ProjectiveTransform
skimage.transform._geometric.AffineTransform
skimage.transform._geometric.EuclideanTransform
skimage.transform._geometric.SimilarityTransform
class AffineTransform(ProjectiveTransform)
| AffineTransform(matrix=None, scale=None, rotation=None, shear=None, translation=None, *, dimensionality=2)
|
| Affine transformation.
|
| Has the following form::
|
| X = a0 * x + a1 * y + a2
| = sx * x * [cos(rotation) + tan(shear_y) * sin(rotation)]
| - sy * y * [tan(shear_x) * cos(rotation) + sin(rotation)]
| + translation_x
|
| Y = b0 * x + b1 * y + b2
| = sx * x * [sin(rotation) - tan(shear_y) * cos(rotation)]
| - sy * y * [tan(shear_x) * sin(rotation) - cos(rotation)]
| + translation_y
|
| where ``sx`` and ``sy`` are scale factors in the x and y directions.
|
| This is equivalent to applying the operations in the following order:
|
| 1. Scale
| 2. Shear
| 3. Rotate
| 4. Translate
|
| The homogeneous transformation matrix is::
|
| [[a0 a1 a2]
| [b0 b1 b2]
| [0 0 1]]
|
| In 2D, the transformation parameters can be given as the homogeneous
| transformation matrix, above, or as the implicit parameters, scale,
| rotation, shear, and translation in x (a2) and y (b2). For 3D and higher,
| only the matrix form is allowed.
|
| In narrower transforms, such as the Euclidean (only rotation and
| translation) or Similarity (rotation, translation, and a global scale
| factor) transforms, it is possible to specify 3D transforms using implicit
| parameters also.
|
| Parameters
| ----------
| matrix : (D+1, D+1) array_like, optional
| Homogeneous transformation matrix. If this matrix is provided, it is an
| error to provide any of scale, rotation, shear, or translation.
| scale : {s as float or (sx, sy) as array, list or tuple}, optional
| Scale factor(s). If a single value, it will be assigned to both
| sx and sy. Only available for 2D.
|
| .. versionadded:: 0.17
| Added support for supplying a single scalar value.
| rotation : float, optional
| Rotation angle, clockwise, as radians. Only available for 2D.
| shear : float or 2-tuple of float, optional
| The x and y shear angles, clockwise, by which these axes are
| rotated around the origin [2].
| If a single value is given, take that to be the x shear angle, with
| the y angle remaining 0. Only available in 2D.
| translation : (tx, ty) as array, list or tuple, optional
| Translation parameters. Only available for 2D.
| dimensionality : int, optional
| The dimensionality of the transform. This is not used if any other
| parameters are provided.
|
| Attributes
| ----------
| params : (D+1, D+1) array
| Homogeneous transformation matrix.
|
| Raises
| ------
| ValueError
| If both ``matrix`` and any of the other parameters are provided.
|
| Examples
| --------
| >>> import numpy as np
| >>> import skimage as ski
| >>> img = ski.data.astronaut()
|
| Define source and destination points:
|
| >>> src = np.array([[150, 150],
| ... [250, 100],
| ... [150, 200]])
| >>> dst = np.array([[200, 200],
| ... [300, 150],
| ... [150, 400]])
|
| Estimate the transformation matrix:
|
| >>> tform = ski.transform.AffineTransform()
| >>> tform.estimate(src, dst)
| True
|
| Apply the transformation:
|
| >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)
|
| References
| ----------
| .. [1] Wikipedia, "Affine transformation",
| https://en.wikipedia.org/wiki/Affine_transformation#Image_transformation
| .. [2] Wikipedia, "Shear mapping",
| https://en.wikipedia.org/wiki/Shear_mapping
|
| Method resolution order:
| AffineTransform
| ProjectiveTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, matrix=None, scale=None, rotation=None, shear=None, translation=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| rotation
|
| scale
|
| shear
|
| translation
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from ProjectiveTransform:
|
| __add__(self, other)
| Combine this transformation with another.
|
| __array__(self, dtype=None, copy=None)
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, D) array_like
| Source coordinates.
|
| Returns
| -------
| coords_out : (N, D) array
| Destination coordinates.
|
| __nice__(self)
| common 'paramstr' used by __str__ and __repr__
|
| __repr__(self)
| Add standard repr formatting around a __nice__ string
|
| __str__(self)
| Add standard str formatting around a __nice__ string
|
| estimate(self, src, dst, weights=None)
| Estimate the transformation from a set of corresponding points.
|
| You can determine the over-, well- and under-determined parameters
| with the total least-squares method.
|
| Number of source and destination coordinates must match.
|
| The transformation is defined as::
|
| X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
| Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)
|
| These equations can be transformed to the following form::
|
| 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
| 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y
|
| which exist for each set of corresponding points, so we have a set of
| N * 2 equations. The coefficients appear linearly so we can write
| A x = 0, where::
|
| A = [[x y 1 0 0 0 -x*X -y*X -X]
| [0 0 0 x y 1 -x*Y -y*Y -Y]
| ...
| ...
| ]
| x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]
|
| In case of total least-squares the solution of this homogeneous system
| of equations is the right singular vector of A which corresponds to the
| smallest singular value normed by the coefficient c3.
|
| Weights can be applied to each pair of corresponding points to
| indicate, particularly in an overdetermined system, if point pairs have
| higher or lower confidence or uncertainties associated with them. From
| the matrix treatment of least squares problems, these weight values are
| normalised, square-rooted, then built into a diagonal matrix, by which
| A is multiplied.
|
| In case of the affine transformation the coefficients c0 and c1 are 0.
| Thus the system of equations is::
|
| A = [[x y 1 0 0 0 -X]
| [0 0 0 x y 1 -Y]
| ...
| ...
| ]
| x.T = [a0 a1 a2 b0 b1 b2 c3]
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
| weights : (N,) array_like, optional
| Relative weight values for each pair of points.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ProjectiveTransform:
|
| dimensionality
| The dimensionality of the transformation.
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class EssentialMatrixTransform(FundamentalMatrixTransform)
| EssentialMatrixTransform(rotation=None, translation=None, matrix=None, *, dimensionality=2)
|
| Essential matrix transformation.
|
| The essential matrix relates corresponding points between a pair of
| calibrated images. The matrix transforms normalized, homogeneous image
| points in one image to epipolar lines in the other image.
|
| The essential matrix is only defined for a pair of moving images capturing a
| non-planar scene. In the case of pure rotation or planar scenes, the
| homography describes the geometric relation between two images
| (`ProjectiveTransform`). If the intrinsic calibration of the images is
| unknown, the fundamental matrix describes the projective relation between
| the two images (`FundamentalMatrixTransform`).
|
| References
| ----------
| .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
| computer vision. Cambridge university press, 2003.
|
| Parameters
| ----------
| rotation : (3, 3) array_like, optional
| Rotation matrix of the relative camera motion.
| translation : (3, 1) array_like, optional
| Translation vector of the relative camera motion. The vector must
| have unit length.
| matrix : (3, 3) array_like, optional
| Essential matrix.
|
| Attributes
| ----------
| params : (3, 3) array
| Essential matrix.
|
| Examples
| --------
| >>> import numpy as np
| >>> import skimage as ski
| >>>
| >>> tform_matrix = ski.transform.EssentialMatrixTransform(
| ... rotation=np.eye(3), translation=np.array([0, 0, 1])
| ... )
| >>> tform_matrix.params
| array([[ 0., -1., 0.],
| [ 1., 0., 0.],
| [ 0., 0., 0.]])
| >>> src = np.array([[ 1.839035, 1.924743],
| ... [ 0.543582, 0.375221],
| ... [ 0.47324 , 0.142522],
| ... [ 0.96491 , 0.598376],
| ... [ 0.102388, 0.140092],
| ... [15.994343, 9.622164],
| ... [ 0.285901, 0.430055],
| ... [ 0.09115 , 0.254594]])
| >>> dst = np.array([[1.002114, 1.129644],
| ... [1.521742, 1.846002],
| ... [1.084332, 0.275134],
| ... [0.293328, 0.588992],
| ... [0.839509, 0.08729 ],
| ... [1.779735, 1.116857],
| ... [0.878616, 0.602447],
| ... [0.642616, 1.028681]])
| >>> tform_matrix.estimate(src, dst)
| True
| >>> tform_matrix.residuals(src, dst)
| array([0.42455187, 0.01460448, 0.13847034, 0.12140951, 0.27759346,
| 0.32453118, 0.00210776, 0.26512283])
|
| Method resolution order:
| EssentialMatrixTransform
| FundamentalMatrixTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, rotation=None, translation=None, matrix=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate essential matrix using 8-point algorithm.
|
| The 8-point algorithm requires at least 8 corresponding point pairs for
| a well-conditioned solution, otherwise the over-determined solution is
| estimated.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from FundamentalMatrixTransform:
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, 2) array_like
| Source coordinates.
|
| Returns
| -------
| coords : (N, 3) array
| Epipolar lines in the destination image.
|
| residuals(self, src, dst)
| Compute the Sampson distance.
|
| The Sampson distance is the first approximation to the geometric error.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Sampson distance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from FundamentalMatrixTransform:
|
| inverse
| Return a transform object representing the inverse.
|
| See Hartley & Zisserman, Ch. 8: Epipolar Geometry and the Fundamental
| Matrix, for an explanation of why F.T gives the inverse.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class EuclideanTransform(ProjectiveTransform)
| EuclideanTransform(matrix=None, rotation=None, translation=None, *, dimensionality=2)
|
| Euclidean transformation, also known as a rigid transform.
|
| Has the following form::
|
| X = a0 * x - b0 * y + a1 =
| = x * cos(rotation) - y * sin(rotation) + a1
|
| Y = b0 * x + a0 * y + b1 =
| = x * sin(rotation) + y * cos(rotation) + b1
|
| where the homogeneous transformation matrix is::
|
| [[a0 -b0 a1]
| [b0 a0 b1]
| [0 0 1 ]]
|
| The Euclidean transformation is a rigid transformation with rotation and
| translation parameters. The similarity transformation extends the Euclidean
| transformation with a single scaling factor.
|
| In 2D and 3D, the transformation parameters may be provided either via
| `matrix`, the homogeneous transformation matrix, above, or via the
| implicit parameters `rotation` and/or `translation` (where `a1` is the
| translation along `x`, `b1` along `y`, etc.). Beyond 3D, if the
| transformation is only a translation, you may use the implicit parameter
| `translation`; otherwise, you must use `matrix`.
|
| Parameters
| ----------
| matrix : (D+1, D+1) array_like, optional
| Homogeneous transformation matrix.
| rotation : float or sequence of float, optional
| Rotation angle, clockwise, as radians. If given as
| a vector, it is interpreted as Euler rotation angles [1]_. Only 2D
| (single rotation) and 3D (Euler rotations) values are supported. For
| higher dimensions, you must provide or estimate the transformation
| matrix.
| translation : (x, y[, z, ...]) sequence of float, length D, optional
| Translation parameters for each axis.
| dimensionality : int, optional
| The dimensionality of the transform.
|
| Attributes
| ----------
| params : (D+1, D+1) array
| Homogeneous transformation matrix.
|
| References
| ----------
| .. [1] https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
|
| Method resolution order:
| EuclideanTransform
| ProjectiveTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, matrix=None, rotation=None, translation=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate the transformation from a set of corresponding points.
|
| You can determine the over-, well- and under-determined parameters
| with the total least-squares method.
|
| Number of source and destination coordinates must match.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| rotation
|
| translation
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from ProjectiveTransform:
|
| __add__(self, other)
| Combine this transformation with another.
|
| __array__(self, dtype=None, copy=None)
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, D) array_like
| Source coordinates.
|
| Returns
| -------
| coords_out : (N, D) array
| Destination coordinates.
|
| __nice__(self)
| common 'paramstr' used by __str__ and __repr__
|
| __repr__(self)
| Add standard repr formatting around a __nice__ string
|
| __str__(self)
| Add standard str formatting around a __nice__ string
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ProjectiveTransform:
|
| dimensionality
| The dimensionality of the transformation.
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class FundamentalMatrixTransform(_GeometricTransform)
| FundamentalMatrixTransform(matrix=None, *, dimensionality=2)
|
| Fundamental matrix transformation.
|
| The fundamental matrix relates corresponding points between a pair of
| uncalibrated images. The matrix transforms homogeneous image points in one
| image to epipolar lines in the other image.
|
| The fundamental matrix is only defined for a pair of moving images. In the
| case of pure rotation or planar scenes, the homography describes the
| geometric relation between two images (`ProjectiveTransform`). If the
| intrinsic calibration of the images is known, the essential matrix describes
| the metric relation between the two images (`EssentialMatrixTransform`).
|
| References
| ----------
| .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
| computer vision. Cambridge university press, 2003.
|
| Parameters
| ----------
| matrix : (3, 3) array_like, optional
| Fundamental matrix.
|
| Attributes
| ----------
| params : (3, 3) array
| Fundamental matrix.
|
| Examples
| --------
| >>> import numpy as np
| >>> import skimage as ski
| >>> tform_matrix = ski.transform.FundamentalMatrixTransform()
|
| Define source and destination points:
|
| >>> src = np.array([1.839035, 1.924743,
| ... 0.543582, 0.375221,
| ... 0.473240, 0.142522,
| ... 0.964910, 0.598376,
| ... 0.102388, 0.140092,
| ... 15.994343, 9.622164,
| ... 0.285901, 0.430055,
| ... 0.091150, 0.254594]).reshape(-1, 2)
| >>> dst = np.array([1.002114, 1.129644,
| ... 1.521742, 1.846002,
| ... 1.084332, 0.275134,
| ... 0.293328, 0.588992,
| ... 0.839509, 0.087290,
| ... 1.779735, 1.116857,
| ... 0.878616, 0.602447,
| ... 0.642616, 1.028681]).reshape(-1, 2)
|
| Estimate the transformation matrix:
|
| >>> tform_matrix.estimate(src, dst)
| True
| >>> tform_matrix.params
| array([[-0.21785884, 0.41928191, -0.03430748],
| [-0.07179414, 0.04516432, 0.02160726],
| [ 0.24806211, -0.42947814, 0.02210191]])
|
| Compute the Sampson distance:
|
| >>> tform_matrix.residuals(src, dst)
| array([0.0053886 , 0.00526101, 0.08689701, 0.01850534, 0.09418259,
| 0.00185967, 0.06160489, 0.02655136])
|
| Apply inverse transformation:
|
| >>> tform_matrix.inverse(dst)
| array([[-0.0513591 , 0.04170974, 0.01213043],
| [-0.21599496, 0.29193419, 0.00978184],
| [-0.0079222 , 0.03758889, -0.00915389],
| [ 0.14187184, -0.27988959, 0.02476507],
| [ 0.05890075, -0.07354481, -0.00481342],
| [-0.21985267, 0.36717464, -0.01482408],
| [ 0.01339569, -0.03388123, 0.00497605],
| [ 0.03420927, -0.1135812 , 0.02228236]])
|
| Method resolution order:
| FundamentalMatrixTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, 2) array_like
| Source coordinates.
|
| Returns
| -------
| coords : (N, 3) array
| Epipolar lines in the destination image.
|
| __init__(self, matrix=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate fundamental matrix using 8-point algorithm.
|
| The 8-point algorithm requires at least 8 corresponding point pairs for
| a well-conditioned solution, otherwise the over-determined solution is
| estimated.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| residuals(self, src, dst)
| Compute the Sampson distance.
|
| The Sampson distance is the first approximation to the geometric error.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Sampson distance.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inverse
| Return a transform object representing the inverse.
|
| See Hartley & Zisserman, Ch. 8: Epipolar Geometry and the Fundamental
| Matrix, for an explanation of why F.T gives the inverse.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class PiecewiseAffineTransform(_GeometricTransform)
| Piecewise affine transformation.
|
| Control points are used to define the mapping. The transform is based on
| a Delaunay triangulation of the points to form a mesh. Each triangle is
| used to find a local affine transform.
|
| Attributes
| ----------
| affines : list of AffineTransform objects
| Affine transformations for each triangle in the mesh.
| inverse_affines : list of AffineTransform objects
| Inverse affine transformations for each triangle in the mesh.
|
| Method resolution order:
| PiecewiseAffineTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __call__(self, coords)
| Apply forward transformation.
|
| Coordinates outside of the mesh will be set to `- 1`.
|
| Parameters
| ----------
| coords : (N, D) array_like
| Source coordinates.
|
| Returns
| -------
| coords : (N, 2) array
| Transformed coordinates.
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate the transformation from a set of corresponding points.
|
| Number of source and destination coordinates must match.
|
| Parameters
| ----------
| src : (N, D) array_like
| Source coordinates.
| dst : (N, D) array_like
| Destination coordinates.
|
| Returns
| -------
| success : bool
| True, if all pieces of the model are successfully estimated.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class PolynomialTransform(_GeometricTransform)
| PolynomialTransform(params=None, *, dimensionality=2)
|
| 2D polynomial transformation.
|
| Has the following form::
|
| X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
| Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))
|
| Parameters
| ----------
| params : (2, N) array_like, optional
| Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
| a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.
|
| Attributes
| ----------
| params : (2, N) array
| Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
| a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.
|
| Method resolution order:
| PolynomialTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, 2) array_like
| source coordinates
|
| Returns
| -------
| coords : (N, 2) array
| Transformed coordinates.
|
| __init__(self, params=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst, order=2, weights=None)
| Estimate the transformation from a set of corresponding points.
|
| You can determine the over-, well- and under-determined parameters
| with the total least-squares method.
|
| Number of source and destination coordinates must match.
|
| The transformation is defined as::
|
| X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
| Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))
|
| These equations can be transformed to the following form::
|
| 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
| 0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y
|
| which exist for each set of corresponding points, so we have a set of
| N * 2 equations. The coefficients appear linearly so we can write
| A x = 0, where::
|
| A = [[1 x y x**2 x*y y**2 ... 0 ... 0 -X]
| [0 ... 0 1 x y x**2 x*y y**2 -Y]
| ...
| ...
| ]
| x.T = [a00 a10 a11 a20 a21 a22 ... ann
| b00 b10 b11 b20 b21 b22 ... bnn c3]
|
| In case of total least-squares the solution of this homogeneous system
| of equations is the right singular vector of A which corresponds to the
| smallest singular value normed by the coefficient c3.
|
| Weights can be applied to each pair of corresponding points to
| indicate, particularly in an overdetermined system, if point pairs have
| higher or lower confidence or uncertainties associated with them. From
| the matrix treatment of least squares problems, these weight values are
| normalised, square-rooted, then built into a diagonal matrix, by which
| A is multiplied.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
| order : int, optional
| Polynomial order (number of coefficients is order + 1).
| weights : (N,) array_like, optional
| Relative weight values for each pair of points.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ProjectiveTransform(_GeometricTransform)
| ProjectiveTransform(matrix=None, *, dimensionality=2)
|
| Projective transformation.
|
| Apply a projective transformation (homography) on coordinates.
|
| For each homogeneous coordinate :math:`\mathbf{x} = [x, y, 1]^T`, its
| target position is calculated by multiplying with the given matrix,
| :math:`H`, to give :math:`H \mathbf{x}`::
|
| [[a0 a1 a2]
| [b0 b1 b2]
| [c0 c1 1 ]].
|
| E.g., to rotate by theta degrees clockwise, the matrix should be::
|
| [[cos(theta) -sin(theta) 0]
| [sin(theta) cos(theta) 0]
| [0 0 1]]
|
| or, to translate x by 10 and y by 20::
|
| [[1 0 10]
| [0 1 20]
| [0 0 1 ]].
|
| Parameters
| ----------
| matrix : (D+1, D+1) array_like, optional
| Homogeneous transformation matrix.
| dimensionality : int, optional
| The number of dimensions of the transform. This is ignored if
| ``matrix`` is not None.
|
| Attributes
| ----------
| params : (D+1, D+1) array
| Homogeneous transformation matrix.
|
| Method resolution order:
| ProjectiveTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
| Combine this transformation with another.
|
| __array__(self, dtype=None, copy=None)
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, D) array_like
| Source coordinates.
|
| Returns
| -------
| coords_out : (N, D) array
| Destination coordinates.
|
| __init__(self, matrix=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| __nice__(self)
| common 'paramstr' used by __str__ and __repr__
|
| __repr__(self)
| Add standard repr formatting around a __nice__ string
|
| __str__(self)
| Add standard str formatting around a __nice__ string
|
| estimate(self, src, dst, weights=None)
| Estimate the transformation from a set of corresponding points.
|
| You can determine the over-, well- and under-determined parameters
| with the total least-squares method.
|
| Number of source and destination coordinates must match.
|
| The transformation is defined as::
|
| X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
| Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)
|
| These equations can be transformed to the following form::
|
| 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
| 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y
|
| which exist for each set of corresponding points, so we have a set of
| N * 2 equations. The coefficients appear linearly so we can write
| A x = 0, where::
|
| A = [[x y 1 0 0 0 -x*X -y*X -X]
| [0 0 0 x y 1 -x*Y -y*Y -Y]
| ...
| ...
| ]
| x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]
|
| In case of total least-squares the solution of this homogeneous system
| of equations is the right singular vector of A which corresponds to the
| smallest singular value normed by the coefficient c3.
|
| Weights can be applied to each pair of corresponding points to
| indicate, particularly in an overdetermined system, if point pairs have
| higher or lower confidence or uncertainties associated with them. From
| the matrix treatment of least squares problems, these weight values are
| normalised, square-rooted, then built into a diagonal matrix, by which
| A is multiplied.
|
| In case of the affine transformation the coefficients c0 and c1 are 0.
| Thus the system of equations is::
|
| A = [[x y 1 0 0 0 -X]
| [0 0 0 x y 1 -Y]
| ...
| ...
| ]
| x.T = [a0 a1 a2 b0 b1 b2 c3]
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
| weights : (N,) array_like, optional
| Relative weight values for each pair of points.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| dimensionality
| The dimensionality of the transformation.
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class SimilarityTransform(EuclideanTransform)
| SimilarityTransform(matrix=None, scale=None, rotation=None, translation=None, *, dimensionality=2)
|
| Similarity transformation.
|
| Has the following form in 2D::
|
| X = a0 * x - b0 * y + a1 =
| = s * x * cos(rotation) - s * y * sin(rotation) + a1
|
| Y = b0 * x + a0 * y + b1 =
| = s * x * sin(rotation) + s * y * cos(rotation) + b1
|
| where ``s`` is a scale factor and the homogeneous transformation matrix is::
|
| [[a0 -b0 a1]
| [b0 a0 b1]
| [0 0 1 ]]
|
| The similarity transformation extends the Euclidean transformation with a
| single scaling factor in addition to the rotation and translation
| parameters.
|
| Parameters
| ----------
| matrix : (dim+1, dim+1) array_like, optional
| Homogeneous transformation matrix.
| scale : float, optional
| Scale factor. Implemented only for 2D and 3D.
| rotation : float, optional
| Rotation angle, clockwise, as radians.
| Implemented only for 2D and 3D. For 3D, this is given in ZYX Euler
| angles.
| translation : (dim,) array_like, optional
| x, y[, z] translation parameters. Implemented only for 2D and 3D.
|
| Attributes
| ----------
| params : (dim+1, dim+1) array
| Homogeneous transformation matrix.
|
| Method resolution order:
| SimilarityTransform
| EuclideanTransform
| ProjectiveTransform
| _GeometricTransform
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, matrix=None, scale=None, rotation=None, translation=None, *, dimensionality=2)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate the transformation from a set of corresponding points.
|
| You can determine the over-, well- and under-determined parameters
| with the total least-squares method.
|
| Number of source and destination coordinates must match.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Source coordinates.
| dst : (N, 2) array_like
| Destination coordinates.
|
| Returns
| -------
| success : bool
| True, if model estimation succeeds.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| scale
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Readonly properties inherited from EuclideanTransform:
|
| rotation
|
| translation
|
| ----------------------------------------------------------------------
| Methods inherited from ProjectiveTransform:
|
| __add__(self, other)
| Combine this transformation with another.
|
| __array__(self, dtype=None, copy=None)
|
| __call__(self, coords)
| Apply forward transformation.
|
| Parameters
| ----------
| coords : (N, D) array_like
| Source coordinates.
|
| Returns
| -------
| coords_out : (N, D) array
| Destination coordinates.
|
| __nice__(self)
| common 'paramstr' used by __str__ and __repr__
|
| __repr__(self)
| Add standard repr formatting around a __nice__ string
|
| __str__(self)
| Add standard str formatting around a __nice__ string
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ProjectiveTransform:
|
| dimensionality
| The dimensionality of the transformation.
|
| inverse
| Return a transform object representing the inverse.
|
| ----------------------------------------------------------------------
| Methods inherited from _GeometricTransform:
|
| residuals(self, src, dst)
| Determine residuals of transformed destination coordinates.
|
| For each transformed source coordinate the Euclidean distance to the
| respective destination coordinate is determined.
|
| Parameters
| ----------
| src : (N, 2) array
| Source coordinates.
| dst : (N, 2) array
| Destination coordinates.
|
| Returns
| -------
| residuals : (N,) array
| Residual for coordinate.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _GeometricTransform:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ThinPlateSplineTransform(builtins.object)
| Thin-plate spline transformation.
|
| Given two matching sets of points, source and destination, this class
| estimates the thin-plate spline (TPS) transformation which transforms
| each point in source into its destination counterpart.
|
| Attributes
| ----------
| src : (N, 2) array_like
| Coordinates of control points in source image.
|
| References
| ----------
| .. [1] Bookstein, Fred L. "Principal warps: Thin-plate splines and the
| decomposition of deformations," IEEE Transactions on pattern analysis
| and machine intelligence 11.6 (1989): 567–585.
| DOI:`10.1109/34.24792`
| https://user.engineering.uiowa.edu/~aip/papers/bookstein-89.pdf
|
| Examples
| --------
| >>> import skimage as ski
|
| Define source and destination control points such that they simulate
| rotating by 90 degrees and generate a meshgrid from them:
|
| >>> src = np.array([[0, 0], [0, 5], [5, 5], [5, 0]])
| >>> dst = np.array([[5, 0], [0, 0], [0, 5], [5, 5]])
|
| Estimate the transformation:
|
| >>> tps = ski.transform.ThinPlateSplineTransform()
| >>> tps.estimate(src, dst)
| True
|
| Appyling the transformation to `src` approximates `dst`:
|
| >>> np.round(tps(src))
| array([[5., 0.],
| [0., 0.],
| [0., 5.],
| [5., 5.]])
|
| Create a meshgrid to apply the transformation to:
|
| >>> grid = np.meshgrid(np.arange(5), np.arange(5))
| >>> grid[1]
| array([[0, 0, 0, 0, 0],
| [1, 1, 1, 1, 1],
| [2, 2, 2, 2, 2],
| [3, 3, 3, 3, 3],
| [4, 4, 4, 4, 4]])
|
| >>> coords = np.vstack([grid[0].ravel(), grid[1].ravel()]).T
| >>> transformed = tps(coords)
| >>> np.round(transformed[:, 1]).reshape(5, 5).astype(int)
| array([[0, 1, 2, 3, 4],
| [0, 1, 2, 3, 4],
| [0, 1, 2, 3, 4],
| [0, 1, 2, 3, 4],
| [0, 1, 2, 3, 4]])
|
| Methods defined here:
|
| __call__(self, coords)
| Estimate the transformation from a set of corresponding points.
|
| Parameters
| ----------
| coords : (N, 2) array_like
| x, y coordinates to transform
|
| Returns
| -------
| transformed_coords: (N, D) array
| Destination coordinates
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| estimate(self, src, dst)
| Estimate optimal spline mappings between source and destination points.
|
| Parameters
| ----------
| src : (N, 2) array_like
| Control points at source coordinates.
| dst : (N, 2) array_like
| Control points at destination coordinates.
|
| Returns
| -------
| success: bool
| True indicates that the estimation was successful.
|
| Notes
| -----
| The number N of source and destination points must match.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inverse
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
downscale_local_mean(image, factors, cval=0, clip=True)
Down-sample N-dimensional image by local averaging.
The image is padded with `cval` if it is not perfectly divisible by the
integer factors.
In contrast to interpolation in `skimage.transform.resize` and
`skimage.transform.rescale` this function calculates the local mean of
elements in each block of size `factors` in the input image.
Parameters
----------
image : (M[, ...]) ndarray
Input image.
factors : array_like
Array containing down-sampling integer factor along each axis.
cval : float, optional
Constant padding value if image is not perfectly divisible by the
integer factors.
clip : bool, optional
Unused, but kept here for API consistency with the other transforms
in this module. (The local mean will never fall outside the range
of values in the input image, assuming the provided `cval` also
falls within that range.)
Returns
-------
image : ndarray
Down-sampled image with same number of dimensions as input image.
For integer inputs, the output dtype will be ``float64``.
See :func:`numpy.mean` for details.
Examples
--------
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> downscale_local_mean(a, (2, 3))
array([[3.5, 4. ],
[5.5, 4.5]])
estimate_transform(ttype, src, dst, *args, **kwargs)
Estimate 2D geometric transformation parameters.
You can determine the over-, well- and under-determined parameters
with the total least-squares method.
Number of source and destination coordinates must match.
Parameters
----------
ttype : {'euclidean', similarity', 'affine', 'piecewise-affine', 'projective', 'polynomial'}
Type of transform.
kwargs : array_like or int
Function parameters (src, dst, n, angle)::
NAME / TTYPE FUNCTION PARAMETERS
'euclidean' `src, `dst`
'similarity' `src, `dst`
'affine' `src, `dst`
'piecewise-affine' `src, `dst`
'projective' `src, `dst`
'polynomial' `src, `dst`, `order` (polynomial order,
default order is 2)
Also see examples below.
Returns
-------
tform : :class:`_GeometricTransform`
Transform object containing the transformation parameters and providing
access to forward and inverse transformation functions.
Examples
--------
>>> import numpy as np
>>> import skimage as ski
>>> # estimate transformation parameters
>>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
>>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))
>>> tform = ski.transform.estimate_transform('similarity', src, dst)
>>> np.allclose(tform.inverse(tform(src)), src)
True
>>> # warp image using the estimated transformation
>>> image = ski.data.camera()
>>> ski.transform.warp(image, inverse_map=tform.inverse) # doctest: +SKIP
>>> # create transformation with explicit parameters
>>> tform2 = ski.transform.SimilarityTransform(scale=1.1, rotation=1,
... translation=(10, 20))
>>> # unite transformations, applied in order from left to right
>>> tform3 = tform + tform2
>>> np.allclose(tform3(src), tform2(tform(src)))
True
frt2(a)
Compute the 2-dimensional finite Radon transform (FRT) for the input array.
Parameters
----------
a : ndarray of int, shape (M, M)
Input array.
Returns
-------
FRT : ndarray of int, shape (M+1, M)
Finite Radon Transform array of coefficients.
See Also
--------
ifrt2 : The two-dimensional inverse FRT.
Notes
-----
The FRT has a unique inverse if and only if M is prime. [FRT]
The idea for this algorithm is due to Vlad Negnevitski.
Examples
--------
Generate a test image:
Use a prime number for the array dimensions
>>> SIZE = 59
>>> img = np.tri(SIZE, dtype=np.int32)
Apply the Finite Radon Transform:
>>> f = frt2(img)
References
----------
.. [FRT] A. Kingston and I. Svalbe, "Projective transforms on periodic
discrete image arrays," in P. Hawkes (Ed), Advances in Imaging
and Electron Physics, 139 (2006)
hough_circle(image, radius, normalize=True, full_output=False)
Perform a circular Hough transform.
Parameters
----------
image : ndarray, shape (M, N)
Input image with nonzero values representing edges.
radius : scalar or sequence of scalars
Radii at which to compute the Hough transform.
Floats are converted to integers.
normalize : boolean, optional
Normalize the accumulator with the number
of pixels used to draw the radius.
full_output : boolean, optional
Extend the output size by twice the largest
radius in order to detect centers outside the
input picture.
Returns
-------
H : ndarray, shape (radius index, M + 2R, N + 2R)
Hough transform accumulator for each radius.
R designates the larger radius if full_output is True.
Otherwise, R = 0.
Examples
--------
>>> from skimage.transform import hough_circle
>>> from skimage.draw import circle_perimeter
>>> img = np.zeros((100, 100), dtype=bool)
>>> rr, cc = circle_perimeter(25, 35, 23)
>>> img[rr, cc] = 1
>>> try_radii = np.arange(5, 50)
>>> res = hough_circle(img, try_radii)
>>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape)
>>> r, c, try_radii[ridx]
(25, 35, 23)
hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=inf, total_num_peaks=inf, normalize=False)
Return peaks in a circle Hough transform.
Identifies most prominent circles separated by certain distances in given
Hough spaces. Non-maximum suppression with different sizes is applied
separately in the first and second dimension of the Hough space to
identify peaks. For circles with different radius but close in distance,
only the one with highest peak is kept.
Parameters
----------
hspaces : (M, N, P) array
Hough spaces returned by the `hough_circle` function.
radii : (M,) array
Radii corresponding to Hough spaces.
min_xdistance : int, optional
Minimum distance separating centers in the x dimension.
min_ydistance : int, optional
Minimum distance separating centers in the y dimension.
threshold : float, optional
Minimum intensity of peaks in each Hough space.
Default is `0.5 * max(hspace)`.
num_peaks : int, optional
Maximum number of peaks in each Hough space. When the
number of peaks exceeds `num_peaks`, only `num_peaks`
coordinates based on peak intensity are considered for the
corresponding radius.
total_num_peaks : int, optional
Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
return `num_peaks` coordinates based on peak intensity.
normalize : bool, optional
If True, normalize the accumulator by the radius to sort the prominent
peaks.
Returns
-------
accum, cx, cy, rad : tuple of array
Peak values in Hough space, x and y center coordinates and radii.
Examples
--------
>>> from skimage import transform, draw
>>> img = np.zeros((120, 100), dtype=int)
>>> radius, x_0, y_0 = (20, 99, 50)
>>> y, x = draw.circle_perimeter(y_0, x_0, radius)
>>> img[x, y] = 1
>>> hspaces = transform.hough_circle(img, radius)
>>> accum, cx, cy, rad = hough_circle_peaks(hspaces, [radius,])
Notes
-----
Circles with bigger radius have higher peaks in Hough space. If larger
circles are preferred over smaller ones, `normalize` should be False.
Otherwise, circles will be returned in the order of decreasing voting
number.
hough_ellipse(image, threshold=4, accuracy=1, min_size=4, max_size=None)
Perform an elliptical Hough transform.
Parameters
----------
image : (M, N) ndarray
Input image with nonzero values representing edges.
threshold : int, optional
Accumulator threshold value. A lower value will return more ellipses.
accuracy : double, optional
Bin size on the minor axis used in the accumulator. A higher value
will return more ellipses, but lead to a less precise estimation of
the minor axis lengths.
min_size : int, optional
Minimal major axis length.
max_size : int, optional
Maximal minor axis length.
If None, the value is set to half of the smaller
image dimension.
Returns
-------
result : ndarray with fields [(accumulator, yc, xc, a, b, orientation)].
Where ``(yc, xc)`` is the center, ``(a, b)`` the major and minor
axes, respectively. The `orientation` value follows the
`skimage.draw.ellipse_perimeter` convention.
Examples
--------
>>> from skimage.transform import hough_ellipse
>>> from skimage.draw import ellipse_perimeter
>>> img = np.zeros((25, 25), dtype=np.uint8)
>>> rr, cc = ellipse_perimeter(10, 10, 6, 8)
>>> img[cc, rr] = 1
>>> result = hough_ellipse(img, threshold=8)
>>> result.tolist()
[(10, 10.0, 10.0, 8.0, 6.0, 0.0)]
Notes
-----
Potential ellipses in the image are characterized by their major and
minor axis lengths. For any pair of nonzero pixels in the image that
are at least half of `min_size` apart, an accumulator keeps track of
the minor axis lengths of potential ellipses formed with all the
other nonzero pixels. If any bin (with `bin_size = accuracy * accuracy`)
in the histogram of those accumulated minor axis lengths is above
`threshold`, the corresponding ellipse is added to the results.
A higher `accuracy` will therefore lead to more ellipses being found
in the image, at the cost of a less precise estimation of the minor
axis length.
References
----------
.. [1] Xie, Yonghong, and Qiang Ji. "A new efficient ellipse detection
method." Pattern Recognition, 2002. Proceedings. 16th International
Conference on. Vol. 2. IEEE, 2002
hough_line(image, theta=None)
Perform a straight line Hough transform.
Parameters
----------
image : (M, N) ndarray
Input image with nonzero values representing edges.
theta : ndarray of double, shape (K,), optional
Angles at which to compute the transform, in radians.
Defaults to a vector of 180 angles evenly spaced in the
range [-pi/2, pi/2).
Returns
-------
hspace : ndarray of uint64, shape (P, Q)
Hough transform accumulator.
angles : ndarray
Angles at which the transform is computed, in radians.
distances : ndarray
Distance values.
Notes
-----
The origin is the top left corner of the original image.
X and Y axis are horizontal and vertical edges respectively.
The distance is the minimal algebraic distance from the origin
to the detected line.
The angle accuracy can be improved by decreasing the step size in
the `theta` array.
Examples
--------
Generate a test image:
>>> img = np.zeros((100, 150), dtype=bool)
>>> img[30, :] = 1
>>> img[:, 65] = 1
>>> img[35:45, 35:50] = 1
>>> for i in range(90):
... img[i, i] = 1
>>> rng = np.random.default_rng()
>>> img += rng.random(img.shape) > 0.95
Apply the Hough transform:
>>> out, angles, d = hough_line(img)
hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, threshold=None, num_peaks=inf)
Return peaks in a straight line Hough transform.
Identifies most prominent lines separated by a certain angle and distance
in a Hough transform. Non-maximum suppression with different sizes is
applied separately in the first (distances) and second (angles) dimension
of the Hough space to identify peaks.
Parameters
----------
hspace : ndarray, shape (M, N)
Hough space returned by the `hough_line` function.
angles : array, shape (N,)
Angles returned by the `hough_line` function. Assumed to be continuous.
(`angles[-1] - angles[0] == PI`).
dists : array, shape (M,)
Distances returned by the `hough_line` function.
min_distance : int, optional
Minimum distance separating lines (maximum filter size for first
dimension of hough space).
min_angle : int, optional
Minimum angle separating lines (maximum filter size for second
dimension of hough space).
threshold : float, optional
Minimum intensity of peaks. Default is `0.5 * max(hspace)`.
num_peaks : int, optional
Maximum number of peaks. When the number of peaks exceeds `num_peaks`,
return `num_peaks` coordinates based on peak intensity.
Returns
-------
accum, angles, dists : tuple of array
Peak values in Hough space, angles and distances.
Examples
--------
>>> from skimage.transform import hough_line, hough_line_peaks
>>> from skimage.draw import line
>>> img = np.zeros((15, 15), dtype=bool)
>>> rr, cc = line(0, 0, 14, 14)
>>> img[rr, cc] = 1
>>> rr, cc = line(0, 14, 14, 0)
>>> img[cc, rr] = 1
>>> hspace, angles, dists = hough_line(img)
>>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists)
>>> len(angles)
2
ifrt2(a)
Compute the 2-dimensional inverse finite Radon transform (iFRT) for the input array.
Parameters
----------
a : ndarray of int, shape (M+1, M)
Input array.
Returns
-------
iFRT : ndarray of int, shape (M, M)
Inverse Finite Radon Transform coefficients.
See Also
--------
frt2 : The two-dimensional FRT
Notes
-----
The FRT has a unique inverse if and only if M is prime.
See [1]_ for an overview.
The idea for this algorithm is due to Vlad Negnevitski.
Examples
--------
>>> SIZE = 59
>>> img = np.tri(SIZE, dtype=np.int32)
Apply the Finite Radon Transform:
>>> f = frt2(img)
Apply the Inverse Finite Radon Transform to recover the input
>>> fi = ifrt2(f)
Check that it's identical to the original
>>> assert len(np.nonzero(img-fi)[0]) == 0
References
----------
.. [1] A. Kingston and I. Svalbe, "Projective transforms on periodic
discrete image arrays," in P. Hawkes (Ed), Advances in Imaging
and Electron Physics, 139 (2006)
integral_image(image, *, dtype=None)
Integral image / summed area table.
The integral image contains the sum of all elements above and to the
left of it, i.e.:
.. math::
S[m, n] = \sum_{i \leq m} \sum_{j \leq n} X[i, j]
Parameters
----------
image : ndarray
Input image.
Returns
-------
S : ndarray
Integral image/summed area table of same shape as input image.
Notes
-----
For better accuracy and to avoid potential overflow, the data type of the
output may differ from the input's when the default dtype of None is used.
For inputs with integer dtype, the behavior matches that for
:func:`numpy.cumsum`. Floating point inputs will be promoted to at least
double precision. The user can set `dtype` to override this behavior.
References
----------
.. [1] F.C. Crow, "Summed-area tables for texture mapping,"
ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212.
integrate(ii, start, end)
Use an integral image to integrate over a given window.
Parameters
----------
ii : ndarray
Integral image.
start : List of tuples, each tuple of length equal to dimension of `ii`
Coordinates of top left corner of window(s).
Each tuple in the list contains the starting row, col, ... index
i.e `[(row_win1, col_win1, ...), (row_win2, col_win2,...), ...]`.
end : List of tuples, each tuple of length equal to dimension of `ii`
Coordinates of bottom right corner of window(s).
Each tuple in the list containing the end row, col, ... index i.e
`[(row_win1, col_win1, ...), (row_win2, col_win2, ...), ...]`.
Returns
-------
S : scalar or ndarray
Integral (sum) over the given window(s).
See Also
--------
integral_image : Create an integral image / summed area table.
Examples
--------
>>> arr = np.ones((5, 6), dtype=float)
>>> ii = integral_image(arr)
>>> integrate(ii, (1, 0), (1, 2)) # sum from (1, 0) to (1, 2)
array([3.])
>>> integrate(ii, [(3, 3)], [(4, 5)]) # sum from (3, 3) to (4, 5)
array([6.])
>>> # sum from (1, 0) to (1, 2) and from (3, 3) to (4, 5)
>>> integrate(ii, [(1, 0), (3, 3)], [(1, 2), (4, 5)])
array([3., 6.])
iradon(radon_image, theta=None, output_size=None, filter_name='ramp', interpolation='linear', circle=True, preserve_range=True)
Inverse radon transform.
Reconstruct an image from the radon transform, using the filtered
back projection algorithm.
Parameters
----------
radon_image : ndarray
Image containing radon transform (sinogram). Each column of
the image corresponds to a projection along a different
angle. The tomography rotation axis should lie at the pixel
index ``radon_image.shape[0] // 2`` along the 0th dimension of
``radon_image``.
theta : array, optional
Reconstruction angles (in degrees). Default: m angles evenly spaced
between 0 and 180 (if the shape of `radon_image` is (N, M)).
output_size : int, optional
Number of rows and columns in the reconstruction.
filter_name : str, optional
Filter used in frequency domain filtering. Ramp filter used by default.
Filters available: ramp, shepp-logan, cosine, hamming, hann.
Assign None to use no filter.
interpolation : str, optional
Interpolation method used in reconstruction. Methods available:
'linear', 'nearest', and 'cubic' ('cubic' is slow).
circle : boolean, optional
Assume the reconstructed image is zero outside the inscribed circle.
Also changes the default output_size to match the behaviour of
``radon`` called with ``circle=True``.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
Returns
-------
reconstructed : ndarray
Reconstructed image. The rotation axis will be located in the pixel
with indices
``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.
.. versionchanged:: 0.19
In ``iradon``, ``filter`` argument is deprecated in favor of
``filter_name``.
References
----------
.. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988.
.. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing
the Discrete Radon Transform With Some Applications", Proceedings of
the Fourth IEEE Region 10 International Conference, TENCON '89, 1989
Notes
-----
It applies the Fourier slice theorem to reconstruct an image by
multiplying the frequency domain of the filter with the FFT of the
projection data. This algorithm is called filtered back projection.
iradon_sart(radon_image, theta=None, image=None, projection_shifts=None, clip=None, relaxation=0.15, dtype=None)
Inverse radon transform.
Reconstruct an image from the radon transform, using a single iteration of
the Simultaneous Algebraic Reconstruction Technique (SART) algorithm.
Parameters
----------
radon_image : ndarray, shape (M, N)
Image containing radon transform (sinogram). Each column of
the image corresponds to a projection along a different angle. The
tomography rotation axis should lie at the pixel index
``radon_image.shape[0] // 2`` along the 0th dimension of
``radon_image``.
theta : array, shape (N,), optional
Reconstruction angles (in degrees). Default: m angles evenly spaced
between 0 and 180 (if the shape of `radon_image` is (N, M)).
image : ndarray, shape (M, M), optional
Image containing an initial reconstruction estimate. Default is an array of zeros.
projection_shifts : array, shape (N,), optional
Shift the projections contained in ``radon_image`` (the sinogram) by
this many pixels before reconstructing the image. The i'th value
defines the shift of the i'th column of ``radon_image``.
clip : length-2 sequence of floats, optional
Force all values in the reconstructed tomogram to lie in the range
``[clip[0], clip[1]]``
relaxation : float, optional
Relaxation parameter for the update step. A higher value can
improve the convergence rate, but one runs the risk of instabilities.
Values close to or higher than 1 are not recommended.
dtype : dtype, optional
Output data type, must be floating point. By default, if input
data type is not float, input is cast to double, otherwise
dtype is set to input data type.
Returns
-------
reconstructed : ndarray
Reconstructed image. The rotation axis will be located in the pixel
with indices
``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.
Notes
-----
Algebraic Reconstruction Techniques are based on formulating the tomography
reconstruction problem as a set of linear equations. Along each ray,
the projected value is the sum of all the values of the cross section along
the ray. A typical feature of SART (and a few other variants of algebraic
techniques) is that it samples the cross section at equidistant points
along the ray, using linear interpolation between the pixel values of the
cross section. The resulting set of linear equations are then solved using
a slightly modified Kaczmarz method.
When using SART, a single iteration is usually sufficient to obtain a good
reconstruction. Further iterations will tend to enhance high-frequency
information, but will also often increase the noise.
References
----------
.. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988.
.. [2] AH Andersen, AC Kak, "Simultaneous algebraic reconstruction
technique (SART): a superior implementation of the ART algorithm",
Ultrasonic Imaging 6 pp 81--94 (1984)
.. [3] S Kaczmarz, "Angenäherte auflösung von systemen linearer
gleichungen", Bulletin International de l’Academie Polonaise des
Sciences et des Lettres 35 pp 355--357 (1937)
.. [4] Kohler, T. "A projection access scheme for iterative
reconstruction based on the golden section." Nuclear Science
Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
.. [5] Kaczmarz' method, Wikipedia,
https://en.wikipedia.org/wiki/Kaczmarz_method
matrix_transform(coords, matrix)
Apply 2D matrix transform.
Parameters
----------
coords : (N, 2) array_like
x, y coordinates to transform
matrix : (3, 3) array_like
Homogeneous transformation matrix.
Returns
-------
coords : (N, 2) array
Transformed coordinates.
order_angles_golden_ratio(theta)
Order angles to reduce the amount of correlated information in
subsequent projections.
Parameters
----------
theta : array of floats, shape (M,)
Projection angles in degrees. Duplicate angles are not allowed.
Returns
-------
indices_generator : generator yielding unsigned integers
The returned generator yields indices into ``theta`` such that
``theta[indices]`` gives the approximate golden ratio ordering
of the projections. In total, ``len(theta)`` indices are yielded.
All non-negative integers < ``len(theta)`` are yielded exactly once.
Notes
-----
The method used here is that of the golden ratio introduced
by T. Kohler.
References
----------
.. [1] Kohler, T. "A projection access scheme for iterative
reconstruction based on the golden section." Nuclear Science
Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
.. [2] Winkelmann, Stefanie, et al. "An optimal radial profile order
based on the Golden Ratio for time-resolved MRI."
Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76.
probabilistic_hough_line(image, threshold=10, line_length=50, line_gap=10, theta=None, rng=None)
Return lines from a progressive probabilistic line Hough transform.
Parameters
----------
image : ndarray, shape (M, N)
Input image with nonzero values representing edges.
threshold : int, optional
Threshold
line_length : int, optional
Minimum accepted length of detected lines.
Increase the parameter to extract longer lines.
line_gap : int, optional
Maximum gap between pixels to still form a line.
Increase the parameter to merge broken lines more aggressively.
theta : ndarray of dtype, shape (K,), optional
Angles at which to compute the transform, in radians.
Defaults to a vector of 180 angles evenly spaced in the
range [-pi/2, pi/2).
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
Returns
-------
lines : list
List of lines identified, lines in format ((x0, y0), (x1, y1)),
indicating line start and end.
References
----------
.. [1] C. Galamhos, J. Matas and J. Kittler, "Progressive probabilistic
Hough transform for line detection", in IEEE Computer Society
Conference on Computer Vision and Pattern Recognition, 1999.
pyramid_expand(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0, preserve_range=False, *, channel_axis=None)
Upsample and then smooth image.
Parameters
----------
image : ndarray
Input image.
upscale : float, optional
Upscale factor.
sigma : float, optional
Sigma for Gaussian filter. Default is `2 * upscale / 6.0` which
corresponds to a filter mask twice the size of the scale factor that
covers more than 99% of the Gaussian distribution.
order : int, optional
Order of splines used in interpolation of upsampling. See
`skimage.transform.warp` for detail.
mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if mode is 'constant'.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : array
Upsampled and smoothed float image.
References
----------
.. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf
pyramid_gaussian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, preserve_range=False, *, channel_axis=None)
Yield images of the Gaussian pyramid formed by the input image.
Recursively applies the `pyramid_reduce` function to the image, and yields
the downscaled images.
Note that the first image of the pyramid will be the original, unscaled
image. The total number of images is `max_layer + 1`. In case all layers
are computed, the last image is either a one-pixel image or the image where
the reduction does not change its shape.
Parameters
----------
image : ndarray
Input image.
max_layer : int, optional
Number of layers for the pyramid. 0th layer is the original image.
Default is -1 which builds all possible layers.
downscale : float, optional
Downscale factor.
sigma : float, optional
Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which
corresponds to a filter mask twice the size of the scale factor that
covers more than 99% of the Gaussian distribution.
order : int, optional
Order of splines used in interpolation of downsampling. See
`skimage.transform.warp` for detail.
mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if mode is 'constant'.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
pyramid : generator
Generator yielding pyramid layers as float images.
References
----------
.. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf
pyramid_laplacian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, preserve_range=False, *, channel_axis=None)
Yield images of the laplacian pyramid formed by the input image.
Each layer contains the difference between the downsampled and the
downsampled, smoothed image::
layer = resize(prev_layer) - smooth(resize(prev_layer))
Note that the first image of the pyramid will be the difference between the
original, unscaled image and its smoothed version. The total number of
images is `max_layer + 1`. In case all layers are computed, the last image
is either a one-pixel image or the image where the reduction does not
change its shape.
Parameters
----------
image : ndarray
Input image.
max_layer : int, optional
Number of layers for the pyramid. 0th layer is the original image.
Default is -1 which builds all possible layers.
downscale : float, optional
Downscale factor.
sigma : float, optional
Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which
corresponds to a filter mask twice the size of the scale factor that
covers more than 99% of the Gaussian distribution.
order : int, optional
Order of splines used in interpolation of downsampling. See
`skimage.transform.warp` for detail.
mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if mode is 'constant'.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
pyramid : generator
Generator yielding pyramid layers as float images.
References
----------
.. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf
.. [2] http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html
pyramid_reduce(image, downscale=2, sigma=None, order=1, mode='reflect', cval=0, preserve_range=False, *, channel_axis=None)
Smooth and then downsample image.
Parameters
----------
image : ndarray
Input image.
downscale : float, optional
Downscale factor.
sigma : float, optional
Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which
corresponds to a filter mask twice the size of the scale factor that
covers more than 99% of the Gaussian distribution.
order : int, optional
Order of splines used in interpolation of downsampling. See
`skimage.transform.warp` for detail.
mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if mode is 'constant'.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : array
Smoothed and downsampled float image.
References
----------
.. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf
radon(image, theta=None, circle=True, *, preserve_range=False)
Calculates the radon transform of an image given specified
projection angles.
Parameters
----------
image : ndarray
Input image. The rotation axis will be located in the pixel with
indices ``(image.shape[0] // 2, image.shape[1] // 2)``.
theta : array, optional
Projection angles (in degrees). If `None`, the value is set to
np.arange(180).
circle : boolean, optional
Assume image is zero outside the inscribed circle, making the
width of each projection (the first dimension of the sinogram)
equal to ``min(image.shape)``.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
Returns
-------
radon_image : ndarray
Radon transform (sinogram). The tomography rotation axis will lie
at the pixel index ``radon_image.shape[0] // 2`` along the 0th
dimension of ``radon_image``.
References
----------
.. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988.
.. [2] B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing
the Discrete Radon Transform With Some Applications", Proceedings of
the Fourth IEEE Region 10 International Conference, TENCON '89, 1989
Notes
-----
Based on code of Justin K. Romberg
(https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html)
rescale(image, scale, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None, *, channel_axis=None)
Scale image by a certain factor.
Performs interpolation to up-scale or down-scale N-dimensional images.
Note that anti-aliasing should be enabled when down-sizing images to avoid
aliasing artifacts. For down-sampling with an integer factor also see
`skimage.transform.downscale_local_mean`.
Parameters
----------
image : (M, N[, ...][, C]) ndarray
Input image.
scale : {float, tuple of floats}
Scale factors for spatial dimensions. Separate scale factors can be defined as
(m, n[, ...]).
Returns
-------
scaled : ndarray
Scaled version of the input.
Other parameters
----------------
order : int, optional
The order of the spline interpolation, default is 0 if
image.dtype is bool and 1 otherwise. The order has to be in
the range 0-5. See `skimage.transform.warp` for detail.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
Points outside the boundaries of the input are filled according
to the given mode. Modes match the behaviour of `numpy.pad`.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
clip : bool, optional
Whether to clip the output to the range of values of the input image.
This is enabled by default, since higher order interpolation may
produce values outside the given input range.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see
https://scikit-image.org/docs/dev/user_guide/data_types.html
anti_aliasing : bool, optional
Whether to apply a Gaussian filter to smooth the image prior
to down-scaling. It is crucial to filter when down-sampling
the image to avoid aliasing artifacts. If input image data
type is bool, no anti-aliasing is applied.
anti_aliasing_sigma : {float, tuple of floats}, optional
Standard deviation for Gaussian filtering to avoid aliasing artifacts.
By default, this value is chosen as (s - 1) / 2 where s is the
down-scaling factor.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Notes
-----
Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
pixels are duplicated during the reflection. As an example, if an array
has values [0, 1, 2] and was padded to the right by four values using
symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
would be [0, 1, 2, 1, 0, 1, 2].
Examples
--------
>>> from skimage import data
>>> from skimage.transform import rescale
>>> image = data.camera()
>>> rescale(image, 0.1).shape
(51, 51)
>>> rescale(image, 0.5).shape
(256, 256)
resize(image, output_shape, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None)
Resize image to match a certain size.
Performs interpolation to up-size or down-size N-dimensional images. Note
that anti-aliasing should be enabled when down-sizing images to avoid
aliasing artifacts. For downsampling with an integer factor also see
`skimage.transform.downscale_local_mean`.
Parameters
----------
image : ndarray
Input image.
output_shape : iterable
Size of the generated output image `(rows, cols[, ...][, dim])`. If
`dim` is not provided, the number of channels is preserved. In case the
number of input channels does not equal the number of output channels a
n-dimensional interpolation is applied.
Returns
-------
resized : ndarray
Resized version of the input.
Other parameters
----------------
order : int, optional
The order of the spline interpolation, default is 0 if
image.dtype is bool and 1 otherwise. The order has to be in
the range 0-5. See `skimage.transform.warp` for detail.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
Points outside the boundaries of the input are filled according
to the given mode. Modes match the behaviour of `numpy.pad`.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
clip : bool, optional
Whether to clip the output to the range of values of the input image.
This is enabled by default, since higher order interpolation may
produce values outside the given input range.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
anti_aliasing : bool, optional
Whether to apply a Gaussian filter to smooth the image prior
to downsampling. It is crucial to filter when downsampling
the image to avoid aliasing artifacts. If not specified, it is set to
True when downsampling an image whose data type is not bool.
It is also set to False when using nearest neighbor interpolation
(``order`` == 0) with integer input data type.
anti_aliasing_sigma : {float, tuple of floats}, optional
Standard deviation for Gaussian filtering used when anti-aliasing.
By default, this value is chosen as (s - 1) / 2 where s is the
downsampling factor, where s > 1. For the up-size case, s < 1, no
anti-aliasing is performed prior to rescaling.
Notes
-----
Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
pixels are duplicated during the reflection. As an example, if an array
has values [0, 1, 2] and was padded to the right by four values using
symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
would be [0, 1, 2, 1, 0, 1, 2].
Examples
--------
>>> from skimage import data
>>> from skimage.transform import resize
>>> image = data.camera()
>>> resize(image, (100, 100)).shape
(100, 100)
resize_local_mean(image, output_shape, grid_mode=True, preserve_range=False, *, channel_axis=None)
Resize an array with the local mean / bilinear scaling.
Parameters
----------
image : ndarray
Input image. If this is a multichannel image, the axis corresponding
to channels should be specified using `channel_axis`.
output_shape : iterable
Size of the generated output image. When `channel_axis` is not None,
the `channel_axis` should either be omitted from `output_shape` or the
``output_shape[channel_axis]`` must match
``image.shape[channel_axis]``. If the length of `output_shape` exceeds
image.ndim, additional singleton dimensions will be appended to the
input ``image`` as needed.
grid_mode : bool, optional
Defines ``image`` pixels position: if True, pixels are assumed to be at
grid intersections, otherwise at cell centers. As a consequence,
for example, a 1d signal of length 5 is considered to have length 4
when `grid_mode` is False, but length 5 when `grid_mode` is True. See
the following visual illustration:
.. code-block:: text
| pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
|<-------------------------------------->|
vs.
|<----------------------------------------------->|
The starting point of the arrow in the diagram above corresponds to
coordinate location 0 in each mode.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see
https://scikit-image.org/docs/dev/user_guide/data_types.html
Returns
-------
resized : ndarray
Resized version of the input.
See Also
--------
resize, downscale_local_mean
Notes
-----
This method is sometimes referred to as "area-based" interpolation or
"pixel mixing" interpolation [1]_. When `grid_mode` is True, it is
equivalent to using OpenCV's resize with `INTER_AREA` interpolation mode.
It is commonly used for image downsizing. If the downsizing factors are
integers, then `downscale_local_mean` should be preferred instead.
References
----------
.. [1] http://entropymine.com/imageworsener/pixelmixing/
Examples
--------
>>> from skimage import data
>>> from skimage.transform import resize_local_mean
>>> image = data.camera()
>>> resize_local_mean(image, (100, 100)).shape
(100, 100)
rotate(image, angle, resize=False, center=None, order=None, mode='constant', cval=0, clip=True, preserve_range=False)
Rotate image by a certain angle around its center.
Parameters
----------
image : ndarray
Input image.
angle : float
Rotation angle in degrees in counter-clockwise direction.
resize : bool, optional
Determine whether the shape of the output image will be automatically
calculated, so the complete rotated image exactly fits. Default is
False.
center : iterable of length 2
The rotation center. If ``center=None``, the image is rotated around
its center, i.e. ``center=(cols / 2 - 0.5, rows / 2 - 0.5)``. Please
note that this parameter is (cols, rows), contrary to normal skimage
ordering.
Returns
-------
rotated : ndarray
Rotated version of the input.
Other parameters
----------------
order : int, optional
The order of the spline interpolation, default is 0 if
image.dtype is bool and 1 otherwise. The order has to be in
the range 0-5. See `skimage.transform.warp` for detail.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
Points outside the boundaries of the input are filled according
to the given mode. Modes match the behaviour of `numpy.pad`.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
clip : bool, optional
Whether to clip the output to the range of values of the input image.
This is enabled by default, since higher order interpolation may
produce values outside the given input range.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see
https://scikit-image.org/docs/dev/user_guide/data_types.html
Notes
-----
Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
pixels are duplicated during the reflection. As an example, if an array
has values [0, 1, 2] and was padded to the right by four values using
symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
would be [0, 1, 2, 1, 0, 1, 2].
Examples
--------
>>> from skimage import data
>>> from skimage.transform import rotate
>>> image = data.camera()
>>> rotate(image, 2).shape
(512, 512)
>>> rotate(image, 2, resize=True).shape
(530, 530)
>>> rotate(image, 90, resize=True).shape
(512, 512)
swirl(image, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=None, mode='reflect', cval=0, clip=True, preserve_range=False)
Perform a swirl transformation.
Parameters
----------
image : ndarray
Input image.
center : (column, row) tuple or (2,) ndarray, optional
Center coordinate of transformation.
strength : float, optional
The amount of swirling applied.
radius : float, optional
The extent of the swirl in pixels. The effect dies out
rapidly beyond `radius`.
rotation : float, optional
Additional rotation applied to the image.
Returns
-------
swirled : ndarray
Swirled version of the input.
Other parameters
----------------
output_shape : tuple (rows, cols), optional
Shape of the output image generated. By default the shape of the input
image is preserved.
order : int, optional
The order of the spline interpolation, default is 0 if
image.dtype is bool and 1 otherwise. The order has to be in
the range 0-5. See `skimage.transform.warp` for detail.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
Points outside the boundaries of the input are filled according
to the given mode, with 'reflect' used as the default. Modes match
the behaviour of `numpy.pad`.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
clip : bool, optional
Whether to clip the output to the range of values of the input image.
This is enabled by default, since higher order interpolation may
produce values outside the given input range.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see
https://scikit-image.org/docs/dev/user_guide/data_types.html
warp(image, inverse_map, map_args=None, output_shape=None, order=None, mode='constant', cval=0.0, clip=True, preserve_range=False)
Warp an image according to a given coordinate transformation.
Parameters
----------
image : ndarray
Input image.
inverse_map : transformation object, callable ``cr = f(cr, **kwargs)``, or ndarray
Inverse coordinate map, which transforms coordinates in the output
images into their corresponding coordinates in the input image.
There are a number of different options to define this map, depending
on the dimensionality of the input image. A 2-D image can have 2
dimensions for gray-scale images, or 3 dimensions with color
information.
- For 2-D images, you can directly pass a transformation object,
e.g. `skimage.transform.SimilarityTransform`, or its inverse.
- For 2-D images, you can pass a ``(3, 3)`` homogeneous
transformation matrix, e.g.
`skimage.transform.SimilarityTransform.params`.
- For 2-D images, a function that transforms a ``(M, 2)`` array of
``(col, row)`` coordinates in the output image to their
corresponding coordinates in the input image. Extra parameters to
the function can be specified through `map_args`.
- For N-D images, you can directly pass an array of coordinates.
The first dimension specifies the coordinates in the input image,
while the subsequent dimensions determine the position in the
output image. E.g. in case of 2-D images, you need to pass an array
of shape ``(2, rows, cols)``, where `rows` and `cols` determine the
shape of the output image, and the first dimension contains the
``(row, col)`` coordinate in the input image.
See `scipy.ndimage.map_coordinates` for further documentation.
Note, that a ``(3, 3)`` matrix is interpreted as a homogeneous
transformation matrix, so you cannot interpolate values from a 3-D
input, if the output is of shape ``(3,)``.
See example section for usage.
map_args : dict, optional
Keyword arguments passed to `inverse_map`.
output_shape : tuple (rows, cols), optional
Shape of the output image generated. By default the shape of the input
image is preserved. Note that, even for multi-band images, only rows
and columns need to be specified.
order : int, optional
The order of interpolation. The order has to be in the range 0-5:
- 0: Nearest-neighbor
- 1: Bi-linear (default)
- 2: Bi-quadratic
- 3: Bi-cubic
- 4: Bi-quartic
- 5: Bi-quintic
Default is 0 if image.dtype is bool and 1 otherwise.
mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
Points outside the boundaries of the input are filled according
to the given mode. Modes match the behaviour of `numpy.pad`.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
clip : bool, optional
Whether to clip the output to the range of values of the input image.
This is enabled by default, since higher order interpolation may
produce values outside the given input range.
preserve_range : bool, optional
Whether to keep the original range of values. Otherwise, the input
image is converted according to the conventions of `img_as_float`.
Also see
https://scikit-image.org/docs/dev/user_guide/data_types.html
Returns
-------
warped : double ndarray
The warped input image.
Notes
-----
- The input image is converted to a `double` image.
- In case of a `SimilarityTransform`, `AffineTransform` and
`ProjectiveTransform` and `order` in [0, 3] this function uses the
underlying transformation matrix to warp the image with a much faster
routine.
Examples
--------
>>> from skimage.transform import warp
>>> from skimage import data
>>> image = data.camera()
The following image warps are all equal but differ substantially in
execution time. The image is shifted to the bottom.
Use a geometric transform to warp an image (fast):
>>> from skimage.transform import SimilarityTransform
>>> tform = SimilarityTransform(translation=(0, -10))
>>> warped = warp(image, tform)
Use a callable (slow):
>>> def shift_down(xy):
... xy[:, 1] -= 10
... return xy
>>> warped = warp(image, shift_down)
Use a transformation matrix to warp an image (fast):
>>> matrix = np.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]])
>>> warped = warp(image, matrix)
>>> from skimage.transform import ProjectiveTransform
>>> warped = warp(image, ProjectiveTransform(matrix=matrix))
You can also use the inverse of a geometric transformation (fast):
>>> warped = warp(image, tform.inverse)
For N-D images you can pass a coordinate array, that specifies the
coordinates in the input image for every element in the output image. E.g.
if you want to rescale a 3-D cube, you can do:
>>> cube_shape = np.array([30, 30, 30])
>>> rng = np.random.default_rng()
>>> cube = rng.random(cube_shape)
Setup the coordinate array, that defines the scaling:
>>> scale = 0.1
>>> output_shape = (scale * cube_shape).astype(int)
>>> coords0, coords1, coords2 = np.mgrid[:output_shape[0],
... :output_shape[1], :output_shape[2]]
>>> coords = np.array([coords0, coords1, coords2])
Assume that the cube contains spatial data, where the first array element
center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to
account for this extra offset when scaling the image:
>>> coords = (coords + 0.5) / scale - 0.5
>>> warped = warp(cube, coords)
warp_coords(coord_map, shape, dtype=<class 'numpy.float64'>)
Build the source coordinates for the output of a 2-D image warp.
Parameters
----------
coord_map : callable like GeometricTransform.inverse
Return input coordinates for given output coordinates.
Coordinates are in the shape (P, 2), where P is the number
of coordinates and each element is a ``(row, col)`` pair.
shape : tuple
Shape of output image ``(rows, cols[, bands])``.
dtype : np.dtype or string
dtype for return value (sane choices: float32 or float64).
Returns
-------
coords : (ndim, rows, cols[, bands]) array of dtype `dtype`
Coordinates for `scipy.ndimage.map_coordinates`, that will yield
an image of shape (orows, ocols, bands) by drawing from source
points according to the `coord_transform_fn`.
Notes
-----
This is a lower-level routine that produces the source coordinates for 2-D
images used by `warp()`.
It is provided separately from `warp` to give additional flexibility to
users who would like, for example, to re-use a particular coordinate
mapping, to use specific dtypes at various points along the the
image-warping process, or to implement different post-processing logic
than `warp` performs after the call to `ndi.map_coordinates`.
Examples
--------
Produce a coordinate map that shifts an image up and to the right:
>>> from skimage import data
>>> from scipy.ndimage import map_coordinates
>>>
>>> def shift_up10_left20(xy):
... return xy - np.array([-20, 10])[None, :]
>>>
>>> image = data.astronaut().astype(np.float32)
>>> coords = warp_coords(shift_up10_left20, image.shape)
>>> warped_image = map_coordinates(image, coords)
warp_polar(image, center=None, *, radius=None, output_shape=None, scaling='linear', channel_axis=None, **kwargs)
Remap image to polar or log-polar coordinates space.
Parameters
----------
image : (M, N[, C]) ndarray
Input image. For multichannel images `channel_axis` has to be specified.
center : 2-tuple, optional
`(row, col)` coordinates of the point in `image` that represents the center of
the transformation (i.e., the origin in Cartesian space). Values can be of
type `float`. If no value is given, the center is assumed to be the center point
of `image`.
radius : float, optional
Radius of the circle that bounds the area to be transformed.
output_shape : tuple (row, col), optional
scaling : {'linear', 'log'}, optional
Specify whether the image warp is polar or log-polar. Defaults to
'linear'.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
**kwargs : keyword arguments
Passed to `transform.warp`.
Returns
-------
warped : ndarray
The polar or log-polar warped image.
Examples
--------
Perform a basic polar warp on a grayscale image:
>>> from skimage import data
>>> from skimage.transform import warp_polar
>>> image = data.checkerboard()
>>> warped = warp_polar(image)
Perform a log-polar warp on a grayscale image:
>>> warped = warp_polar(image, scaling='log')
Perform a log-polar warp on a grayscale image while specifying center,
radius, and output shape:
>>> warped = warp_polar(image, (100,100), radius=100,
... output_shape=image.shape, scaling='log')
Perform a log-polar warp on a color image:
>>> image = data.astronaut()
>>> warped = warp_polar(image, scaling='log', channel_axis=-1)
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\transform\__init__.py
scikit-image.util
Python Library Documentation: package skimage.util in skimage
NAME
skimage.util - Generic utilities.
DESCRIPTION
This module contains a number of utility functions to work with images in general.
PACKAGE CONTENTS
_invert
_label
_map_array
_montage
_regular_grid
_remap
_slice_along_axes
apply_parallel
arraycrop
compare
dtype
lookfor
noise
shape
tests (package)
unique
FUNCTIONS
apply_parallel(function, array, chunks=None, depth=0, mode=None, extra_arguments=(), extra_keywords=None, *, dtype=None, compute=None, channel_axis=None)
Map a function in parallel across an array.
Split an array into possibly overlapping chunks of a given depth and
boundary type, call the given function in parallel on the chunks, combine
the chunks and return the resulting array.
Parameters
----------
function : function
Function to be mapped which takes an array as an argument.
array : numpy array or dask array
Array which the function will be applied to.
chunks : int, tuple, or tuple of tuples, optional
A single integer is interpreted as the length of one side of a square
chunk that should be tiled across the array. One tuple of length
``array.ndim`` represents the shape of a chunk, and it is tiled across
the array. A list of tuples of length ``ndim``, where each sub-tuple
is a sequence of chunk sizes along the corresponding dimension. If
None, the array is broken up into chunks based on the number of
available cpus. More information about chunks is in the documentation
`here <https://dask.pydata.org/en/latest/array-design.html>`_. When
`channel_axis` is not None, the tuples can be length ``ndim - 1`` and
a single chunk will be used along the channel axis.
depth : int or sequence of int, optional
The depth of the added boundary cells. A tuple can be used to specify a
different depth per array axis. Defaults to zero. When `channel_axis`
is not None, and a tuple of length ``ndim - 1`` is provided, a depth of
0 will be used along the channel axis.
mode : {'reflect', 'symmetric', 'periodic', 'wrap', 'nearest', 'edge'}, optional
Type of external boundary padding.
extra_arguments : tuple, optional
Tuple of arguments to be passed to the function.
extra_keywords : dictionary, optional
Dictionary of keyword arguments to be passed to the function.
dtype : data-type or None, optional
The data-type of the `function` output. If None, Dask will attempt to
infer this by calling the function on data of shape ``(1,) * ndim``.
For functions expecting RGB or multichannel data this may be
problematic. In such cases, the user should manually specify this dtype
argument instead.
.. versionadded:: 0.18
``dtype`` was added in 0.18.
compute : bool, optional
If ``True``, compute eagerly returning a NumPy Array.
If ``False``, compute lazily returning a Dask Array.
If ``None`` (default), compute based on array type provided
(eagerly for NumPy Arrays and lazily for Dask Arrays).
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.
Returns
-------
out : ndarray or dask Array
Returns the result of the applying the operation.
Type is dependent on the ``compute`` argument.
Notes
-----
Numpy edge modes 'symmetric', 'wrap', and 'edge' are converted to the
equivalent ``dask`` boundary modes 'reflect', 'periodic' and 'nearest',
respectively.
Setting ``compute=False`` can be useful for chaining later operations.
For example region selection to preview a result or storing large data
to disk instead of loading in memory.
compare_images(image0, image1, *, method='diff', n_tiles=(8, 8))
Return an image showing the differences between two images.
.. versionadded:: 0.16
Parameters
----------
image0, image1 : ndarray, shape (M, N)
Images to process, must be of the same shape.
.. versionchanged:: 0.24
`image1` and `image2` were renamed into `image0` and `image1`
respectively.
method : string, optional
Method used for the comparison.
Valid values are {'diff', 'blend', 'checkerboard'}.
Details are provided in the note section.
.. versionchanged:: 0.24
This parameter and following ones are keyword-only.
n_tiles : tuple, optional
Used only for the `checkerboard` method. Specifies the number
of tiles (row, column) to divide the image.
Returns
-------
comparison : ndarray, shape (M, N)
Image showing the differences.
Notes
-----
``'diff'`` computes the absolute difference between the two images.
``'blend'`` computes the mean value.
``'checkerboard'`` makes tiles of dimension `n_tiles` that display
alternatively the first and the second image. Note that images must be
2-dimensional to be compared with the checkerboard method.
crop(ar, crop_width, copy=False, order='K')
Crop array `ar` by `crop_width` along each dimension.
Parameters
----------
ar : array-like of rank N
Input array.
crop_width : {sequence, int}
Number of values to remove from the edges of each axis.
``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies
unique crop widths at the start and end of each axis.
``((before, after),) or (before, after)`` specifies
a fixed start and end crop for every axis.
``(n,)`` or ``n`` for integer ``n`` is a shortcut for
before = after = ``n`` for all axes.
copy : bool, optional
If `True`, ensure the returned array is a contiguous copy. Normally,
a crop operation will return a discontiguous view of the underlying
input array.
order : {'C', 'F', 'A', 'K'}, optional
If ``copy==True``, control the memory layout of the copy. See
``np.copy``.
Returns
-------
cropped : array
The cropped array. If ``copy=False`` (default), this is a sliced
view of the input array.
dtype_limits(image, clip_negative=False)
Return intensity limits, i.e. (min, max) tuple, of the image's dtype.
Parameters
----------
image : ndarray
Input image.
clip_negative : bool, optional
If True, clip the negative range (i.e. return 0 for min intensity)
even if the image dtype allows negative values.
Returns
-------
imin, imax : tuple
Lower and upper intensity limits.
img_as_bool(image, force_copy=False)
Convert an image to boolean format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of bool (`bool_`)
Output image.
Notes
-----
The upper half of the input dtype's positive range is True, and the lower
half is False. All negative values (if present) are False.
img_as_float(image, force_copy=False)
Convert an image to floating point format.
This function is similar to `img_as_float64`, but will not convert
lower-precision floating point arrays to `float64`.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of float
Output image.
Notes
-----
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when
converting from unsigned or signed datatypes, respectively.
If the input image has a float type, intensity values are not modified
and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
img_as_float32(image, force_copy=False)
Convert an image to single-precision (32-bit) floating point format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of float32
Output image.
Notes
-----
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when
converting from unsigned or signed datatypes, respectively.
If the input image has a float type, intensity values are not modified
and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
img_as_float64(image, force_copy=False)
Convert an image to double-precision (64-bit) floating point format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of float64
Output image.
Notes
-----
The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when
converting from unsigned or signed datatypes, respectively.
If the input image has a float type, intensity values are not modified
and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
img_as_int(image, force_copy=False)
Convert an image to 16-bit signed integer format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of int16
Output image.
Notes
-----
The values are scaled between -32768 and 32767.
If the input data-type is positive-only (e.g., uint8), then
the output image will still only have positive values.
img_as_ubyte(image, force_copy=False)
Convert an image to 8-bit unsigned integer format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of ubyte (uint8)
Output image.
Notes
-----
Negative input values will be clipped.
Positive values are scaled between 0 and 255.
img_as_uint(image, force_copy=False)
Convert an image to 16-bit unsigned integer format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool, optional
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of uint16
Output image.
Notes
-----
Negative input values will be clipped.
Positive values are scaled between 0 and 65535.
invert(image, signed_float=False)
Invert an image.
Invert the intensity range of the input image, so that the dtype maximum
is now the dtype minimum, and vice-versa. This operation is
slightly different depending on the input dtype:
- unsigned integers: subtract the image from the dtype maximum
- signed integers: subtract the image from -1 (see Notes)
- floats: subtract the image from 1 (if signed_float is False, so we
assume the image is unsigned), or from 0 (if signed_float is True).
See the examples for clarification.
Parameters
----------
image : ndarray
Input image.
signed_float : bool, optional
If True and the image is of type float, the range is assumed to
be [-1, 1]. If False and the image is of type float, the range is
assumed to be [0, 1].
Returns
-------
inverted : ndarray
Inverted image.
Notes
-----
Ideally, for signed integers we would simply multiply by -1. However,
signed integer ranges are asymmetric. For example, for np.int8, the range
of possible values is [-128, 127], so that -128 * -1 equals -128! By
subtracting from -1, we correctly map the maximum dtype value to the
minimum.
Examples
--------
>>> img = np.array([[100, 0, 200],
... [ 0, 50, 0],
... [ 30, 0, 255]], np.uint8)
>>> invert(img)
array([[155, 255, 55],
[255, 205, 255],
[225, 255, 0]], dtype=uint8)
>>> img2 = np.array([[ -2, 0, -128],
... [127, 0, 5]], np.int8)
>>> invert(img2)
array([[ 1, -1, 127],
[-128, -1, -6]], dtype=int8)
>>> img3 = np.array([[ 0., 1., 0.5, 0.75]])
>>> invert(img3)
array([[1. , 0. , 0.5 , 0.25]])
>>> img4 = np.array([[ 0., 1., -1., -0.25]])
>>> invert(img4, signed_float=True)
array([[-0. , -1. , 1. , 0.25]])
label_points(coords, output_shape)
Assign unique integer labels to coordinates on an image mask
Parameters
----------
coords: ndarray
An array of N coordinates with dimension D
output_shape: tuple
The shape of the mask on which `coords` are labelled
Returns
-------
labels: ndarray
A mask of zeroes containing unique integer labels at the `coords`
Examples
--------
>>> import numpy as np
>>> from skimage.util._label import label_points
>>> coords = np.array([[0, 1], [2, 2]])
>>> output_shape = (5, 5)
>>> mask = label_points(coords, output_shape)
>>> mask
array([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint64)
Notes
-----
- The labels are assigned to coordinates that are converted to
integer and considered to start from 0.
- Coordinates that are out of range of the mask raise an IndexError.
- Negative coordinates raise a ValueError
lookfor(what)
Do a keyword search on scikit-image docstrings and print results.
.. warning::
This function may also print results that are not part of
scikit-image's public API.
Parameters
----------
what : str
Words to look for.
Examples
--------
>>> import skimage as ski
>>> ski.util.lookfor('regular_grid')
Search results for 'regular_grid'
---------------------------------
skimage.util.regular_grid
Find `n_points` regularly spaced along `ar_shape`.
skimage.util.lookfor
Do a keyword search on scikit-image docstrings and print results.
map_array(input_arr, input_vals, output_vals, out=None)
Map values from input array from input_vals to output_vals.
Parameters
----------
input_arr : array of int, shape (M[, ...])
The input label image.
input_vals : array of int, shape (K,)
The values to map from.
output_vals : array, shape (K,)
The values to map to.
out: array, same shape as `input_arr`
The output array. Will be created if not provided. It should
have the same dtype as `output_vals`.
Returns
-------
out : array, same shape as `input_arr`
The array of mapped values.
Notes
-----
If `input_arr` contains values that aren't covered by `input_vals`, they
are set to 0.
Examples
--------
>>> import numpy as np
>>> import skimage as ski
>>> ski.util.map_array(
... input_arr=np.array([[0, 2, 2, 0], [3, 4, 5, 0]]),
... input_vals=np.array([1, 2, 3, 4, 6]),
... output_vals=np.array([6, 7, 8, 9, 10]),
... )
array([[0, 7, 7, 0],
[8, 9, 0, 0]])
montage(arr_in, fill='mean', rescale_intensity=False, grid_shape=None, padding_width=0, *, channel_axis=None)
Create a montage of several single- or multichannel images.
Create a rectangular montage from an input array representing an ensemble
of equally shaped single- (gray) or multichannel (color) images.
For example, ``montage(arr_in)`` called with the following `arr_in`
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
will return
+---+---+
| 1 | 2 |
+---+---+
| 3 | * |
+---+---+
where the '*' patch will be determined by the `fill` parameter.
Parameters
----------
arr_in : ndarray, shape (K, M, N[, C])
An array representing an ensemble of `K` images of equal shape.
fill : float or array-like of floats or 'mean', optional
Value to fill the padding areas and/or the extra tiles in
the output array. Has to be `float` for single channel collections.
For multichannel collections has to be an array-like of shape of
number of channels. If `mean`, uses the mean value over all images.
rescale_intensity : bool, optional
Whether to rescale the intensity of each image to [0, 1].
grid_shape : tuple, optional
The desired grid shape for the montage `(ntiles_row, ntiles_column)`.
The default aspect ratio is square.
padding_width : int, optional
The size of the spacing between the tiles and between the tiles and
the borders. If non-zero, makes the boundaries of individual images
easier to perceive.
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.
Returns
-------
arr_out : (K*(M+p)+p, K*(N+p)+p[, C]) ndarray
Output array with input images glued together (including padding `p`).
Examples
--------
>>> import numpy as np
>>> from skimage.util import montage
>>> arr_in = np.arange(3 * 2 * 2).reshape(3, 2, 2)
>>> arr_in # doctest: +NORMALIZE_WHITESPACE
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
>>> arr_out = montage(arr_in)
>>> arr_out.shape
(4, 4)
>>> arr_out
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 5, 5],
[10, 11, 5, 5]])
>>> arr_in.mean()
5.5
>>> arr_out_nonsquare = montage(arr_in, grid_shape=(1, 3))
>>> arr_out_nonsquare
array([[ 0, 1, 4, 5, 8, 9],
[ 2, 3, 6, 7, 10, 11]])
>>> arr_out_nonsquare.shape
(2, 6)
random_noise(image, mode='gaussian', rng=None, clip=True, **kwargs)
Function to add random noise of various types to a floating-point image.
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str, optional
One of the following strings, selecting the type of noise to add:
'gaussian' (default)
Gaussian-distributed additive noise.
'localvar'
Gaussian-distributed additive noise, with specified local variance
at each point of `image`.
'poisson'
Poisson-distributed noise generated from the data.
'salt'
Replaces random pixels with 1.
'pepper'
Replaces random pixels with 0 (for unsigned images) or -1 (for
signed images).
's&p'
Replaces random pixels with either 1 or `low_val`, where `low_val`
is 0 for unsigned images or -1 for signed images.
'speckle'
Multiplicative noise using ``out = image + n * image``, where ``n``
is Gaussian noise with specified mean & variance.
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.
clip : bool, optional
If True (default), the output will be clipped after noise applied
for modes `'speckle'`, `'poisson'`, and `'gaussian'`. This is
needed to maintain the proper image data range. If False, clipping
is not applied, and the output may extend beyond the range [-1, 1].
mean : float, optional
Mean of random distribution. Used in 'gaussian' and 'speckle'.
Default : 0.
var : float, optional
Variance of random distribution. Used in 'gaussian' and 'speckle'.
Note: variance = (standard deviation) ** 2. Default : 0.01
local_vars : ndarray, optional
Array of positive floats, same shape as `image`, defining the local
variance at every image point. Used in 'localvar'.
amount : float, optional
Proportion of image pixels to replace with noise on range [0, 1].
Used in 'salt', 'pepper', and 'salt & pepper'. Default : 0.05
salt_vs_pepper : float, optional
Proportion of salt vs. pepper noise for 's&p' on range [0, 1].
Higher values represent more salt. Default : 0.5 (equal amounts)
Returns
-------
out : ndarray
Output floating-point image data on range [0, 1] or [-1, 1] if the
input `image` was unsigned or signed, respectively.
Notes
-----
Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside
the valid image range. The default is to clip (not alias) these values,
but they may be preserved by setting `clip=False`. Note that in this case
the output may contain values outside the ranges [0, 1] or [-1, 1].
Use this option with care.
Because of the prevalence of exclusively positive floating-point images in
intermediate calculations, it is not possible to intuit if an input is
signed based on dtype alone. Instead, negative values are explicitly
searched for. Only if found does this function assume signed input.
Unexpected results only occur in rare, poorly exposes cases (e.g. if all
values are above 50 percent gray in a signed `image`). In this event,
manually scaling the input to the positive domain will solve the problem.
The Poisson distribution is only defined for positive integers. To apply
this noise type, the number of unique values in the image is found and
the next round power of two is used to scale up the floating-point result,
after which it is scaled back down to the floating-point image range.
To generate Poisson noise against a signed image, the signed image is
temporarily converted to an unsigned image in the floating point domain,
Poisson noise is generated, then it is returned to the original range.
regular_grid(ar_shape, n_points)
Find `n_points` regularly spaced along `ar_shape`.
The returned points (as slices) should be as close to cubically-spaced as
possible. Essentially, the points are spaced by the Nth root of the input
array size, where N is the number of dimensions. However, if an array
dimension cannot fit a full step size, it is "discarded", and the
computation is done for only the remaining dimensions.
Parameters
----------
ar_shape : array-like of ints
The shape of the space embedding the grid. ``len(ar_shape)`` is the
number of dimensions.
n_points : int
The (approximate) number of points to embed in the space.
Returns
-------
slices : tuple of slice objects
A slice along each dimension of `ar_shape`, such that the intersection
of all the slices give the coordinates of regularly spaced points.
.. versionchanged:: 0.14.1
In scikit-image 0.14.1 and 0.15, the return type was changed from a
list to a tuple to ensure `compatibility with Numpy 1.15`_ and
higher. If your code requires the returned result to be a list, you
may convert the output of this function to a list with:
>>> result = list(regular_grid(ar_shape=(3, 20, 40), n_points=8))
.. _compatibility with NumPy 1.15: https://github.com/numpy/numpy/blob/master/doc/release/1.15.0-notes.rst#deprecations
Examples
--------
>>> ar = np.zeros((20, 40))
>>> g = regular_grid(ar.shape, 8)
>>> g
(slice(5, None, 10), slice(5, None, 10))
>>> ar[g] = 1
>>> ar.sum()
8.0
>>> ar = np.zeros((20, 40))
>>> g = regular_grid(ar.shape, 32)
>>> g
(slice(2, None, 5), slice(2, None, 5))
>>> ar[g] = 1
>>> ar.sum()
32.0
>>> ar = np.zeros((3, 20, 40))
>>> g = regular_grid(ar.shape, 8)
>>> g
(slice(1, None, 3), slice(5, None, 10), slice(5, None, 10))
>>> ar[g] = 1
>>> ar.sum()
8.0
regular_seeds(ar_shape, n_points, dtype=<class 'int'>)
Return an image with ~`n_points` regularly-spaced nonzero pixels.
Parameters
----------
ar_shape : tuple of int
The shape of the desired output image.
n_points : int
The desired number of nonzero points.
dtype : numpy data type, optional
The desired data type of the output.
Returns
-------
seed_img : array of int or bool
The desired image.
Examples
--------
>>> regular_seeds((5, 5), 4)
array([[0, 0, 0, 0, 0],
[0, 1, 0, 2, 0],
[0, 0, 0, 0, 0],
[0, 3, 0, 4, 0],
[0, 0, 0, 0, 0]])
slice_along_axes(image, slices, axes=None, copy=False)
Slice an image along given axes.
Parameters
----------
image : ndarray
Input image.
slices : list of 2-tuple (a, b) where a < b.
For each axis in `axes`, a corresponding 2-tuple
``(min_val, max_val)`` to slice with (as with Python slices,
``max_val`` is non-inclusive).
axes : int or tuple, optional
Axes corresponding to the limits given in `slices`. If None,
axes are in ascending order, up to the length of `slices`.
copy : bool, optional
If True, ensure that the output is not a view of `image`.
Returns
-------
out : ndarray
The region of `image` corresponding to the given slices and axes.
Examples
--------
>>> from skimage import data
>>> img = data.camera()
>>> img.shape
(512, 512)
>>> cropped_img = slice_along_axes(img, [(0, 100)])
>>> cropped_img.shape
(100, 512)
>>> cropped_img = slice_along_axes(img, [(0, 100), (0, 100)])
>>> cropped_img.shape
(100, 100)
>>> cropped_img = slice_along_axes(img, [(0, 100), (0, 75)], axes=[1, 0])
>>> cropped_img.shape
(75, 100)
unique_rows(ar)
Remove repeated rows from a 2D array.
In particular, if given an array of coordinates of shape
(Npoints, Ndim), it will remove repeated points.
Parameters
----------
ar : ndarray, shape (M, N)
The input array.
Returns
-------
ar_out : ndarray, shape (P, N)
A copy of the input array with repeated rows removed.
Raises
------
ValueError : if `ar` is not two-dimensional.
Notes
-----
The function will generate a copy of `ar` if it is not
C-contiguous, which will negatively affect performance for large
input arrays.
Examples
--------
>>> ar = np.array([[1, 0, 1],
... [0, 1, 0],
... [1, 0, 1]], np.uint8)
>>> unique_rows(ar)
array([[0, 1, 0],
[1, 0, 1]], dtype=uint8)
view_as_blocks(arr_in, block_shape)
Block view of the input n-dimensional array (using re-striding).
Blocks are non-overlapping views of the input array.
Parameters
----------
arr_in : ndarray, shape (M[, ...])
Input array.
block_shape : tuple
The shape of the block. Each dimension must divide evenly into the
corresponding dimensions of `arr_in`.
Returns
-------
arr_out : ndarray
Block view of the input array.
Examples
--------
>>> import numpy as np
>>> from skimage.util.shape import view_as_blocks
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> B = view_as_blocks(A, block_shape=(2, 2))
>>> B[0, 0]
array([[0, 1],
[4, 5]])
>>> B[0, 1]
array([[2, 3],
[6, 7]])
>>> B[1, 0, 1, 1]
13
>>> A = np.arange(4*4*6).reshape(4,4,6)
>>> A # doctest: +NORMALIZE_WHITESPACE
array([[[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]],
[[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47]],
[[48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65],
[66, 67, 68, 69, 70, 71]],
[[72, 73, 74, 75, 76, 77],
[78, 79, 80, 81, 82, 83],
[84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95]]])
>>> B = view_as_blocks(A, block_shape=(1, 2, 2))
>>> B.shape
(4, 2, 3, 1, 2, 2)
>>> B[2:, 0, 2] # doctest: +NORMALIZE_WHITESPACE
array([[[[52, 53],
[58, 59]]],
[[[76, 77],
[82, 83]]]])
view_as_windows(arr_in, window_shape, step=1)
Rolling window view of the input n-dimensional array.
Windows are overlapping views of the input array, with adjacent windows
shifted by a single row or column (or an index of a higher dimension).
Parameters
----------
arr_in : ndarray, shape (M[, ...])
Input array.
window_shape : integer or tuple of length arr_in.ndim
Defines the shape of the elementary n-dimensional orthotope
(better know as hyperrectangle [1]_) of the rolling window view.
If an integer is given, the shape will be a hypercube of
sidelength given by its value.
step : integer or tuple of length arr_in.ndim
Indicates step size at which extraction shall be performed.
If integer is given, then the step is uniform in all dimensions.
Returns
-------
arr_out : ndarray
(rolling) window view of the input array.
Notes
-----
One should be very careful with rolling views when it comes to
memory usage. Indeed, although a 'view' has the same memory
footprint as its base array, the actual array that emerges when this
'view' is used in a computation is generally a (much) larger array
than the original, especially for 2-dimensional arrays and above.
For example, let us consider a 3 dimensional array of size (100,
100, 100) of ``float64``. This array takes about 8*100**3 Bytes for
storage which is just 8 MB. If one decides to build a rolling view
on this array with a window of (3, 3, 3) the hypothetical size of
the rolling view (if one was to reshape the view for example) would
be 8*(100-3+1)**3*3**3 which is about 203 MB! The scaling becomes
even worse as the dimension of the input array becomes larger.
References
----------
.. [1] https://en.wikipedia.org/wiki/Hyperrectangle
Examples
--------
>>> import numpy as np
>>> from skimage.util.shape import view_as_windows
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> window_shape = (2, 2)
>>> B = view_as_windows(A, window_shape)
>>> B[0, 0]
array([[0, 1],
[4, 5]])
>>> B[0, 1]
array([[1, 2],
[5, 6]])
>>> A = np.arange(10)
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(8, 3)
>>> B
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7],
[6, 7, 8],
[7, 8, 9]])
>>> A = np.arange(5*4).reshape(5, 4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> window_shape = (4, 3)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(2, 2, 4, 3)
>>> B # doctest: +NORMALIZE_WHITESPACE
array([[[[ 0, 1, 2],
[ 4, 5, 6],
[ 8, 9, 10],
[12, 13, 14]],
[[ 1, 2, 3],
[ 5, 6, 7],
[ 9, 10, 11],
[13, 14, 15]]],
[[[ 4, 5, 6],
[ 8, 9, 10],
[12, 13, 14],
[16, 17, 18]],
[[ 5, 6, 7],
[ 9, 10, 11],
[13, 14, 15],
[17, 18, 19]]]])
DATA
__all__ = ['img_as_float32', 'img_as_float64', 'img_as_float', 'img_as...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\skimage\util\__init__.py