

scikit-image 0.18.0 docs
========================

 scikit-image is an image processing toolbox for [SciPy](https://www.scipy.org). View the latest [release notes here](https://scikit-image.org/docs/0.18.x/release_notes.html).

 Sections
--------

 

|  |  |
| --- | --- |
| [Overview](https://scikit-image.org/docs/0.18.x/overview.html) Introduction to scikit-image. | [API Reference](api/api) ([changes](https://scikit-image.org/docs/0.18.x/api_changes.html)) Documentation for the functions included in scikit-image. |
| [Mission Statement](https://scikit-image.org/docs/0.18.x/values.html) Our mission, vision, and values. | [Governance](https://scikit-image.org/docs/0.18.x/skips/1-governance.html) How decisions are made in scikit-image. |
| [Installation](https://scikit-image.org/docs/0.18.x/install.html) How to install scikit-image. | [User Guide](user_guide) Usage guidelines. |
| [Glossary](https://scikit-image.org/docs/0.18.x/glossary.html) Definitions of common terms. | [Contribute](https://scikit-image.org/docs/0.18.x/contribute.html) Take part in development. Core developers, please [read your guide](https://scikit-image.org/docs/0.18.x/core_developer.html). |
| [Gallery](https://scikit-image.org/docs/0.18.x/auto_examples/index.html) Introductory generic and domain-specific examples. | [License Info](https://scikit-image.org/docs/0.18.x/license.html) Conditions on the use and redistribution of this package. |
| [SKIPs](https://scikit-image.org/docs/0.18.x/skips/index.html) **s**ci**k**it-**i**mage **p**roposals, documents describing major changes to the library. | [Code of Conduct](https://scikit-image.org/docs/0.18.x/conduct/code_of_conduct.html) Community interaction guidelines. |

 Indices
-------

 

|  |  |
| --- | --- |
| [Search Page](https://scikit-image.org/docs/0.18.x/search.html) Search this documentation. | [Index](https://scikit-image.org/docs/0.18.x/genindex.html) All functions, classes, terms. |



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/>

User Guide
==========

 * [Getting started](user_guide/getting_started)
* [A crash course on NumPy for images](user_guide/numpy_images)
	+ [NumPy indexing](user_guide/numpy_images#numpy-indexing)
	+ [Color images](user_guide/numpy_images#color-images)
	+ [Coordinate conventions](user_guide/numpy_images#coordinate-conventions)
	+ [Notes on the order of array dimensions](user_guide/numpy_images#notes-on-the-order-of-array-dimensions)
	+ [A note on the time dimension](user_guide/numpy_images#a-note-on-the-time-dimension)
* [Image data types and what they mean](user_guide/data_types)
	+ [Input types](user_guide/data_types#input-types)
	+ [Output types](user_guide/data_types#output-types)
	+ [Working with OpenCV](user_guide/data_types#working-with-opencv)
	+ [Image processing pipeline](user_guide/data_types#image-processing-pipeline)
	+ [Rescaling intensity values](user_guide/data_types#rescaling-intensity-values)
	+ [Note about negative values](user_guide/data_types#note-about-negative-values)
	+ [References](user_guide/data_types#references)
* [I/O Plugin Infrastructure](user_guide/plugins)
* [Handling Video Files](user_guide/video)
	+ [A Workaround: Convert the Video to an Image Sequence](user_guide/video#a-workaround-convert-the-video-to-an-image-sequence)
	+ [PyAV](user_guide/video#pyav)
	+ [Adding Random Access to PyAV](user_guide/video#adding-random-access-to-pyav)
	+ [MoviePy](user_guide/video#moviepy)
	+ [Imageio](user_guide/video#imageio)
	+ [OpenCV](user_guide/video#opencv)
* [Data visualization](user_guide/visualization)
	+ [Matplotlib](user_guide/visualization#matplotlib)
	+ [Plotly](user_guide/visualization#plotly)
	+ [Mayavi](user_guide/visualization#mayavi)
	+ [Napari](user_guide/visualization#napari)
* [Image adjustment: transforming image content](user_guide/transforming_image_data)
	+ [Color manipulation](user_guide/transforming_image_data#color-manipulation)
	+ [Contrast and exposure](user_guide/transforming_image_data#contrast-and-exposure)
* [Geometrical transformations of images](user_guide/geometrical_transform)
	+ [Cropping, resizing and rescaling images](user_guide/geometrical_transform#cropping-resizing-and-rescaling-images)
	+ [Projective transforms (homographies)](user_guide/geometrical_transform#projective-transforms-homographies)
* [Tutorials](user_guide/tutorials)
	+ [Image Segmentation](user_guide/tutorial_segmentation)
	+ [How to parallelize loops](user_guide/tutorial_parallelization)
* [Getting help on using `skimage`](user_guide/getting_help)
	+ [Examples gallery](user_guide/getting_help#examples-gallery)
	+ [Search field](user_guide/getting_help#search-field)
	+ [API Discovery](user_guide/getting_help#api-discovery)
	+ [Docstrings](user_guide/getting_help#docstrings)
	+ [Mailing-list](user_guide/getting_help#mailing-list)
* [Image Viewer](user_guide/viewer)
	+ [Quick Start](user_guide/viewer#quick-start)



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide.html>

skimage
=======

 Image Processing for Python

 `scikit-image` (a.k.a. `skimage`) is a collection of algorithms for image processing and computer vision.

 The main package of `skimage` only provides a few utilities for converting between image data types; for most features, you need to import one of the following subpackages:

 Subpackages
-----------

  color

Color space conversion.

  data

Test images and example data.

  draw

Drawing primitives (lines, text, etc.) that operate on NumPy arrays.

  exposure

Image intensity adjustment, e.g., histogram equalization, etc.

  feature

Feature detection and extraction, e.g., texture analysis corners, etc.

  filters

Sharpening, edge finding, rank filters, thresholding, etc.

  graph

Graph-theoretic operations, e.g., shortest paths.

  io

Reading, saving, and displaying images and video.

  measure

Measurement of image properties, e.g., region properties and contours.

  metrics

Metrics corresponding to images, e.g. distance metrics, similarity, etc.

  morphology

Morphological operations, e.g., opening or skeletonization.

  restoration

Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.

  segmentation

Partitioning an image into multiple regions.

  transform

Geometric and other transforms, e.g., rotation or the Radon transform.

  util

Generic utilities.

  viewer

A simple graphical user interface for visualizing results and exploring parameters.

   Utility Functions
-----------------

  img\_as\_float

Convert an image to floating point format, with values in [0, 1]. Is similar to [`img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`.

  img\_as\_float32

Convert an image to single-precision (32-bit) floating point format, with values in [0, 1].

  img\_as\_float64

Convert an image to double-precision (64-bit) floating point format, with values in [0, 1].

  img\_as\_uint

Convert an image to unsigned integer format, with values in [0, 65535].

  img\_as\_int

Convert an image to signed integer format, with values in [-32768, 32767].

  img\_as\_ubyte

Convert an image to unsigned byte format, with values in [0, 255].

  img\_as\_bool

Convert an image to boolean format, with values either True or False.

  dtype\_limits

Return intensity limits, i.e. (min, max) tuple, of the image’s dtype.

   

|  |  |
| --- | --- |
| [`skimage.dtype_limits`](#skimage.dtype_limits "skimage.dtype_limits")(image[, clip\_negative]) | Return intensity limits, i.e. |
| [`skimage.ensure_python_version`](#skimage.ensure_python_version "skimage.ensure_python_version")(min\_version) |  |
| [`skimage.img_as_bool`](#skimage.img_as_bool "skimage.img_as_bool")(image[, force\_copy]) | Convert an image to boolean format. |
| [`skimage.img_as_float`](#skimage.img_as_float "skimage.img_as_float")(image[, force\_copy]) | Convert an image to floating point format. |
| [`skimage.img_as_float32`](#skimage.img_as_float32 "skimage.img_as_float32")(image[, force\_copy]) | Convert an image to single-precision (32-bit) floating point format. |
| [`skimage.img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64")(image[, force\_copy]) | Convert an image to double-precision (64-bit) floating point format. |
| [`skimage.img_as_int`](#skimage.img_as_int "skimage.img_as_int")(image[, force\_copy]) | Convert an image to 16-bit signed integer format. |
| [`skimage.img_as_ubyte`](#skimage.img_as_ubyte "skimage.img_as_ubyte")(image[, force\_copy]) | Convert an image to 8-bit unsigned integer format. |
| [`skimage.img_as_uint`](#skimage.img_as_uint "skimage.img_as_uint")(image[, force\_copy]) | Convert an image to 16-bit unsigned integer format. |
| [`skimage.lookfor`](#skimage.lookfor "skimage.lookfor")(what) | Do a keyword search on scikit-image docstrings. |
| [`skimage.data`](skimage.data#module-skimage.data "skimage.data") | Standard test images. |
| [`skimage.util`](skimage.util#module-skimage.util "skimage.util") |  |

 dtype\_limits
-------------

  
`skimage.dtype_limits(image, clip_negative=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L38-L57)
 
Return intensity limits, i.e. (min, max) tuple, of the image’s dtype.

  Parameters 
 
`imagendarray` 

Input image.

  
`clip_negativebool, optional` 

If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values.

    Returns 
 
`imin, imaxtuple` 

Lower and upper intensity limits.

     
 ensure\_python\_version
-----------------------

  
`skimage.ensure_python_version(min_version)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/_shared/version_requirements.py#L4-L30)

 img\_as\_bool
-------------

  
`skimage.img_as_bool(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L534-L555)
 
Convert an image to boolean format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
--------------

  
`skimage.img_as_float(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L432-L458)
 
Convert an image to floating point format.

 This function is similar to [`img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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].

 
 ### Examples using `skimage.img_as_float`

 
 ![Tinting gray-scale images]

  

 ![3D adaptive histogram equalization]

  

 ![Phase Unwrapping]

  

 ![Finding local maxima]

  

 ![Use rolling-ball algorithm for estimating background intensity]

  

 ![Explore 3D images (of cells)]

   img\_as\_float32
----------------

  
`skimage.img_as_float32(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L380-L403)
 
Convert an image to single-precision (32-bit) floating point format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
----------------

  
`skimage.img_as_float64(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L406-L429)
 
Convert an image to double-precision (64-bit) floating point format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
------------

  
`skimage.img_as_int(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L485-L507)
 
Convert an image to 16-bit signed integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
--------------

  
`skimage.img_as_ubyte(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L510-L531)
 
Convert an image to 8-bit unsigned integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray of ubyte (uint8)` 

Output image.

     #### Notes

 Negative input values will be clipped. Positive values are scaled between 0 and 255.

 
 ### Examples using `skimage.img_as_ubyte`

 
 ![Local Histogram Equalization]

  

 ![Entropy]

  

 ![Markers for watershed transform]

  

 ![Segment human cells (in mitosis)]

  

 ![Rank filters]

   img\_as\_uint
-------------

  
`skimage.img_as_uint(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L461-L482)
 
Convert an image to 16-bit unsigned integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray of uint16` 

Output image.

     #### Notes

 Negative input values will be clipped. Positive values are scaled between 0 and 65535.

 
 lookfor
-------

  
`skimage.lookfor(what)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/lookfor.py#L5-L24)
 
Do a keyword search on scikit-image docstrings.

  Parameters 
 
`whatstr` 

Words to look for.

     #### Examples

 
```
>>> import skimage
>>> skimage.lookfor('regular_grid')
Search results for 'regular_grid'
---------------------------------
skimage.lookfor
    Do a keyword search on scikit-image docstrings.
skimage.util.regular_grid
    Find `n_points` regularly spaced along `ar_shape`.

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.html>

Module: color
=============

 

|  |  |
| --- | --- |
| [`skimage.color.combine_stains`](#skimage.color.combine_stains "skimage.color.combine_stains")(stains, conv\_matrix) | Stain to RGB color space conversion. |
| [`skimage.color.convert_colorspace`](#skimage.color.convert_colorspace "skimage.color.convert_colorspace")(arr, …) | Convert an image array to a new color space. |
| [`skimage.color.deltaE_cie76`](#skimage.color.deltaE_cie76 "skimage.color.deltaE_cie76")(lab1, lab2) | Euclidean distance between two points in Lab color space |
| [`skimage.color.deltaE_ciede2000`](#skimage.color.deltaE_ciede2000 "skimage.color.deltaE_ciede2000")(lab1, lab2[, …]) | Color difference as given by the CIEDE 2000 standard. |
| [`skimage.color.deltaE_ciede94`](#skimage.color.deltaE_ciede94 "skimage.color.deltaE_ciede94")(lab1, lab2[, …]) | Color difference according to CIEDE 94 standard |
| [`skimage.color.deltaE_cmc`](#skimage.color.deltaE_cmc "skimage.color.deltaE_cmc")(lab1, lab2[, kL, kC]) | Color difference from the CMC l:c standard. |
| [`skimage.color.gray2rgb`](#skimage.color.gray2rgb "skimage.color.gray2rgb")(image[, alpha]) | Create an RGB representation of a gray-level image. |
| [`skimage.color.gray2rgba`](#skimage.color.gray2rgba "skimage.color.gray2rgba")(image[, alpha]) | Create a RGBA representation of a gray-level image. |
| [`skimage.color.grey2rgb`](#skimage.color.grey2rgb "skimage.color.grey2rgb")(image[, alpha]) | Create an RGB representation of a gray-level image. |
| [`skimage.color.hed2rgb`](#skimage.color.hed2rgb "skimage.color.hed2rgb")(hed) | Haematoxylin-Eosin-DAB (HED) to RGB color space conversion. |
| [`skimage.color.hsv2rgb`](#skimage.color.hsv2rgb "skimage.color.hsv2rgb")(hsv) | HSV to RGB color space conversion. |
| [`skimage.color.lab2lch`](#skimage.color.lab2lch "skimage.color.lab2lch")(lab) | CIE-LAB to CIE-LCH color space conversion. |
| [`skimage.color.lab2rgb`](#skimage.color.lab2rgb "skimage.color.lab2rgb")(lab[, illuminant, …]) | Lab to RGB color space conversion. |
| [`skimage.color.lab2xyz`](#skimage.color.lab2xyz "skimage.color.lab2xyz")(lab[, illuminant, …]) | CIE-LAB to XYZcolor space conversion. |
| [`skimage.color.label2rgb`](#skimage.color.label2rgb "skimage.color.label2rgb")(label[, image, …]) | Return an RGB image where color-coded labels are painted over the image. |
| [`skimage.color.lch2lab`](#skimage.color.lch2lab "skimage.color.lch2lab")(lch) | CIE-LCH to CIE-LAB color space conversion. |
| [`skimage.color.rgb2gray`](#skimage.color.rgb2gray "skimage.color.rgb2gray")(rgb) | Compute luminance of an RGB image. |
| [`skimage.color.rgb2grey`](#skimage.color.rgb2grey "skimage.color.rgb2grey")(rgb) | Compute luminance of an RGB image. |
| [`skimage.color.rgb2hed`](#skimage.color.rgb2hed "skimage.color.rgb2hed")(rgb) | RGB to Haematoxylin-Eosin-DAB (HED) color space conversion. |
| [`skimage.color.rgb2hsv`](#skimage.color.rgb2hsv "skimage.color.rgb2hsv")(rgb) | RGB to HSV color space conversion. |
| [`skimage.color.rgb2lab`](#skimage.color.rgb2lab "skimage.color.rgb2lab")(rgb[, illuminant, …]) | Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer. |
| [`skimage.color.rgb2rgbcie`](#skimage.color.rgb2rgbcie "skimage.color.rgb2rgbcie")(rgb) | RGB to RGB CIE color space conversion. |
| [`skimage.color.rgb2xyz`](#skimage.color.rgb2xyz "skimage.color.rgb2xyz")(rgb) | RGB to XYZ color space conversion. |
| [`skimage.color.rgb2ycbcr`](#skimage.color.rgb2ycbcr "skimage.color.rgb2ycbcr")(rgb) | RGB to YCbCr color space conversion. |
| [`skimage.color.rgb2ydbdr`](#skimage.color.rgb2ydbdr "skimage.color.rgb2ydbdr")(rgb) | RGB to YDbDr color space conversion. |
| [`skimage.color.rgb2yiq`](#skimage.color.rgb2yiq "skimage.color.rgb2yiq")(rgb) | RGB to YIQ color space conversion. |
| [`skimage.color.rgb2ypbpr`](#skimage.color.rgb2ypbpr "skimage.color.rgb2ypbpr")(rgb) | RGB to YPbPr color space conversion. |
| [`skimage.color.rgb2yuv`](#skimage.color.rgb2yuv "skimage.color.rgb2yuv")(rgb) | RGB to YUV color space conversion. |
| [`skimage.color.rgba2rgb`](#skimage.color.rgba2rgb "skimage.color.rgba2rgb")(rgba[, background]) | RGBA to RGB conversion using alpha blending [[1]](#rd9bc87eaa392-1). |
| [`skimage.color.rgbcie2rgb`](#skimage.color.rgbcie2rgb "skimage.color.rgbcie2rgb")(rgbcie) | RGB CIE to RGB color space conversion. |
| [`skimage.color.separate_stains`](#skimage.color.separate_stains "skimage.color.separate_stains")(rgb, conv\_matrix) | RGB to stain color space conversion. |
| [`skimage.color.xyz2lab`](#skimage.color.xyz2lab "skimage.color.xyz2lab")(xyz[, illuminant, …]) | XYZ to CIE-LAB color space conversion. |
| [`skimage.color.xyz2rgb`](#skimage.color.xyz2rgb "skimage.color.xyz2rgb")(xyz) | XYZ to RGB color space conversion. |
| [`skimage.color.ycbcr2rgb`](#skimage.color.ycbcr2rgb "skimage.color.ycbcr2rgb")(ycbcr) | YCbCr to RGB color space conversion. |
| [`skimage.color.ydbdr2rgb`](#skimage.color.ydbdr2rgb "skimage.color.ydbdr2rgb")(ydbdr) | YDbDr to RGB color space conversion. |
| [`skimage.color.yiq2rgb`](#skimage.color.yiq2rgb "skimage.color.yiq2rgb")(yiq) | YIQ to RGB color space conversion. |
| [`skimage.color.ypbpr2rgb`](#skimage.color.ypbpr2rgb "skimage.color.ypbpr2rgb")(ypbpr) | YPbPr to RGB color space conversion. |
| [`skimage.color.yuv2rgb`](#skimage.color.yuv2rgb "skimage.color.yuv2rgb")(yuv) | YUV to RGB color space conversion. |

 combine\_stains
---------------

  
`skimage.color.combine_stains(stains, conv_matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1457-L1518)
 
Stain to RGB color space conversion.

  Parameters 
 
`stains(…, 3) array_like` 

The image in stain color space. Final dimension denotes channels.

  **conv\_matrix: ndarray**

The stain separation matrix as described by G. Landini [[1]](#r33a9a7d2e90f-1).

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `stains` is not at least 2-D with shape (…, 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
-------------------

  
`skimage.color.convert_colorspace(arr, fromspace, tospace)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L60-L115)
 
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(…, 3) array_like` 

The image to convert. Final dimension denotes channels.

  
`fromspacestr` 

The color space to convert from. Can be specified in lower case.

  
`tospacestr` 

The color space to convert to. Can be specified in lower case.

    Returns 
 
`out(…, 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
-------------

  
`skimage.color.deltaE_cie76(lab1, lab2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L26-L51)
 
Euclidean distance between two points in Lab color space

  Parameters 
 
`lab1array_like` 

reference color (Lab colorspace)

  
`lab2array_like` 

comparison color (Lab colorspace)

    Returns 
 
`dEarray_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
-----------------

  
`skimage.color.deltaE_ciede2000(lab1, lab2, kL=1, kC=1, kH=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L122-L244)
 
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 
 
`lab1array_like` 

reference color (Lab colorspace)

  
`lab2array_like` 

comparison color (Lab colorspace)

  
`kLfloat (range), optional` 

lightness scale factor, 1 for “acceptably close”; 2 for “imperceptible” see deltaE\_cmc

  
`kCfloat (range), optional` 

chroma scale factor, usually 1

  
`kHfloat (range), optional` 

hue scale factor, usually 1

    Returns 
 
`deltaEarray_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](https://doi.org/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
---------------

  
`skimage.color.deltaE_ciede94(lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L54-L119)
 
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 
 
`lab1array_like` 

reference color (Lab colorspace)

  
`lab2array_like` 

comparison color (Lab colorspace)

  
`kHfloat, optional` 

Hue scale

  
`kCfloat, optional` 

Chroma scale

  
`kLfloat, optional` 

Lightness scale

  
`k1float, optional` 

first scale parameter

  
`k2float, optional` 

second scale parameter

    Returns 
 
`dEarray_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
-----------

  
`skimage.color.deltaE_cmc(lab1, lab2, kL=1, kC=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L247-L308)
 
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 
 
`lab1array_like` 

reference color (Lab colorspace)

  
`lab2array_like` 

comparison color (Lab colorspace)

    Returns 
 
`dEarray_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
--------

  
`skimage.color.gray2rgb(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L834-L896)
 
Create an RGB representation of a gray-level image.

  Parameters 
 
`imagearray_like` 

Input image.

  
`alphabool, optional` 

Ensure that the output image has an alpha layer. If None, alpha layers are passed through but not created.

    Returns 
 
`rgb(…, 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, 3)`.

 
 ### Examples using `skimage.color.gray2rgb`

 
 ![Tinting gray-scale images]

   gray2rgba
---------

  
`skimage.color.gray2rgba(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L797-L831)
 
Create a RGBA representation of a gray-level image.

  Parameters 
 
`imagearray_like` 

Input image.

  
`alphaarray_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.

    Returns 
 
`rgbandarray` 

RGBA image. A new dimension of length 4 is added to input image shape.

     
 grey2rgb
--------

  
`skimage.color.grey2rgb(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L834-L896)
 
Create an RGB representation of a gray-level image.

  Parameters 
 
`imagearray_like` 

Input image.

  
`alphabool, optional` 

Ensure that the output image has an alpha layer. If None, alpha layers are passed through but not created.

    Returns 
 
`rgb(…, 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, 3)`.

 
 hed2rgb
-------

  
`skimage.color.hed2rgb(hed)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1355-L1388)
 
Haematoxylin-Eosin-DAB (HED) to RGB color space conversion.

  Parameters 
 
`hed(…, 3) array_like` 

The image in the HED color space. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB. Same dimensions as input.

    Raises 
 ValueError

If `hed` is not at least 2-D with shape (…, 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
-------

  
`skimage.color.hsv2rgb(hsv)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L272-L324)
 
HSV to RGB color space conversion.

  Parameters 
 
`hsv(…, 3) array_like` 

The image in HSV format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `hsv` is not at least 2-D with shape (…, 3).

     #### Notes

 Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [[1]](#r933d6ba7a3ec-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)

```
 
 ### Examples using `skimage.color.hsv2rgb`

 
 ![Tinting gray-scale images]

  

 ![Flood Fill]

   lab2lch
-------

  
`skimage.color.lab2lch(lab)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1521-L1559)
 
CIE-LAB to CIE-LCH color space conversion.

 LCH is the cylindrical representation of the LAB (Cartesian) colorspace

  Parameters 
 
`lab(…, 3) array_like` 

The N-D image in CIE-LAB format. The last (`N+1`-th) dimension must have at least 3 elements, corresponding to the `L`, `a`, and `b` color channels. Subsequent elements are copied.

    Returns 
 
`out(…, 3) ndarray` 

The image in LCH format, in a N-D array with same shape as input `lab`.

    Raises 
 ValueError

If `lch` does not have at least 3 color channels (i.e. l, a, b).

     #### Notes

 The Hue is expressed as an angle between `(0, 2*pi)`

 #### Examples

 
```
>>> from skimage import data
>>> from skimage.color import rgb2lab, lab2lch
>>> img = data.astronaut()
>>> img_lab = rgb2lab(img)
>>> img_lch = lab2lch(img_lab)

```
 
 lab2rgb
-------

  
`skimage.color.lab2rgb(lab, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1076-L1109)
 
Lab to RGB color space conversion.

  Parameters 
 
`lab(…, 3) array_like` 

The image in Lab format. Final dimension denotes channels.

  
`illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional` 

The name of the illuminant (the function is NOT case sensitive).

  
`observer{“2”, “10”}, optional` 

The aperture angle of the observer.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `lab` is not at least 2-D with shape (…, 3).

     #### Notes

 This function uses lab2xyz and xyz2rgb. By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants.

 #### References

  
`1`  
<https://en.wikipedia.org/wiki/Standard_illuminant>

   
 lab2xyz
-------

  
`skimage.color.lab2xyz(lab, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L972-L1032)
 
CIE-LAB to XYZcolor space conversion.

  Parameters 
 
`lab(…, 3) array_like` 

The image in Lab format. Final dimension denotes channels.

  
`illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional` 

The name of the illuminant (the function is NOT case sensitive).

  
`observer{“2”, “10”}, optional` 

The aperture angle of the observer.

    Returns 
 
`out(…, 3) ndarray` 

The image in XYZ format. Same dimensions as input.

    Raises 
 ValueError

If `lab` is not at least 2-D with shape (…, 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

 By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref = 95.047, y\_ref = 100., z\_ref = 108.883. See function ‘get\_xyz\_coords’ for a list of supported illuminants.

 #### References

  
`1`  
<http://www.easyrgb.com/index.php?X=MATH&H=07>

  
`2`  
<https://en.wikipedia.org/wiki/Lab_color_space>

   
 label2rgb
---------

  
`skimage.color.label2rgb(label, image=None, colors=None, alpha=0.3, bg_label=-1, bg_color=(0, 0, 0), image_alpha=1, kind='overlay')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorlabel.py#L74-L118)
 
Return an RGB image where color-coded labels are painted over the image.

  Parameters 
 
`labelarray, shape (M, N)` 

Integer array of labels with the same shape as `image`.

  
`imagearray, shape (M, N, 3), optional` 

Image used as underlay for labels. If the input is an RGB image, it’s converted to grayscale before coloring.

  
`colorslist, optional` 

List of colors. If the number of labels exceeds the number of colors, then the colors are cycled.

  
`alphafloat [0, 1], optional` 

Opacity of colorized labels. Ignored if image is `None`.

  
`bg_labelint, 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_colorstr or array, optional` 

Background color. Must be a name in `color_dict` or RGB float values between [0, 1].

  
`image_alphafloat [0, 1], optional` 

Opacity of the image.

  
`kindstring, 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.

    Returns 
 
`resultarray of float, shape (M, N, 3)` 

The result of blending a cycling colormap (`colors`) for each distinct value in `label` with the image, at a certain alpha value.

     
 ### Examples using `skimage.color.label2rgb`

 
 ![Segment human cells (in mitosis)]

   lch2lab
-------

  
`skimage.color.lch2lab(lch)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1572-L1607)
 
CIE-LCH to CIE-LAB color space conversion.

 LCH is the cylindrical representation of the LAB (Cartesian) colorspace

  Parameters 
 
`lch(…, 3) array_like` 

The N-D image in CIE-LCH format. The last (`N+1`-th) dimension must have at least 3 elements, corresponding to the `L`, `a`, and `b` color channels. Subsequent elements are copied.

    Returns 
 
`out(…, 3) ndarray` 

The image in LAB format, with same shape as input `lch`.

    Raises 
 ValueError

If `lch` does not have at least 3 color channels (i.e. l, c, h).

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.color import rgb2lab, lch2lab
>>> img = data.astronaut()
>>> img_lab = rgb2lab(img)
>>> img_lch = lab2lch(img_lab)
>>> img_lab2 = lch2lab(img_lch)

```
 
 rgb2gray
--------

  
`skimage.color.rgb2gray(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L729-L787)
 
Compute luminance of an RGB image.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`outndarray` 

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 (…, 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)

```
 
 ### Examples using `skimage.color.rgb2gray`

 
 ![Registration using optical flow]

  

 ![Phase Unwrapping]

   rgb2grey
--------

  
`skimage.color.rgb2grey(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L729-L787)
 
Compute luminance of an RGB image.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`outndarray` 

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 (…, 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
-------

  
`skimage.color.rgb2hed(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1320-L1352)
 
RGB to Haematoxylin-Eosin-DAB (HED) color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in HED format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
-------

  
`skimage.color.rgb2hsv(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L190-L269)
 
RGB to HSV color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in HSV format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 3).

     #### Notes

 Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [[1]](#r80b4a664a365-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)

```
 
 ### Examples using `skimage.color.rgb2hsv`

 
 ![Tinting gray-scale images]

  

 ![Flood Fill]

   rgb2lab
-------

  
`skimage.color.rgb2lab(rgb, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1035-L1073)
 
Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

  
`illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional` 

The name of the illuminant (the function is NOT case sensitive).

  
`observer{“2”, “10”}, optional` 

The aperture angle of the observer.

    Returns 
 
`out(…, 3) ndarray` 

The image in Lab format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants.

 #### References

  
`1`  
<https://en.wikipedia.org/wiki/Standard_illuminant>

   
 rgb2rgbcie
----------

  
`skimage.color.rgb2rgbcie(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L664-L693)
 
RGB to RGB CIE color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB CIE format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
-------

  
`skimage.color.rgb2xyz(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L622-L661)
 
RGB to XYZ color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in XYZ format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
---------

  
`skimage.color.rgb2ycbcr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1699-L1730)
 
RGB to YCbCr color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in YCbCr format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
---------

  
`skimage.color.rgb2ydbdr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1733-L1761)
 
RGB to YDbDr color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in YDbDr format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
-------

  
`skimage.color.rgb2yiq(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1653-L1671)
 
RGB to YIQ color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in YIQ format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 3).

     
 rgb2ypbpr
---------

  
`skimage.color.rgb2ypbpr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1674-L1696)
 
RGB to YPbPr color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in YPbPr format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 3).

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/YPbPr>

   
 rgb2yuv
-------

  
`skimage.color.rgb2yuv(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1623-L1650)
 
RGB to YUV color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in YUV format. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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
--------

  
`skimage.color.rgba2rgb(rgba, background=(1, 1, 1))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L131-L187)
 
RGBA to RGB conversion using alpha blending [[1]](#rd9bc87eaa392-1).

  Parameters 
 
`rgba(…, 4) array_like` 

The image in RGBA format. Final dimension denotes channels.

  
`backgroundarray_like` 

The color of the background to blend the image with (3 floats between 0 to 1 - the RGB value of the background).

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `rgba` is not at least 2-D with shape (…, 4).

     #### References

  
`1(1,2)`  
<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
----------

  
`skimage.color.rgbcie2rgb(rgbcie)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L696-L726)
 
RGB CIE to RGB color space conversion.

  Parameters 
 
`rgbcie(…, 3) array_like` 

The image in RGB CIE format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `rgbcie` is not at least 2-D with shape (…, 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
----------------

  
`skimage.color.separate_stains(rgb, conv_matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1391-L1454)
 
RGB to stain color space conversion.

  Parameters 
 
`rgb(…, 3) array_like` 

The image in RGB format. Final dimension denotes channels.

  **conv\_matrix: ndarray**

The stain separation matrix as described by G. Landini [[1]](#re5603a4e7517-1).

    Returns 
 
`out(…, 3) ndarray` 

The image in stain color space. Same dimensions as input.

    Raises 
 ValueError

If `rgb` is not at least 2-D with shape (…, 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]](#re5603a4e7517-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
-------

  
`skimage.color.xyz2lab(xyz, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L906-L969)
 
XYZ to CIE-LAB color space conversion.

  Parameters 
 
`xyz(…, 3) array_like` 

The image in XYZ format. Final dimension denotes channels.

  
`illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional` 

The name of the illuminant (the function is NOT case sensitive).

  
`observer{“2”, “10”}, optional` 

The aperture angle of the observer.

    Returns 
 
`out(…, 3) ndarray` 

The image in CIE-LAB format. Same dimensions as input.

    Raises 
 ValueError

If `xyz` is not at least 2-D with shape (…, 3).

  ValueError

If either the illuminant or the observer angle is unsupported or unknown.

     #### Notes

 By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants.

 #### References

  
`1`  
<http://www.easyrgb.com/index.php?X=MATH&H=07>

  
`2`  
<https://en.wikipedia.org/wiki/Lab_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)

```
 
 xyz2rgb
-------

  
`skimage.color.xyz2rgb(xyz)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L577-L619)
 
XYZ to RGB color space conversion.

  Parameters 
 
`xyz(…, 3) array_like` 

The image in XYZ format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `xyz` is not at least 2-D with shape (…, 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)

```
 
 ycbcr2rgb
---------

  
`skimage.color.ycbcr2rgb(ycbcr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1835-L1866)
 
YCbCr to RGB color space conversion.

  Parameters 
 
`ycbcr(…, 3) array_like` 

The image in YCbCr format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `ycbcr` is not at least 2-D with shape (…, 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
---------

  
`skimage.color.ydbdr2rgb(ydbdr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1869-L1896)
 
YDbDr to RGB color space conversion.

  Parameters 
 
`ydbdr(…, 3) array_like` 

The image in YDbDr format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `ydbdr` is not at least 2-D with shape (…, 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
-------

  
`skimage.color.yiq2rgb(yiq)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1789-L1807)
 
YIQ to RGB color space conversion.

  Parameters 
 
`yiq(…, 3) array_like` 

The image in YIQ format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `yiq` is not at least 2-D with shape (…, 3).

     
 ypbpr2rgb
---------

  
`skimage.color.ypbpr2rgb(ypbpr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1810-L1832)
 
YPbPr to RGB color space conversion.

  Parameters 
 
`ypbpr(…, 3) array_like` 

The image in YPbPr format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `ypbpr` is not at least 2-D with shape (…, 3).

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/YPbPr>

   
 yuv2rgb
-------

  
`skimage.color.yuv2rgb(yuv)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1764-L1786)
 
YUV to RGB color space conversion.

  Parameters 
 
`yuv(…, 3) array_like` 

The image in YUV format. Final dimension denotes channels.

    Returns 
 
`out(…, 3) ndarray` 

The image in RGB format. Same dimensions as input.

    Raises 
 ValueError

If `yuv` is not at least 2-D with shape (…, 3).

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/YUV>

   


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.color.html>

Module: draw
============

 

|  |  |
| --- | --- |
| [`skimage.draw.bezier_curve`](#skimage.draw.bezier_curve "skimage.draw.bezier_curve")(r0, c0, r1, c1, …) | Generate Bezier curve coordinates. |
| [`skimage.draw.circle`](#skimage.draw.circle "skimage.draw.circle")(r, c, radius[, shape]) | Generate coordinates of pixels within circle. |
| [`skimage.draw.circle_perimeter`](#skimage.draw.circle_perimeter "skimage.draw.circle_perimeter")(r, c, radius) | Generate circle perimeter coordinates. |
| [`skimage.draw.circle_perimeter_aa`](#skimage.draw.circle_perimeter_aa "skimage.draw.circle_perimeter_aa")(r, c, radius) | Generate anti-aliased circle perimeter coordinates. |
| [`skimage.draw.disk`](#skimage.draw.disk "skimage.draw.disk")(center, radius, \*[, shape]) | Generate coordinates of pixels within circle. |
| [`skimage.draw.ellipse`](#skimage.draw.ellipse "skimage.draw.ellipse")(r, c, r\_radius, c\_radius) | Generate coordinates of pixels within ellipse. |
| [`skimage.draw.ellipse_perimeter`](#skimage.draw.ellipse_perimeter "skimage.draw.ellipse_perimeter")(r, c, …[, …]) | Generate ellipse perimeter coordinates. |
| [`skimage.draw.ellipsoid`](#skimage.draw.ellipsoid "skimage.draw.ellipsoid")(a, b, c[, spacing, …]) | Generates ellipsoid with semimajor axes aligned with grid dimensions on grid with specified `spacing`. |
| [`skimage.draw.ellipsoid_stats`](#skimage.draw.ellipsoid_stats "skimage.draw.ellipsoid_stats")(a, b, c) | Calculates analytical surface area and volume for ellipsoid with semimajor axes aligned with grid dimensions of specified `spacing`. |
| [`skimage.draw.line`](#skimage.draw.line "skimage.draw.line")(r0, c0, r1, c1) | Generate line pixel coordinates. |
| [`skimage.draw.line_aa`](#skimage.draw.line_aa "skimage.draw.line_aa")(r0, c0, r1, c1) | Generate anti-aliased line pixel coordinates. |
| [`skimage.draw.line_nd`](#skimage.draw.line_nd "skimage.draw.line_nd")(start, stop, \*[, …]) | Draw a single-pixel thick line in n dimensions. |
| [`skimage.draw.polygon`](#skimage.draw.polygon "skimage.draw.polygon")(r, c[, shape]) | Generate coordinates of pixels within polygon. |
| [`skimage.draw.polygon2mask`](#skimage.draw.polygon2mask "skimage.draw.polygon2mask")(image\_shape, polygon) | Compute a mask from polygon. |
| [`skimage.draw.polygon_perimeter`](#skimage.draw.polygon_perimeter "skimage.draw.polygon_perimeter")(r, c[, …]) | Generate polygon perimeter coordinates. |
| [`skimage.draw.random_shapes`](#skimage.draw.random_shapes "skimage.draw.random_shapes")(image\_shape, …) | Generate an image with random shapes, labeled with bounding boxes. |
| [`skimage.draw.rectangle`](#skimage.draw.rectangle "skimage.draw.rectangle")(start[, end, extent, …]) | Generate coordinates of pixels within a rectangle. |
| [`skimage.draw.rectangle_perimeter`](#skimage.draw.rectangle_perimeter "skimage.draw.rectangle_perimeter")(start[, …]) | Generate coordinates of pixels that are exactly around a rectangle. |
| [`skimage.draw.set_color`](#skimage.draw.set_color "skimage.draw.set_color")(image, coords, color) | Set pixel color in the image at the given coordinates. |

 bezier\_curve
-------------

  
`skimage.draw.bezier_curve(r0, c0, r1, c1, r2, c2, weight, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L697-L751)
 
Generate Bezier curve coordinates.

  Parameters 
 
`r0, c0int` 

Coordinates of the first control point.

  
`r1, c1int` 

Coordinates of the middle control point.

  
`r2, c2int` 

Coordinates of the last control point.

  
`weightdouble` 

Middle control point weight, it describes the line tension.

  
`shapetuple, 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]](#r275489368e51-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
------

  
`skimage.draw.circle(r, c, radius, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L146-L180)
 
Generate coordinates of pixels within circle.

  Parameters 
 
`r, cdouble` 

Center coordinate of disk.

  
`radiusdouble` 

Radius of disk.

  
`shapetuple, optional` 

Image shape which is used to determine 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. Must be at least length 2. Only the first two values are used to determine the extent of the input image.

    Returns 
 
`rr, ccndarray of int` 

Pixel coordinates of disk. May be used to directly index into an array, e.g. `img[rr, cc] = 1`.

    Warns 
 Deprecated:

 New in version 0.17: This function is deprecated and will be removed in scikit-image 0.19. Please use the function named `disk` instead.

      
 circle\_perimeter
-----------------

  
`skimage.draw.circle_perimeter(r, c, radius, method='bresenham', shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L502-L562)
 
Generate circle perimeter coordinates.

  Parameters 
 
`r, cint` 

Centre coordinate of circle.

  
`radiusint` 

Radius of circle.

  
`method{‘bresenham’, ‘andres’}, optional` 

bresenham : Bresenham method (default) andres : Andres method

  
`shapetuple, 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`](#skimage.draw.circle_perimeter_aa "skimage.draw.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
---------------------

  
`skimage.draw.circle_perimeter_aa(r, c, radius, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L565-L623)
 
Generate anti-aliased circle perimeter coordinates.

  Parameters 
 
`r, cint` 

Centre coordinate of circle.

  
`radiusint` 

Radius of circle.

  
`shapetuple, 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
----

  
`skimage.draw.disk(center, radius, *, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L183-L225)
 
Generate coordinates of pixels within circle.

  Parameters 
 
`centertuple` 

Center coordinate of disk.

  
`radiusdouble` 

Radius of disk.

  
`shapetuple, optional` 

Image shape which is used to determine 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. Must be at least length 2. Only the first two values are used to determine the extent of the input image.

    Returns 
 
`rr, ccndarray of int` 

Pixel coordinates of disk. May be used to directly index into an array, e.g. `img[rr, cc] = 1`.

     #### Examples

 
```
>>> from skimage.draw import disk
>>> 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
-------

  
`skimage.draw.ellipse(r, c, r_radius, c_radius, shape=None, rotation=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L46-L143)
 
Generate coordinates of pixels within ellipse.

  Parameters 
 
`r, cdouble` 

Centre coordinate of ellipse.

  
`r_radius, c_radiusdouble` 

Minor and major semi-axes. `(r/r_radius)**2 + (c/c_radius)**2 = 1`.

  
`shapetuple, 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.

  
`rotationfloat, 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, ccndarray of int` 

Pixel coordinates of ellipse. May be used to directly index into an array, e.g. `img[rr, cc] = 1`.

     #### 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`](#skimage.draw.ellipse "skimage.draw.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)

```
 #### 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)

```
 
 ### Examples using `skimage.draw.ellipse`

 
 ![Masked Normalized Cross-Correlation]

  

 ![Measure region properties]

   ellipse\_perimeter
------------------

  
`skimage.draw.ellipse_perimeter(r, c, r_radius, c_radius, orientation=0, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L626-L694)
 
Generate ellipse perimeter coordinates.

  Parameters 
 
`r, cint` 

Centre coordinate of ellipse.

  
`r_radius, c_radiusint` 

Minor and major semi-axes. `(r/r_radius)**2 + (c/c_radius)**2 = 1`.

  
`orientationdouble, optional` 

Major axis orientation in clockwise direction as radians.

  
`shapetuple, 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`](#skimage.draw.ellipse "skimage.draw.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
---------

  
`skimage.draw.ellipsoid(a, b, c, spacing=(1.0, 1.0, 1.0), levelset=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw3d.py#L5-L63)
 
Generates ellipsoid with semimajor axes aligned with grid dimensions on grid with specified `spacing`.

  Parameters 
 
`afloat` 

Length of semimajor axis aligned with x-axis.

  
`bfloat` 

Length of semimajor axis aligned with y-axis.

  
`cfloat` 

Length of semimajor axis aligned with z-axis.

  
`spacingtuple of floats, length 3` 

Spacing in (x, y, z) spatial dimensions.

  
`levelsetbool` 

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 
 
`ellip(N, M, 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
----------------

  
`skimage.draw.ellipsoid_stats(a, b, c)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw3d.py#L66-L114)
 
Calculates analytical surface area and volume for ellipsoid with semimajor axes aligned with grid dimensions of specified `spacing`.

  Parameters 
 
`afloat` 

Length of semimajor axis aligned with x-axis.

  
`bfloat` 

Length of semimajor axis aligned with y-axis.

  
`cfloat` 

Length of semimajor axis aligned with z-axis.

    Returns 
 
`volfloat` 

Calculated volume of ellipsoid.

  
`surffloat` 

Calculated surface area of ellipsoid.

     
 line
----

  
`skimage.draw.line(r0, c0, r1, c1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L371-L410)
 
Generate line pixel coordinates.

  Parameters 
 
`r0, c0int` 

Starting position (row, column).

  
`r1, c1int` 

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`](#skimage.draw.line_aa "skimage.draw.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
--------

  
`skimage.draw.line_aa(r0, c0, r1, c1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L413-L452)
 
Generate anti-aliased line pixel coordinates.

  Parameters 
 
`r0, c0int` 

Starting position (row, column).

  
`r1, c1int` 

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
--------

  
`skimage.draw.line_nd(start, stop, *, endpoint=False, integer=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw_nd.py#L54-L108)
 
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 neighbours in n dimensions.

  Parameters 
 
`startarray-like, shape (N,)` 

The start coordinates of the line.

  
`stoparray-like, shape (N,)` 

The end coordinates of the line.

  
`endpointbool, optional` 

Whether to include the endpoint in the returned line. Defaults to False, which allows for easy drawing of multi-point paths.

  
`integerbool, 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 
 
`coordstuple 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
-------

  
`skimage.draw.polygon(r, c, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L455-L499)
 
Generate coordinates of pixels within polygon.

  Parameters 
 
`r(N,) ndarray` 

Row coordinates of vertices of polygon.

  
`c(N,) ndarray` 

Column coordinates of vertices of polygon.

  
`shapetuple, 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, ccndarray of int` 

Pixel coordinates of polygon. May be used to directly index into an array, e.g. `img[rr, cc] = 1`.

     #### Examples

 
```
>>> from skimage.draw import polygon
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> r = np.array([1, 2, 8])
>>> c = np.array([1, 7, 4])
>>> rr, cc = polygon(r, c)
>>> 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]], dtype=uint8)

```
 
 polygon2mask
------------

  
`skimage.draw.polygon2mask(image_shape, polygon)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/_polygon2mask.py#L6-L41)
 
Compute a mask from polygon.

  Parameters 
 
`image_shapetuple of size 2.` 

The shape of the mask.

  
`polygonarray_like.` 

The polygon coordinates of shape (N, 2) where N is the number of points.

    Returns 
 
`mask2-D ndarray of type ‘bool’.` 

The mask that corresponds to the input polygon.

     #### Notes

 This function does not do any border checking, so that all the vertices need to be within the given shape.

 #### Examples

 
```
>>> image_shape = (128, 128)
>>> polygon = np.array([[60, 100], [100, 40], [40, 40]])
>>> mask = polygon2mask(image_shape, polygon)
>>> mask.shape
(128, 128)

```
 
 polygon\_perimeter
------------------

  
`skimage.draw.polygon_perimeter(r, c, shape=None, clip=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L228-L304)
 
Generate polygon perimeter coordinates.

  Parameters 
 
`r(N,) ndarray` 

Row coordinates of vertices of polygon.

  
`c(N,) ndarray` 

Column coordinates of vertices of polygon.

  
`shapetuple, 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.

  
`clipbool, 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, ccndarray of int` 

Pixel coordinates of polygon. May be used to directly index into an array, e.g. `img[rr, cc] = 1`.

     #### Examples

 
```
>>> from skimage.draw import polygon_perimeter
>>> img = np.zeros((10, 10), dtype=np.uint8)
>>> rr, cc = polygon_perimeter([5, -1, 5, 10],
...                            [-1, 5, 11, 5],
...                            shape=img.shape, clip=True)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 1, 1, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)

```
 
 random\_shapes
--------------

  
`skimage.draw.random_shapes(image_shape, max_shapes, min_shapes=1, min_size=2, max_size=None, multichannel=True, num_channels=3, shape=None, intensity_range=None, allow_overlap=False, num_trials=100, random_seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/_random_shapes.py#L293-L437)
 
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_shapetuple` 

The number of rows and columns of the image to generate.

  
`max_shapesint` 

The maximum number of shapes to (attempt to) fit into the shape.

  
`min_shapesint, optional` 

The minimum number of shapes to (attempt to) fit into the shape.

  
`min_sizeint, optional` 

The minimum dimension of each shape to fit into the image.

  
`max_sizeint, optional` 

The maximum dimension of each shape to fit into the image.

  
`multichannelbool, optional` 

If True, the generated image has `num_channels` color channels, otherwise generates grayscale image.

  
`num_channelsint, 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_overlapbool, optional` 

If `True`, allow shapes to overlap.

  
`num_trialsint, optional` 

How often to attempt to fit a shape into the image before skipping it.

  
`random_seedint, optional` 

Seed to initialize the random number generator. If `None`, a random seed from the operating system is used.

    Returns 
 
`imageuint8 array` 

An image with the fitted shapes.

  
`labelslist` 

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 
array([
   [[255, 255, 255],
    [255, 255, 255],
    [255, 255, 255],
    ...,
    [255, 255, 255],
    [255, 255, 255],
    [255, 255, 255]]], dtype=uint8)
>>> labels 
[('circle', ((22, 18), (25, 21))),
 ('triangle', ((5, 6), (13, 13)))]

```
 
 rectangle
---------

  
`skimage.draw.rectangle(start, end=None, extent=None, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L754-L847)
 
Generate coordinates of pixels within a rectangle.

  Parameters 
 
`starttuple` 

Origin point of the rectangle, e.g., `([plane,] row, column)`.

  
`endtuple` 

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.

  
`extenttuple` 

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.

  
`shapetuple, 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 
 
`coordsarray 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
--------------------

  
`skimage.draw.rectangle_perimeter(start, end=None, extent=None, shape=None, clip=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L850-L920)
 
Generate coordinates of pixels that are exactly around a rectangle.

  Parameters 
 
`starttuple` 

Origin point of the inner rectangle, e.g., `(row, column)`.

  
`endtuple` 

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.

  
`extenttuple` 

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`](#skimage.draw.rectangle "skimage.draw.rectangle") to better understand how they behave.

  
`shapetuple, 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.

  
`clipbool, 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 
 
`coordsarray of int, shape (2, Npoints)` 

The coordinates of all pixels in the rectangle.

     #### Examples

 
```
>>> import numpy as np
>>> from skimage.draw import rectangle_perimeter
>>> img = np.zeros((5, 6), dtype=np.uint8)
>>> start = (2, 3)
>>> end = (3, 4)
>>> rr, cc = rectangle_perimeter(start, end=end, shape=img.shape)
>>> img[rr, cc] = 1
>>> img
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1],
       [0, 0, 1, 0, 0, 1],
       [0, 0, 1, 0, 0, 1],
       [0, 0, 1, 1, 1, 1]], dtype=uint8)

```
 
```
>>> img = np.zeros((5, 5), dtype=np.uint8)
>>> r, c = rectangle_perimeter(start, (10, 10), shape=img.shape, clip=True)
>>> img[r, c] = 1
>>> img
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1],
       [0, 0, 1, 0, 1],
       [0, 0, 1, 0, 1],
       [0, 0, 1, 1, 1]], dtype=uint8)

```
 
 set\_color
----------

  
`skimage.draw.set_color(image, coords, color, alpha=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L307-L368)
 
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, D) ndarray` 

Image

  
`coordstuple of ((P,) ndarray, (P,) ndarray)` 

Row and column coordinates of pixels to be colored.

  
`color(D,) ndarray` 

Color to be assigned to coordinates in the image.

  
`alphascalar or (N,) 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)

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.draw.html>

Module: exposure
================

 

|  |  |
| --- | --- |
| [`skimage.exposure.adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma")(image[, …]) | Performs Gamma Correction on the input image. |
| [`skimage.exposure.adjust_log`](#skimage.exposure.adjust_log "skimage.exposure.adjust_log")(image[, gain, inv]) | Performs Logarithmic correction on the input image. |
| [`skimage.exposure.adjust_sigmoid`](#skimage.exposure.adjust_sigmoid "skimage.exposure.adjust_sigmoid")(image[, …]) | Performs Sigmoid Correction on the input image. |
| [`skimage.exposure.cumulative_distribution`](#skimage.exposure.cumulative_distribution "skimage.exposure.cumulative_distribution")(image) | Return cumulative distribution function (cdf) for the given image. |
| [`skimage.exposure.equalize_adapthist`](#skimage.exposure.equalize_adapthist "skimage.exposure.equalize_adapthist")(image[, …]) | Contrast Limited Adaptive Histogram Equalization (CLAHE). |
| [`skimage.exposure.equalize_hist`](#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist")(image[, …]) | Return image after histogram equalization. |
| [`skimage.exposure.histogram`](#skimage.exposure.histogram "skimage.exposure.histogram")(image[, nbins, …]) | Return histogram of image. |
| [`skimage.exposure.is_low_contrast`](#skimage.exposure.is_low_contrast "skimage.exposure.is_low_contrast")(image[, …]) | Determine if an image is low contrast. |
| [`skimage.exposure.match_histograms`](#skimage.exposure.match_histograms "skimage.exposure.match_histograms")(image, …) | Adjust an image so that its cumulative histogram matches that of another. |
| [`skimage.exposure.rescale_intensity`](#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity")(image[, …]) | Return image after stretching or shrinking its intensity levels. |

 adjust\_gamma
-------------

  
`skimage.exposure.adjust_gamma(image, gamma=1, gain=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L447-L508)
 
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 
 
`imagendarray` 

Input image.

  
`gammafloat, optional` 

Non negative real number. Default value is 1.

  
`gainfloat, optional` 

The constant multiplier. Default value is 1.

    Returns 
 
`outndarray` 

Gamma corrected output image.

      See also

  
[`adjust_log`](#skimage.exposure.adjust_log "skimage.exposure.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

```
 
 ### Examples using `skimage.exposure.adjust_gamma`

 
 ![Explore 3D images (of cells)]

   adjust\_log
-----------

  
`skimage.exposure.adjust_log(image, gain=1, inv=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L511-L551)
 
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 
 
`imagendarray` 

Input image.

  
`gainfloat, optional` 

The constant multiplier. Default value is 1.

  
`invfloat, optional` 

If True, it performs inverse logarithmic correction, else correction will be logarithmic. Defaults to False.

    Returns 
 
`outndarray` 

Logarithm corrected output image.

      See also

  
[`adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma")

  #### References

  
`1`  
<http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf>

   
 adjust\_sigmoid
---------------

  
`skimage.exposure.adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L554-L600)
 
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 
 
`imagendarray` 

Input image.

  
`cutofffloat, optional` 

Cutoff of the sigmoid function that shifts the characteristic curve in horizontal direction. Default value is 0.5.

  
`gainfloat, optional` 

The constant multiplier in exponential’s power of sigmoid function. Default value is 10.

  
`invbool, optional` 

If True, returns the negative sigmoid correction. Defaults to False.

    Returns 
 
`outndarray` 

Sigmoid corrected output image.

      See also

  
[`adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma")

  #### References

  
`1`  
Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”, <http://www.cis.rit.edu/fairchild/PDFs/PAP07.pdf>

   
 cumulative\_distribution
------------------------

  
`skimage.exposure.cumulative_distribution(image, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L147-L184)
 
Return cumulative distribution function (cdf) for the given image.

  Parameters 
 
`imagearray` 

Image array.

  
`nbinsint, optional` 

Number of bins for image histogram.

    Returns 
 
`img_cdfarray` 

Values of cumulative distribution function.

  
`bin_centersarray` 

Centers of bins.

      See also

  
[`histogram`](#skimage.exposure.histogram "skimage.exposure.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)
>>> np.alltrue(cdf[0] == np.cumsum(hi[0])/float(image.size))
True

```
 
 ### Examples using `skimage.exposure.cumulative_distribution`

 
 ![Local Histogram Equalization]

  

 ![Explore 3D images (of cells)]

   equalize\_adapthist
-------------------

  
`skimage.exposure.equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/_adapthist.py#L26-L95)
 
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(N1, …,NN[, 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_limitfloat, optional` 

Clipping limit, normalized between 0 and 1 (higher values give more contrast).

  
`nbinsint, optional` 

Number of gray bins for histogram (“data range”).

    Returns 
 
`out(N1, …,NN[, C]) ndarray` 

Equalized image with float64 dtype.

      See also

  
`equalize_hist,` [`rescale_intensity`](#skimage.exposure.rescale_intensity "skimage.exposure.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.

  Changed in version 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>

   
 ### Examples using `skimage.exposure.equalize_adapthist`

 
 ![3D adaptive histogram equalization]

   equalize\_hist
--------------

  
`skimage.exposure.equalize_hist(image, nbins=256, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L187-L223)
 
Return image after histogram equalization.

  Parameters 
 
`imagearray` 

Image array.

  
`nbinsint, 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 
 
`outfloat array` 

Image array after histogram equalization.

     #### Notes

 This function is adapted from [[1]](#rda90ab4dd09a-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>

   
 ### Examples using `skimage.exposure.equalize_hist`

 
 ![Local Histogram Equalization]

  

 ![3D adaptive histogram equalization]

  

 ![Explore 3D images (of cells)]

  

 ![Rank filters]

   histogram
---------

  
`skimage.exposure.histogram(image, nbins=256, source_range='image', normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L77-L144)
 
Return histogram of image.

 Unlike [`numpy.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.19)"), 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.

 The histogram is computed on the flattened image: for color images, the function should be used separately on each channel to obtain a histogram for each color channel.

  Parameters 
 
`imagearray` 

Input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

  
`source_rangestring, 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.

  
`normalizebool, optional` 

If True, normalize the histogram by the sum of its values.

    Returns 
 
`histarray` 

The values of the histogram.

  
`bin_centersarray` 

The values at the center of the bins.

      See also

  
[`cumulative_distribution`](#skimage.exposure.cumulative_distribution "skimage.exposure.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]))

```
 
 ### Examples using `skimage.exposure.histogram`

 
 ![Rank filters]

   is\_low\_contrast
-----------------

  
`skimage.exposure.is_low_contrast(image, fraction_threshold=0.05, lower_percentile=1, upper_percentile=99, method='linear')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L603-L654)
 
Determine if an image is low contrast.

  Parameters 
 
`imagearray-like` 

The image under test.

  
`fraction_thresholdfloat, 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]](#re0c68370bb9d-1)

  
`lower_percentilefloat, optional` 

Disregard values below this percentile when computing image contrast.

  
`upper_percentilefloat, optional` 

Disregard values above this percentile when computing image contrast.

  
`methodstr, optional` 

The contrast determination method. Right now the only available option is “linear”.

    Returns 
 
`outbool` 

True when the image is determined to be low contrast.

     #### 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
-----------------

  
`skimage.exposure.match_histograms(image, reference, *, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/histogram_matching.py#L22-L70)
 
Adjust an image so that its cumulative histogram matches that of another.

 The adjustment is applied separately for each channel.

  Parameters 
 
`imagendarray` 

Input image. Can be gray-scale or in color.

  
`referencendarray` 

Image to match histogram of. Must have the same number of channels as image.

  
`multichannelbool, optional` 

Apply the matching separately for each channel.

    Returns 
 
`matchedndarray` 

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
------------------

  
`skimage.exposure.rescale_intensity(image, in_range='image', out_range='dtype')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L313-L428)
 
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 
 
`imagearray` 

Image array.

  
`in_range, out_rangestr 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 
 
`outarray` 

Image array after rescaling its intensity. This image is the same dtype as the input image.

      See also

  
[`equalize_hist`](#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist")

  #### Notes

  Changed in version 0.17: The dtype of the output array has changed to match the output dtype, or float if the output range is specified by a pair of floats.

  #### 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`](#skimage.exposure.rescale_intensity "skimage.exposure.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)

 
 ### Examples using `skimage.exposure.rescale_intensity`

 
 ![Phase Unwrapping]

  

 ![Explore 3D images (of cells)]

  

 ![Rank filters]

  

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.exposure.html>

Module: filters
===============

 

|  |  |
| --- | --- |
| [`skimage.filters.apply_hysteresis_threshold`](#skimage.filters.apply_hysteresis_threshold "skimage.filters.apply_hysteresis_threshold")(…) | Apply hysteresis thresholding to `image`. |
| [`skimage.filters.correlate_sparse`](#skimage.filters.correlate_sparse "skimage.filters.correlate_sparse")(image, kernel) | Compute valid cross-correlation of `padded_array` and `kernel`. |
| [`skimage.filters.difference_of_gaussians`](#skimage.filters.difference_of_gaussians "skimage.filters.difference_of_gaussians")(…) | Find features between `low_sigma` and `high_sigma` in size. |
| [`skimage.filters.farid`](#skimage.filters.farid "skimage.filters.farid")(image, \*[, mask]) | Find the edge magnitude using the Farid transform. |
| [`skimage.filters.farid_h`](#skimage.filters.farid_h "skimage.filters.farid_h")(image, \*[, mask]) | Find the horizontal edges of an image using the Farid transform. |
| [`skimage.filters.farid_v`](#skimage.filters.farid_v "skimage.filters.farid_v")(image, \*[, mask]) | Find the vertical edges of an image using the Farid transform. |
| [`skimage.filters.frangi`](#skimage.filters.frangi "skimage.filters.frangi")(image[, sigmas, …]) | Filter an image with the Frangi vesselness filter. |
| [`skimage.filters.gabor`](#skimage.filters.gabor "skimage.filters.gabor")(image, frequency[, …]) | Return real and imaginary responses to Gabor filter. |
| [`skimage.filters.gabor_kernel`](#skimage.filters.gabor_kernel "skimage.filters.gabor_kernel")(frequency[, …]) | Return complex 2D Gabor filter kernel. |
| [`skimage.filters.gaussian`](#skimage.filters.gaussian "skimage.filters.gaussian")(image[, sigma, …]) | Multi-dimensional Gaussian filter. |
| [`skimage.filters.hessian`](#skimage.filters.hessian "skimage.filters.hessian")(image[, sigmas, …]) | Filter an image with the Hybrid Hessian filter. |
| [`skimage.filters.inverse`](#skimage.filters.inverse "skimage.filters.inverse")(data[, …]) | Apply the filter in reverse to the given data. |
| [`skimage.filters.laplace`](#skimage.filters.laplace "skimage.filters.laplace")(image[, ksize, mask]) | Find the edges of an image using the Laplace operator. |
| [`skimage.filters.median`](#skimage.filters.median "skimage.filters.median")(image[, selem, out, …]) | Return local median of an image. |
| [`skimage.filters.meijering`](#skimage.filters.meijering "skimage.filters.meijering")(image[, sigmas, …]) | Filter an image with the Meijering neuriteness filter. |
| [`skimage.filters.prewitt`](#skimage.filters.prewitt "skimage.filters.prewitt")(image[, mask, axis, …]) | Find the edge magnitude using the Prewitt transform. |
| [`skimage.filters.prewitt_h`](#skimage.filters.prewitt_h "skimage.filters.prewitt_h")(image[, mask]) | Find the horizontal edges of an image using the Prewitt transform. |
| [`skimage.filters.prewitt_v`](#skimage.filters.prewitt_v "skimage.filters.prewitt_v")(image[, mask]) | Find the vertical edges of an image using the Prewitt transform. |
| [`skimage.filters.rank_order`](#skimage.filters.rank_order "skimage.filters.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. |
| [`skimage.filters.roberts`](#skimage.filters.roberts "skimage.filters.roberts")(image[, mask]) | Find the edge magnitude using Roberts’ cross operator. |
| [`skimage.filters.roberts_neg_diag`](#skimage.filters.roberts_neg_diag "skimage.filters.roberts_neg_diag")(image[, mask]) | Find the cross edges of an image using the Roberts’ Cross operator. |
| [`skimage.filters.roberts_pos_diag`](#skimage.filters.roberts_pos_diag "skimage.filters.roberts_pos_diag")(image[, mask]) | Find the cross edges of an image using Roberts’ cross operator. |
| [`skimage.filters.sato`](#skimage.filters.sato "skimage.filters.sato")(image[, sigmas, …]) | Filter an image with the Sato tubeness filter. |
| [`skimage.filters.scharr`](#skimage.filters.scharr "skimage.filters.scharr")(image[, mask, axis, …]) | Find the edge magnitude using the Scharr transform. |
| [`skimage.filters.scharr_h`](#skimage.filters.scharr_h "skimage.filters.scharr_h")(image[, mask]) | Find the horizontal edges of an image using the Scharr transform. |
| [`skimage.filters.scharr_v`](#skimage.filters.scharr_v "skimage.filters.scharr_v")(image[, mask]) | Find the vertical edges of an image using the Scharr transform. |
| [`skimage.filters.sobel`](#skimage.filters.sobel "skimage.filters.sobel")(image[, mask, axis, …]) | Find edges in an image using the Sobel filter. |
| [`skimage.filters.sobel_h`](#skimage.filters.sobel_h "skimage.filters.sobel_h")(image[, mask]) | Find the horizontal edges of an image using the Sobel transform. |
| [`skimage.filters.sobel_v`](#skimage.filters.sobel_v "skimage.filters.sobel_v")(image[, mask]) | Find the vertical edges of an image using the Sobel transform. |
| [`skimage.filters.threshold_isodata`](#skimage.filters.threshold_isodata "skimage.filters.threshold_isodata")([image, …]) | Return threshold value(s) based on ISODATA method. |
| [`skimage.filters.threshold_li`](#skimage.filters.threshold_li "skimage.filters.threshold_li")(image, \*[, …]) | Compute threshold value by Li’s iterative Minimum Cross Entropy method. |
| [`skimage.filters.threshold_local`](#skimage.filters.threshold_local "skimage.filters.threshold_local")(image, …) | Compute a threshold mask image based on local pixel neighborhood. |
| [`skimage.filters.threshold_mean`](#skimage.filters.threshold_mean "skimage.filters.threshold_mean")(image) | Return threshold value based on the mean of grayscale values. |
| [`skimage.filters.threshold_minimum`](#skimage.filters.threshold_minimum "skimage.filters.threshold_minimum")([image, …]) | Return threshold value based on minimum method. |
| [`skimage.filters.threshold_multiotsu`](#skimage.filters.threshold_multiotsu "skimage.filters.threshold_multiotsu")(image[, …]) | Generate `classes`-1 threshold values to divide gray levels in `image`. |
| [`skimage.filters.threshold_niblack`](#skimage.filters.threshold_niblack "skimage.filters.threshold_niblack")(image[, …]) | Applies Niblack local threshold to an array. |
| [`skimage.filters.threshold_otsu`](#skimage.filters.threshold_otsu "skimage.filters.threshold_otsu")([image, …]) | Return threshold value based on Otsu’s method. |
| [`skimage.filters.threshold_sauvola`](#skimage.filters.threshold_sauvola "skimage.filters.threshold_sauvola")(image[, …]) | Applies Sauvola local threshold to an array. |
| [`skimage.filters.threshold_triangle`](#skimage.filters.threshold_triangle "skimage.filters.threshold_triangle")(image[, …]) | Return threshold value based on the triangle algorithm. |
| [`skimage.filters.threshold_yen`](#skimage.filters.threshold_yen "skimage.filters.threshold_yen")([image, …]) | Return threshold value based on Yen’s method. |
| [`skimage.filters.try_all_threshold`](#skimage.filters.try_all_threshold "skimage.filters.try_all_threshold")(image[, …]) | Returns a figure comparing the outputs of different thresholding methods. |
| [`skimage.filters.unsharp_mask`](#skimage.filters.unsharp_mask "skimage.filters.unsharp_mask")(image[, …]) | Unsharp masking filter. |
| [`skimage.filters.wiener`](#skimage.filters.wiener "skimage.filters.wiener")(data[, …]) | Minimum Mean Square Error (Wiener) inverse filter. |
| [`skimage.filters.window`](#skimage.filters.window "skimage.filters.window")(window\_type, shape[, …]) | Return an n-dimensional window of a given size and dimensionality. |
| [`skimage.filters.LPIFilter2D`](#skimage.filters.LPIFilter2D "skimage.filters.LPIFilter2D")(…) | Linear Position-Invariant Filter (2-dimensional) |
| [`skimage.filters.rank`](skimage.filters.rank#module-skimage.filters.rank "skimage.filters.rank") |  |

 apply\_hysteresis\_threshold
----------------------------

  
`skimage.filters.apply_hysteresis_threshold(image, low, high)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1090-L1134)
 
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 
 
`imagearray, shape (M,[ N, …, P])` 

Grayscale input image.

  
`lowfloat, or array of same shape as image` 

Lower threshold.

  
`highfloat, or array of same shape as image` 

Higher threshold.

    Returns 
 
`thresholdedarray of bool, same shape as image` 

Array in which `True` indicates the locations where `image` was above the hysteresis threshold.

     #### 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](https://doi.org/10.1109/TPAMI.1986.4767851)

   #### 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])

```
 
 correlate\_sparse
-----------------

  
`skimage.filters.correlate_sparse(image, kernel, mode='reflect')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_sparse.py#L35-L97)
 
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 
 
`imagendarray, 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.

  
`kernelndarray, 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).

  
`modestring, optional` 

See [`scipy.ndimage.correlate`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.correlate.html#scipy.ndimage.correlate "(in SciPy v1.5.4)") 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 
 
`resultarray 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
-------------------------

  
`skimage.filters.difference_of_gaussians(image, low_sigma, high_sigma=None, *, mode='nearest', cval=0, multichannel=False, truncate=4.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gaussian.py#L160-L290)
 
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 
 
`imagendarray` 

Input array to filter.

  
`low_sigmascalar 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_sigmascalar 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’.

  
`cvalscalar, optional` 

Value to fill past edges of input if `mode` is ‘constant’. Default is 0.0

  
`multichannelbool, optional (default: False)` 

Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together).

  
`truncatefloat, optional (default is 4.0)` 

Truncate the filter at this many standard deviations.

    Returns 
 
`filtered_imagendarray` 

the filtered array.

      See also

  
`skimage.feature.blog_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]](#r96d4c0941595-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.

 #### 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>

   #### 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,
...                                          multichannel=True)

```
 Apply a Laplacian of Gaussian filter as approximated by the Difference of Gaussians filter:

 
```
>>> filtered_image = difference_of_gaussians(astronaut(), 2,
...                                          multichannel=True)

```
 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))

```
 
 farid
-----

  
`skimage.filters.farid(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L690-L737)
 
Find the edge magnitude using the Farid transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Farid edge map.

      See also

  
`sobel, prewitt, 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](https://doi.org/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
--------

  
`skimage.filters.farid_h(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L740-L773)
 
Find the horizontal edges of an image using the Farid transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-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](https://doi.org/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
--------

  
`skimage.filters.farid_v(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L776-L806)
 
Find the vertical edges of an image using the Farid transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-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](https://doi.org/10.1109/TIP.2004.823819)

   
 frangi
------

  
`skimage.filters.frangi(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)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L357-L490)
 
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 eigenvectors of the Hessian to compute the similarity of an image region to vessels, according to the method described in [[1]](#r9152c279884a-1).

  Parameters 
 
`image(N, M[, P]) ndarray` 

Array with input image data.

  
`sigmasiterable of floats, optional` 

Sigmas used as scales of filter, i.e., np.arange(scale\_range[0], scale\_range[1], scale\_step)

  
`scale_range2-tuple of floats, optional` 

The range of sigmas used.

  
`scale_stepfloat, optional` 

Step size between sigmas.

  
`alphafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a plate-like structure.

  
`betafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure.

  
`gammafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure.

  
`black_ridgesboolean, 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.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`out(N, M[, P]) ndarray` 

Filtered image (maximum of pixels across all scales).

      See also

  
[`meijering`](#skimage.filters.meijering "skimage.filters.meijering")


[`sato`](#skimage.filters.sato "skimage.filters.sato")


[`hessian`](#skimage.filters.hessian "skimage.filters.hessian")

  #### Notes

 Written by Marc Schrijver, November 2001 Re-Written by D. J. Kroon, University of Twente, May 2009, [[2]](#r9152c279884a-2) Adoption of 3D version from D. G. Ellis, Januar 20017, [[3]](#r9152c279884a-3)

 #### 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](https://doi.org/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
-----

  
`skimage.filters.gabor(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gabor.py#L98-L177)
 
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 
 
`image2-D array` 

Input image.

  
`frequencyfloat` 

Spatial frequency of the harmonic function. Specified in pixels.

  
`thetafloat, optional` 

Orientation in radians. If 0, the harmonic is in the x-direction.

  
`bandwidthfloat, 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_yfloat, 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_stdsscalar, optional` 

The linear size of the kernel is n\_stds (3 by default) standard deviations.

  
`offsetfloat, 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`

  
`cvalscalar, optional` 

Value to fill past edges of input if `mode` of convolution is ‘constant’. The parameter is passed to `ndi.convolve`.

    Returns 
 
`real, imagarrays` 

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, io
>>> from matplotlib import pyplot as plt  

```
 
```
>>> image = data.coins()
>>> # detecting edges in a coin image
>>> filt_real, filt_imag = gabor(image, frequency=0.6)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               

```
 
```
>>> # less sensitivity to finer details with the lower frequency kernel
>>> filt_real, filt_imag = gabor(image, frequency=0.1)
>>> plt.figure()            
>>> io.imshow(filt_real)    
>>> io.show()               

```
 
 gabor\_kernel
-------------

  
`skimage.filters.gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gabor.py#L16-L95)
 
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 
 
`frequencyfloat` 

Spatial frequency of the harmonic function. Specified in pixels.

  
`thetafloat, optional` 

Orientation in radians. If 0, the harmonic is in the x-direction.

  
`bandwidthfloat, 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_yfloat, 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_stdsscalar, optional` 

The linear size of the kernel is n\_stds (3 by default) standard deviations

  
`offsetfloat, optional` 

Phase offset of harmonic function in radians.

    Returns 
 
`gcomplex 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 skimage import io
>>> from matplotlib import pyplot as plt  

```
 
```
>>> gk = gabor_kernel(frequency=0.2)
>>> plt.figure()        
>>> io.imshow(gk.real)  
>>> io.show()           

```
 
```
>>> # more ripples (equivalent to increasing the size of the
>>> # Gaussian spread)
>>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1)
>>> plt.figure()        
>>> io.imshow(gk.real)  
>>> io.show()           

```
 
 gaussian
--------

  
`skimage.filters.gaussian(image, sigma=1, output=None, mode='nearest', cval=0, multichannel=None, preserve_range=False, truncate=4.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gaussian.py#L12-L126)
 
Multi-dimensional Gaussian filter.

  Parameters 
 
`imagearray-like` 

Input image (grayscale or color) to filter.

  
`sigmascalar 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.

  
`outputarray, optional` 

The `output` parameter passes an array in which to store the filter output.

  
`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’.

  
`cvalscalar, optional` 

Value to fill past edges of input if `mode` is ‘constant’. Default is 0.0

  
`multichannelbool, optional (default: None)` 

Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3).

  
`preserve_rangebool, 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>

  
`truncatefloat, optional` 

Truncate the filter at this many standard deviations.

    Returns 
 
`filtered_imagendarray` 

the filtered array

     #### Notes

 This function is a wrapper around `scipy.ndi.gaussian_filter()`.

 Integer arrays are converted to float.

 The `output` should be floating point data type since gaussian converts to float provided `image`. If `output` 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

 
```
>>> a = np.zeros((3, 3))
>>> a[1, 1] = 1
>>> a
array([[0., 0., 0.],
       [0., 1., 0.],
       [0., 0., 0.]])
>>> 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]])
>>> 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
>>> 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
>>> from skimage.data import astronaut
>>> image = astronaut()
>>> filtered_img = gaussian(image, sigma=1, multichannel=True)

```
 
 hessian
-------

  
`skimage.filters.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=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L493-L571)
 
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]](#r29057abd4159-1) to find the differences between Frangi and Hessian filters.

  Parameters 
 
`image(N, M[, P]) ndarray` 

Array with input image data.

  
`sigmasiterable of floats, optional` 

Sigmas used as scales of filter, i.e., np.arange(scale\_range[0], scale\_range[1], scale\_step)

  
`scale_range2-tuple of floats, optional` 

The range of sigmas used.

  
`scale_stepfloat, optional` 

Step size between sigmas.

  
`betafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure.

  
`gammafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure.

  
`black_ridgesboolean, 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.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`out(N, M[, P]) ndarray` 

Filtered image (maximum of pixels across all scales).

      See also

  
[`meijering`](#skimage.filters.meijering "skimage.filters.meijering")


[`sato`](#skimage.filters.sato "skimage.filters.sato")


[`frangi`](#skimage.filters.frangi "skimage.filters.frangi")

  #### Notes

 Written by Marc Schrijver (November 2001) Re-Written by D. J. Kroon University of Twente (May 2009) [[2]](#r29057abd4159-2)

 #### 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](https://doi.org/10.1007/978-3-319-16811-1_40)

  
`2`  
Kroon, D. J.: Hessian based Frangi vesselness filter.

   
 inverse
-------

  
`skimage.filters.inverse(data, impulse_response=None, filter_params={}, max_gain=2, predefined_filter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L167-L204)
 
Apply the filter in reverse to the given data.

  Parameters 
 
`data(M,N) ndarray` 

Input data.

  
`impulse_responsecallable f(r, c, **filter_params)` 

Impulse response of the filter. See LPIFilter2D.\_\_init\_\_.

  
`filter_paramsdict` 

Additional keyword parameters to the impulse\_response function.

  
`max_gainfloat` 

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_filterLPIFilter2D` 

If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here.

     
 laplace
-------

  
`skimage.filters.laplace(image, ksize=3, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L656-L687)
 
Find the edges of an image using the Laplace operator.

  Parameters 
 
`imagendarray` 

Image to process.

  
`ksizeint, optional` 

Define the size of the discrete Laplacian operator such that it will have a size of (ksize,) \* image.ndim.

  
`maskndarray, 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 
 
`outputndarray` 

The Laplace edge map.

     #### Notes

 The Laplacian operator is generated using the function skimage.restoration.uft.laplacian().

 
 median
------

  
`skimage.filters.median(image, selem=None, out=None, mode='nearest', cval=0.0, behavior='ndimage')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_median.py#L10-L78)
 
Return local median of an image.

  Parameters 
 
`imagearray-like` 

Input image.

  
`selemndarray, optional` 

If `behavior=='rank'`, `selem` is a 2-D array of 1’s and 0’s. If `behavior=='ndimage'`, `selem` is a N-D array of 1’s and 0’s with the same number of dimension than `image`. If None, `selem` will be a N-D array with 3 elements for each dimension (e.g., vector, square, cube, etc.)

  
`outndarray, (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’.

  New in version 0.15: `mode` is used when `behavior='ndimage'`.

   
`cvalscalar, optional` 

Value to fill past edges of input if mode is ‘constant’. Default is 0.0

  New in version 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 [`skimage.filters.rank.median()`](skimage.filters.rank#skimage.filters.rank.median "skimage.filters.rank.median"). The new behavior will call the [`scipy.ndimage.median_filter()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter "(in SciPy v1.5.4)"). Default is ‘ndimage’.

  New in version 0.15: `behavior` is introduced in 0.15

   Changed in version 0.16: Default `behavior` has been changed from ‘rank’ to ‘ndimage’

     Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

      See also

  
[`skimage.filters.rank.median`](skimage.filters.rank#skimage.filters.rank.median "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
---------

  
`skimage.filters.meijering(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L167-L265)
 
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 eigenvectors of the Hessian to compute the similarity of an image region to neurites, according to the method described in [[1]](#rbd62388c4e81-1).

  Parameters 
 
`image(N, M[, …, P]) ndarray` 

Array with input image data.

  
`sigmasiterable of floats, optional` 

Sigmas used as scales of filter

  
`alphafloat, optional` 

Frangi correction constant that adjusts the filter’s sensitivity to deviation from a plate-like structure.

  
`black_ridgesboolean, 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.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`out(N, M[, …, P]) ndarray` 

Filtered image (maximum of pixels across all scales).

      See also

  
[`sato`](#skimage.filters.sato "skimage.filters.sato")


[`frangi`](#skimage.filters.frangi "skimage.filters.frangi")


[`hessian`](#skimage.filters.hessian "skimage.filters.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](https://doi.org/10.1002/cyto.a.20022)

   
 prewitt
-------

  
`skimage.filters.prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L434-L489)
 
Find the edge magnitude using the Prewitt transform.

  Parameters 
 
`imagearray` 

The input image.

  
`maskarray of bool, optional` 

Clip the output image to this mask. (Values where mask=0 will be set to 0.)

  
`axisint 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.

  
`modestr or sequence of str, optional` 

The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis.

  
`cvalfloat, optional` 

When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data.

    Returns 
 
`outputarray of float` 

The Prewitt edge map.

      See also

  
`sobel,` [`scharr`](#skimage.filters.scharr "skimage.filters.scharr")

  #### 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
----------

  
`skimage.filters.prewitt_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L492-L519)
 
Find the horizontal edges of an image using the Prewitt transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-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
----------

  
`skimage.filters.prewitt_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L522-L549)
 
Find the vertical edges of an image using the Prewitt transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-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
-----------

  
`skimage.filters.rank_order(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_rank_order.py#L14-L59)
 
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 
 
`imagendarray` 
  Returns 
 
`labelsndarray of type np.uint32, 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`.

  
`original_values1-D ndarray` 

Unique original values of `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=uint32), array([1, 4, 5]))
>>> b = np.array([-1., 2.5, 3.1, 2.5])
>>> rank_order(b)
(array([0, 1, 2, 1], dtype=uint32), array([-1. ,  2.5,  3.1]))

```
 
 roberts
-------

  
`skimage.filters.roberts(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L552-L585)
 
Find the edge magnitude using Roberts’ cross operator.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Roberts’ Cross edge map.

      See also

  
`sobel, scharr, prewitt, feature.canny` 
  #### Examples

 
```
>>> from skimage import data
>>> camera = data.camera()
>>> from skimage import filters
>>> edges = filters.roberts(camera)

```
 
 roberts\_neg\_diag
------------------

  
`skimage.filters.roberts_neg_diag(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L622-L653)
 
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 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Robert’s edge map.

     #### Notes

 We use the following kernel:

 
```
 0   1
-1   0

```
 
 roberts\_pos\_diag
------------------

  
`skimage.filters.roberts_pos_diag(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L588-L619)
 
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 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Robert’s edge map.

     #### Notes

 We use the following kernel:

 
```
1   0
0  -1

```
 
 sato
----

  
`skimage.filters.sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L268-L354)
 
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 eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [[1]](#r7b0e4f38c6a4-1).

  Parameters 
 
`image(N, M[, P]) ndarray` 

Array with input image data.

  
`sigmasiterable of floats, optional` 

Sigmas used as scales of filter.

  
`black_ridgesboolean, 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.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`out(N, M[, P]) ndarray` 

Filtered image (maximum of pixels across all scales).

      See also

  
[`meijering`](#skimage.filters.meijering "skimage.filters.meijering")


[`frangi`](#skimage.filters.frangi "skimage.filters.frangi")


[`hessian`](#skimage.filters.hessian "skimage.filters.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](https://doi.org/10.1016/S1361-8415(98)80009-1)

   
 scharr
------

  
`skimage.filters.scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L304-L362)
 
Find the edge magnitude using the Scharr transform.

  Parameters 
 
`imagearray` 

The input image.

  
`maskarray of bool, optional` 

Clip the output image to this mask. (Values where mask=0 will be set to 0.)

  
`axisint 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.

  
`modestr or sequence of str, optional` 

The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis.

  
`cvalfloat, optional` 

When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data.

    Returns 
 
`outputarray of float` 

The Scharr edge map.

      See also

  
`sobel, prewitt, 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
---------

  
`skimage.filters.scharr_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L365-L397)
 
Find the horizontal edges of an image using the Scharr transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-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
---------

  
`skimage.filters.scharr_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L400-L431)
 
Find the vertical edges of an image using the Scharr transform.

  Parameters 
 
`image2-D array` 

Image to process

  
`mask2-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 
 
`output2-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
-----

  
`skimage.filters.sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L188-L241)
 
Find edges in an image using the Sobel filter.

  Parameters 
 
`imagearray` 

The input image.

  
`maskarray of bool, optional` 

Clip the output image to this mask. (Values where mask=0 will be set to 0.)

  
`axisint 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.

  
`modestr or sequence of str, optional` 

The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis.

  
`cvalfloat, optional` 

When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data.

    Returns 
 
`outputarray of float` 

The Sobel edge map.

      See also

  
`scharr, prewitt, 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)

```
 
 ### Examples using `skimage.filters.sobel`

 
 ![Flood Fill]

   sobel\_h
--------

  
`skimage.filters.sobel_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L244-L271)
 
Find the horizontal edges of an image using the Sobel transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Sobel edge map.

     #### Notes

 We use the following kernel:

 
```
 1   2   1
 0   0   0
-1  -2  -1

```
 
 sobel\_v
--------

  
`skimage.filters.sobel_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L274-L301)
 
Find the vertical edges of an image using the Sobel transform.

  Parameters 
 
`image2-D array` 

Image to process.

  
`mask2-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 
 
`output2-D array` 

The Sobel edge map.

     #### Notes

 We use the following kernel:

 
```
1   0  -1
2   0  -2
1   0  -1

```
 
 threshold\_isodata
------------------

  
`skimage.filters.threshold_isodata(image=None, nbins=256, return_all=False, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L414-L528)
 
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(N, M) ndarray, optional` 

Input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

  
`return_allbool, optional` 

If False (default), return only the lowest threshold that satisfies the above equality. If True, return all valid thresholds.

  
`histarray, 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 
 
`thresholdfloat 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](https://doi.org/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](https://doi.org/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
-------------

  
`skimage.filters.threshold_li(image, *, tolerance=None, initial_guess=None, iter_callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L586-L707)
 
Compute threshold value by Li’s iterative Minimum Cross Entropy method.

  Parameters 
 
`imagendarray` 

Input image.

  
`tolerancefloat, 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_guessfloat 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 [`skimage.filters.threshold_otsu()`](#skimage.filters.threshold_otsu "skimage.filters.threshold_otsu").

  
`iter_callbackCallable[[float], Any], optional` 

A function that will be called on the threshold at every iteration of the algorithm.

    Returns 
 
`thresholdfloat` 

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](https://doi.org/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](https://doi.org/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](https://doi.org/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
----------------

  
`skimage.filters.threshold_local(image, block_size, method='gaussian', offset=0, mode='reflect', param=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L145-L236)
 
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(N, M) ndarray` 

Input image.

  
`block_sizeint` 

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 neighbourhood 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.

  
`offsetfloat, 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 neighbourhood as a single argument and returns the calculated threshold for the centre pixel.

  
`cvalfloat, optional` 

Value to fill past edges of input if mode is ‘constant’.

    Returns 
 
`threshold(N, M) ndarray` 

Threshold image. All pixels in the input image higher than the corresponding pixel in the threshold image are considered foreground.

     #### References

  
`1`  
<https://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold>

   #### 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
---------------

  
`skimage.filters.threshold_mean(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L802-L830)
 
Return threshold value based on the mean of grayscale values.

  Parameters 
 
`image(N, M[, …, P]) ndarray` 

Grayscale input image.

    Returns 
 
`thresholdfloat` 

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](https://doi.org/10.1006/cgip.1993.1040)

   #### Examples

 
```
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_mean(image)
>>> binary = image > thresh

```
 
 threshold\_minimum
------------------

  
`skimage.filters.threshold_minimum(image=None, nbins=256, max_iter=10000, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L710-L799)
 
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` 

Input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

  
`max_iterint, optional` 

Maximum number of iterations to smooth the histogram.

  
`histarray, 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 
 
`thresholdfloat` 

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](https://doi.org/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
--------------------

  
`skimage.filters.threshold_multiotsu(image, classes=3, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1137-L1228)
 
Generate `classes`-1 threshold values to divide gray levels in `image`.

 The threshold values are chosen to maximize the total sum of pairwise variances between the thresholded graylevel classes. See Notes and [[1]](#r9f5f8b3d5d49-1) for more details.

  Parameters 
 
`image(N, M) ndarray` 

Grayscale input image.

  
`classesint, optional` 

Number of classes to be thresholded, i.e. the number of resulting regions.

  
`nbinsint, optional` 

Number of bins used to calculate the histogram. This value is ignored for integer arrays.

    Returns 
 
`thresharray` 

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 \(O\left(\frac{Ch^{C-1}}{(C-1)!}\right)\), where \(h\) is the number of histogram bins and \(C\) is the number of classes desired.

 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](https://doi.org/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)

```
 
 ### Examples using `skimage.filters.threshold_multiotsu`

 
 ![Multi-Otsu Thresholding]

  

 ![Segment human cells (in mitosis)]

   threshold\_niblack
------------------

  
`skimage.filters.threshold_niblack(image, window_size=15, k=0.2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L967-L1027)
 
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 
 
`imagendarray` 

Input image.

  
`window_sizeint, 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)`).

  
`kfloat, optional` 

Value of parameter k in threshold formula.

    Returns 
 
`threshold(N, M) 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](https://doi.org/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
---------------

  
`skimage.filters.threshold_otsu(image=None, nbins=256, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L282-L350)
 
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(N, M) ndarray, optional` 

Grayscale input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

  
`histarray, 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 
 
`thresholdfloat` 

Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground.

     #### Notes

 The input image must be grayscale.

 #### References

  
`1`  
Wikipedia, [https://en.wikipedia.org/wiki/Otsu’s\_Method](https://en.wikipedia.org/wiki/Otsu's_Method)

   #### Examples

 
```
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_otsu(image)
>>> binary = image <= thresh

```
 
 ### Examples using `skimage.filters.threshold_otsu`

 
 ![Measure region properties]

  

 ![Rank filters]

   threshold\_sauvola
------------------

  
`skimage.filters.threshold_sauvola(image, window_size=15, k=0.2, r=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1030-L1087)
 
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 greyscale image.

  Parameters 
 
`imagendarray` 

Input image.

  
`window_sizeint, 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)`).

  
`kfloat, optional` 

Value of the positive parameter k.

  
`rfloat, optional` 

Value of R, the dynamic range of standard deviation. If None, set to the half of the image dtype range.

    Returns 
 
`threshold(N, M) 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](https://doi.org/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
-------------------

  
`skimage.filters.threshold_triangle(image, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L833-L907)
 
Return threshold value based on the triangle algorithm.

  Parameters 
 
`image(N, M[, …, P]) ndarray` 

Grayscale input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

    Returns 
 
`thresholdfloat` 

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](https://doi.org/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
--------------

  
`skimage.filters.threshold_yen(image=None, nbins=256, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L353-L411)
 
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(N, M) ndarray, optional` 

Input image.

  
`nbinsint, optional` 

Number of bins used to calculate histogram. This value is ignored for integer arrays.

  
`histarray, 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 
 
`thresholdfloat` 

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](https://doi.org/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](https://doi.org/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
-------------------

  
`skimage.filters.try_all_threshold(image, figsize=(8, 5), verbose=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L86-L142)
 
Returns a figure comparing the outputs of different thresholding methods.

  Parameters 
 
`image(N, M) ndarray` 

Input image.

  
`figsizetuple, optional` 

Figure size (in inches).

  
`verbosebool, optional` 

Print function name for each method.

    Returns 
 
`fig, axtuple` 

Matplotlib figure and axes.

     #### Notes

 The following algorithms are used:

 * isodata
* li
* mean
* minimum
* otsu
* triangle
* yen

 #### Examples

 
```
>>> from skimage.data import text
>>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False)

```
 
 unsharp\_mask
-------------

  
`skimage.filters.unsharp_mask(image, radius=1.0, amount=1.0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_unsharp_mask.py#L19-L135)
 
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[P, …, ]M[, N][, C] ndarray` 

Input image.

  
`radiusscalar 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.

  
`amountscalar, 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.

  
`multichannelbool, optional` 

If True, the last `image` dimension is considered as a color channel, otherwise as spatial. Color channels are processed individually.

  
`preserve_rangebool, 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 
 
`output[P, …, ]M[, N][, 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]](#re30cac9066b6-1).

 #### References

  
`1`  
Maria Petrou, Costas Petrou “Image Processing: The Fundamentals”, (2010), ed ii., page 357, ISBN 13: 9781119994398 [DOI:10.1002/9781119994398](https://doi.org/10.1002/9781119994398)

  
`2`  
Wikipedia. Unsharp masking <https://en.wikipedia.org/wiki/Unsharp_masking>

   #### 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.  ]])

```
 
 wiener
------

  
`skimage.filters.wiener(data, impulse_response=None, filter_params={}, K=0.25, predefined_filter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L207-L246)
 
Minimum Mean Square Error (Wiener) inverse filter.

  Parameters 
 
`data(M,N) ndarray` 

Input data.

  
`Kfloat or (M,N) ndarray` 

Ratio between power spectrum of noise and undegraded image.

  
`impulse_responsecallable f(r, c, **filter_params)` 

Impulse response of the filter. See LPIFilter2D.\_\_init\_\_.

  
`filter_paramsdict` 

Additional keyword parameters to the impulse\_response function.

    Other Parameters 
 
`predefined_filterLPIFilter2D` 

If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here.

     
 window
------

  
`skimage.filters.window(window_type, shape, warp_kwargs=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_window.py#L8-L129)
 
Return an n-dimensional window of a given size and dimensionality.

  Parameters 
 
`window_typestring, 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.

  
`shapetuple of int or int` 

The shape of the window along each axis. If an integer is provided, a 1D window is generated.

  
`warp_kwargsdict` 

Keyword arguments passed to [`skimage.transform.warp`](skimage.transform#skimage.transform.warp "skimage.transform.warp") (e.g., `warp_kwargs={'order':3}` to change interpolation method).

    Returns 
 
`nd_windowndarray` 

A window of the specified `shape`. `dtype` is `np.double`.

     #### 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`](skimage.transform#skimage.transform.warp "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)

 #### References

  
`1`  
Two-dimensional window design, Wikipedia, <https://en.wikipedia.org/wiki/Two_dimensional_window_design>

   #### 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))

```
 
 LPIFilter2D
-----------

  
`class skimage.filters.LPIFilter2D(impulse_response, **filter_params)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L42-L127)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Linear Position-Invariant Filter (2-dimensional)

  
`__init__(impulse_response, **filter_params)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L47-L83)
 
 Parameters 
 
`impulse_responsecallable 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: Use a 1-D gaussian in each direction without normalization coefficients.

 
```
>>> def filt_func(r, c, sigma = 1):
...     return np.exp(-np.hypot(r, c)/sigma)
>>> filter = LPIFilter2D(filt_func)

```
 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.filters.html>

Module: future
==============

 Functionality with an experimental API. 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.

 

|  |  |
| --- | --- |
| [`skimage.future.fit_segmenter`](#skimage.future.fit_segmenter "skimage.future.fit_segmenter")(labels, …) | Segmentation using labeled parts of the image and a classifier. |
| [`skimage.future.manual_lasso_segmentation`](#skimage.future.manual_lasso_segmentation "skimage.future.manual_lasso_segmentation")(image) | Return a label image based on freeform selections made with the mouse. |
| [`skimage.future.manual_polygon_segmentation`](#skimage.future.manual_polygon_segmentation "skimage.future.manual_polygon_segmentation")(image) | Return a label image based on polygon selections made with the mouse. |
| [`skimage.future.predict_segmenter`](#skimage.future.predict_segmenter "skimage.future.predict_segmenter")(features, clf) | Segmentation of images using a pretrained classifier. |
| [`skimage.future.TrainableSegmenter`](#skimage.future.TrainableSegmenter "skimage.future.TrainableSegmenter")([clf, …]) | Estimator for classifying pixels. |
| [`skimage.future.graph`](skimage.future.graph#module-skimage.future.graph "skimage.future.graph") |  |

 fit\_segmenter
--------------

  
`skimage.future.fit_segmenter(labels, features, clf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L89-L118)
 
Segmentation using labeled parts of the image and a classifier.

  Parameters 
 
`labelsndarray of ints` 

Image of labels. Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented.

  
`featuresndarray` 

Array of features, with the first dimension corresponding to the number of features, and the other dimensions correspond to `labels.shape`.

  
`clfclassifier 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 
 
`clfclassifier object` 

classifier trained on `labels`

    Raises 
 
`NotFittedError if self.clf has not been fitted yet (use self.fit).` 
   
 ### Examples using `skimage.future.fit_segmenter`

 
 ![Trainable segmentation using local features and random forests]

   manual\_lasso\_segmentation
---------------------------

  
`skimage.future.manual_lasso_segmentation(image, alpha=0.4, return_all=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/manual_segmentation.py#L147-L227)
 
Return a label image based on freeform selections made with the mouse.

  Parameters 
 
`image(M, N[, 3]) array` 

Grayscale or RGB image.

  
`alphafloat, optional` 

Transparency value for polygons drawn over the image.

  
`return_allbool, 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 
 
`labelsarray 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, io
>>> camera = data.camera()
>>> mask = future.manual_lasso_segmentation(camera)  
>>> io.imshow(mask)  
>>> io.show()  

```
 
 manual\_polygon\_segmentation
-----------------------------

  
`skimage.future.manual_polygon_segmentation(image, alpha=0.4, return_all=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/manual_segmentation.py#L31-L144)
 
Return a label image based on polygon selections made with the mouse.

  Parameters 
 
`image(M, N[, 3]) array` 

Grayscale or RGB image.

  
`alphafloat, optional` 

Transparency value for polygons drawn over the image.

  
`return_allbool, 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 
 
`labelsarray 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, io
>>> camera = data.camera()
>>> mask = future.manual_polygon_segmentation(camera)  
>>> io.imshow(mask)  
>>> io.show()  

```
 
 predict\_segmenter
------------------

  
`skimage.future.predict_segmenter(features, clf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L121-L160)
 
Segmentation of images using a pretrained classifier.

  Parameters 
 
`featuresndarray` 

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.

  
`clfclassifier 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 `skimage.segmentation.fit_segmenter()`.

    Returns 
 
`outputndarray` 

Labeled array, built from the prediction of the classifier.

     
 ### Examples using `skimage.future.predict_segmenter`

 
 ![Trainable segmentation using local features and random forests]

   TrainableSegmenter
------------------

  
`class skimage.future.TrainableSegmenter(clf=None, features_func=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L14-L86)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Estimator for classifying pixels.

  Parameters 
 
`clfclassifier 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_funcfunction, 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, `skimage.segmentation.multiscale_basic_features()` is used.

     #### Methods

 

|  |  |
| --- | --- |
| [`fit`](#skimage.future.TrainableSegmenter.fit "skimage.future.TrainableSegmenter.fit")(image, labels) | Train classifier using partially labeled (annotated) image. |
| [`predict`](#skimage.future.TrainableSegmenter.predict "skimage.future.TrainableSegmenter.predict")(image) | Segment new image using trained internal classifier. |

 

|  |  |
| --- | --- |
| **compute\_features** |  |

  
`__init__(clf=None, features_func=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L36-L47)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`compute_features(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L49-L52)

  
`fit(image, labels)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L54-L68)
 
Train classifier using partially labeled (annotated) image.

  Parameters 
 
`imagendarray` 

Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with `self.features_func`.

  
`labelsndarray 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(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L70-L86)
 
Segment new image using trained internal classifier.

  Parameters 
 
`imagendarray` 

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).` 
   
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.future.html>

Module: graph
=============

 

|  |  |
| --- | --- |
| [`skimage.graph.route_through_array`](#skimage.graph.route_through_array "skimage.graph.route_through_array")(array, …) | Simple example of how to use the MCP and MCP\_Geometric classes. |
| [`skimage.graph.shortest_path`](#skimage.graph.shortest_path "skimage.graph.shortest_path")(arr[, reach, …]) | Find the shortest path through an n-d array from one side to another. |
| [`skimage.graph.MCP`](#skimage.graph.MCP "skimage.graph.MCP")(costs[, offsets, …]) | A class for finding the minimum cost path through a given n-d costs array. |
| [`skimage.graph.MCP_Connect`](#skimage.graph.MCP_Connect "skimage.graph.MCP_Connect")(costs[, offsets, …]) | Connect source points using the distance-weighted minimum cost function. |
| [`skimage.graph.MCP_Flexible`](#skimage.graph.MCP_Flexible "skimage.graph.MCP_Flexible")(costs[, offsets, …]) | Find minimum cost paths through an N-d costs array. |
| [`skimage.graph.MCP_Geometric`](#skimage.graph.MCP_Geometric "skimage.graph.MCP_Geometric")(costs[, …]) | Find distance-weighted minimum cost paths through an n-d costs array. |

 route\_through\_array
---------------------

  
`skimage.graph.route_through_array(array, start, end, fully_connected=True, geometric=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/graph/mcp.py#L4-L89)
 
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 
 
`arrayndarray` 

Array of costs.

  
`startiterable` 

n-d index into [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") defining the starting point

  
`enditerable` 

n-d index into [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") defining the end point

  
`fully_connectedbool (optional)` 

If True, diagonal moves are permitted, if False, only axial moves.

  
`geometricbool (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 
 
`pathlist` 

List of n-d index tuples defining the path from `start` to `end`.

  
`costfloat` 

Cost of the path. If `geometric` is False, the cost of the path is the sum of the values of [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") 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`](#skimage.graph.MCP_Geometric "skimage.graph.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
--------------

  
`skimage.graph.shortest_path(arr, reach=1, axis=-1, output_indexlist=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/graph/spath.py#L5-L81)
 
Find the shortest path through an n-d array from one side to another.

  Parameters 
 
`arrndarray of float64` 

`reachint, 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.

  
`axisint, optional` 

The axis along which the path must always move forward (default -1)

  
`output_indexlistbool, optional` 

See return value `p` for explanation.

    Returns 
 
`piterable 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],)`

  
`costfloat` 

Cost of path. This is the absolute sum of all the differences along the path.

     
 MCP
---

  
`class skimage.graph.MCP(costs, offsets=None, fully_connected=True, sampling=None)`  
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 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 
 
`costsndarray` 

`offsetsiterable, 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_connectedbool, 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.

  
`samplingtuple, optional` 

For each dimension, specifies the distance between two cells/voxels. If not given or None, the distance is assumed unit.

    Attributes 
 
`offsetsndarray` 

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`](#skimage.graph.MCP.traceback "skimage.graph.MCP.traceback") array returned by the find\_costs() method.

      
`__init__(costs, offsets=None, fully_connected=True, sampling=None)`  
See class documentation.

 
  
`find_costs()`  
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 
 
`startsiterable` 

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.

  
`endsiterable, optional` 

A list of n-d ending indices.

  
`find_all_endsbool, 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_costsndarray` 

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.)

  
`tracebackndarray` 

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()`  
int goal\_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours.

 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 neighbours and 2 if the algorithm is now done.

 
  
`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 
 
`enditerable` 

An n-d index into the `costs` array.

    Returns 
 
`tracebacklist 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().)

     
 
 MCP\_Connect
------------

  
`class skimage.graph.MCP_Connect(costs, offsets=None, fully_connected=True)`  
Bases: `skimage.graph._mcp.MCP`

 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.

  
`__init__(*args, **kwargs)`  
Initialize self. See help(type(self)) for accurate signature.

 
  
`create_connection()`  
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 
 
`id1int` 

The seed point id where the first neighbor originated from.

  
`id2int` 

The seed point id where the second neighbor originated from.

  
`pos1tuple` 

The index of of the first neighbour in the connection.

  
`pos2tuple` 

The index of of the second neighbour in the connection.

  
`cost1float` 

The cumulative cost at `pos1`.

  
`cost2float` 

The cumulative costs at `pos2`.

     
 
 MCP\_Flexible
-------------

  
`class skimage.graph.MCP_Flexible(costs, offsets=None, fully_connected=True)`  
Bases: `skimage.graph._mcp.MCP`

 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.

  
`__init__(costs, offsets=None, fully_connected=True, sampling=None)`  
See class documentation.

 
  
`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 neightboring 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(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(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.

 
 
 MCP\_Geometric
--------------

  
`class skimage.graph.MCP_Geometric(costs, offsets=None, fully_connected=True)`  
Bases: `skimage.graph._mcp.MCP`

 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.

  
`__init__(costs, offsets=None, fully_connected=True, sampling=None)`  
See class documentation.

 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.graph.html>

Module: io
==========

 Utilities to read and write images in various formats.

 The following plug-ins are available:

 

|  |  |
| --- | --- |
| Plugin | Description |
| qt | Fast image display using the Qt library. Deprecated since 0.18. Will be removed in 0.20. |
| imread | Image reading and writing via imread |
| gdal | Image reading via the GDAL Library (www.gdal.org) |
| simpleitk | Image reading and writing via SimpleITK |
| gtk | Fast image display using the GTK library |
| pil | Image reading via the Python Imaging Library |
| fits | FITS image reading via PyFITS |
| matplotlib | Display or save images using Matplotlib |
| tifffile | Load and save TIFF and TIFF-based images using tifffile.py |
| imageio | Image reading via the ImageIO Library |

 

|  |  |
| --- | --- |
| [`skimage.io.call_plugin`](#skimage.io.call_plugin "skimage.io.call_plugin")(kind, \*args, \*\*kwargs) | Find the appropriate plugin of ‘kind’ and execute it. |
| [`skimage.io.concatenate_images`](#skimage.io.concatenate_images "skimage.io.concatenate_images")(ic) | Concatenate all images in the image collection into an array. |
| [`skimage.io.find_available_plugins`](#skimage.io.find_available_plugins "skimage.io.find_available_plugins")([loaded]) | List available plugins. |
| [`skimage.io.imread`](#skimage.io.imread "skimage.io.imread")(fname[, as\_gray, plugin]) | Load an image from file. |
| [`skimage.io.imread_collection`](#skimage.io.imread_collection "skimage.io.imread_collection")(load\_pattern[, …]) | Load a collection of images. |
| [`skimage.io.imread_collection_wrapper`](#skimage.io.imread_collection_wrapper "skimage.io.imread_collection_wrapper")(imread) |  |
| [`skimage.io.imsave`](#skimage.io.imsave "skimage.io.imsave")(fname, arr[, plugin, …]) | Save an image to file. |
| [`skimage.io.imshow`](#skimage.io.imshow "skimage.io.imshow")(arr[, plugin]) | Display an image. |
| [`skimage.io.imshow_collection`](#skimage.io.imshow_collection "skimage.io.imshow_collection")(ic[, plugin]) | Display a collection of images. |
| [`skimage.io.load_sift`](#skimage.io.load_sift "skimage.io.load_sift")(f) | Read SIFT or SURF features from externally generated file. |
| [`skimage.io.load_surf`](#skimage.io.load_surf "skimage.io.load_surf")(f) | Read SIFT or SURF features from externally generated file. |
| [`skimage.io.plugin_info`](#skimage.io.plugin_info "skimage.io.plugin_info")(plugin) | Return plugin meta-data. |
| [`skimage.io.plugin_order`](#skimage.io.plugin_order "skimage.io.plugin_order")() | Return the currently preferred plugin order. |
| [`skimage.io.pop`](#skimage.io.pop "skimage.io.pop")() | Pop an image from the shared image stack. |
| [`skimage.io.push`](#skimage.io.push "skimage.io.push")(img) | Push an image onto the shared image stack. |
| [`skimage.io.reset_plugins`](#skimage.io.reset_plugins "skimage.io.reset_plugins")() |  |
| [`skimage.io.show`](#skimage.io.show "skimage.io.show")() | Display pending images. |
| [`skimage.io.use_plugin`](#skimage.io.use_plugin "skimage.io.use_plugin")(name[, kind]) | Set the default plugin for a specified operation. |
| [`skimage.io.ImageCollection`](#skimage.io.ImageCollection "skimage.io.ImageCollection")(load\_pattern[, …]) | Load and manage a collection of image files. |
| [`skimage.io.MultiImage`](#skimage.io.MultiImage "skimage.io.MultiImage")(filename[, …]) | A class containing all frames from multi-frame images. |
| `skimage.io.collection` | Data structures to hold collections of images, with optional caching. |
| `skimage.io.manage_plugins` | Handle image reading, writing and plotting plugins. |
| `skimage.io.sift` |  |
| `skimage.io.util` |  |

 call\_plugin
------------

  
`skimage.io.call_plugin(kind, *args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L171-L207)
 
Find the appropriate plugin of ‘kind’ and execute it.

  Parameters 
 
`kind{‘imshow’, ‘imsave’, ‘imread’, ‘imread_collection’}` 

Function to look up.

  
`pluginstr, optional` 

Plugin to load. Defaults to None, in which case the first matching plugin is used.

  
`*args, **kwargsarguments and keyword arguments` 

Passed to the plugin function.

     
 concatenate\_images
-------------------

  
`skimage.io.concatenate_images(ic)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L31-L63)
 
Concatenate all images in the image collection into an array.

  Parameters 
 
`ican iterable of images` 

The images to be concatenated.

    Returns 
 
`array_catndarray` 

An array having one more dimension than the images in `ic`.

    Raises 
 ValueError

If images in `ic` don’t have identical shapes.

      See also

  
`ImageCollection.concatenate, MultiImage.concatenate` 
  #### Notes

 `concatenate_images` receives any iterable object containing images, including ImageCollection and MultiImage, and returns a NumPy array.

 
 find\_available\_plugins
------------------------

  
`skimage.io.find_available_plugins(loaded=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L138-L165)
 
List available plugins.

  Parameters 
 
`loadedbool` 

If True, show only those plugins currently loaded. By default, all plugins are shown.

    Returns 
 
`pdict` 

Dictionary with plugin names as keys and exposed functions as values.

     
 imread
------

  
`skimage.io.imread(fname, as_gray=False, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L14-L63)
 
Load an image from file.

  Parameters 
 
`fnamestring` 

Image file name, e.g. `test.jpg` or URL.

  
`as_graybool, optional` 

If True, convert color images to gray-scale (64-bit floats). Images that are already in gray-scale format are not converted.

  
`pluginstr, optional` 

Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.

    Returns 
 
`img_arrayndarray` 

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.

    Other Parameters 
 
`plugin_argskeywords` 

Passed to the given plugin.

     
 imread\_collection
------------------

  
`skimage.io.imread_collection(load_pattern, conserve_memory=True, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L66-L93)
 
Load a collection of images.

  Parameters 
 
`load_patternstr or list` 

List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for `ImageCollection` for the default behaviour of this parameter.

  
`conserve_memorybool, optional` 

If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded.

    Returns 
 
`icImageCollection` 

Collection of images.

    Other Parameters 
 
`plugin_argskeywords` 

Passed to the given plugin.

     
 imread\_collection\_wrapper
---------------------------

  
`skimage.io.imread_collection_wrapper(imread)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L378-L401)

 imsave
------

  
`skimage.io.imsave(fname, arr, plugin=None, check_contrast=True, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L96-L136)
 
Save an image to file.

  Parameters 
 
`fnamestr` 

Target filename.

  
`arrndarray of shape (M,N) or (M,N,3) or (M,N,4)` 

Image data.

  
`pluginstr, optional` 

Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.

  
`check_contrastbool, optional` 

Check for low contrast and print warning (default: True).

    Other Parameters 
 
`plugin_argskeywords` 

Passed to the given plugin.

     #### Notes

 When saving a JPEG, the compression ratio may be controlled using the `quality` keyword argument which is an integer with values in [1, 100] where 1 is worst quality and smallest file size, and 100 is best quality and largest file size (default 75). This is only available when using the PIL and imageio plugins.

 
 imshow
------

  
`skimage.io.imshow(arr, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L139-L159)
 
Display an image.

  Parameters 
 
`arrndarray or str` 

Image data or name of image file.

  
`pluginstr` 

Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found.

    Other Parameters 
 
`plugin_argskeywords` 

Passed to the given plugin.

     
 ### Examples using `skimage.io.imshow`

 
 ![Explore 3D images (of cells)]

   imshow\_collection
------------------

  
`skimage.io.imshow_collection(ic, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L162-L179)
 
Display a collection of images.

  Parameters 
 
`icImageCollection` 

Collection to display.

  
`pluginstr` 

Name of plugin to use. By default, the different plugins are tried until a suitable candidate is found.

    Other Parameters 
 
`plugin_argskeywords` 

Passed to the given plugin.

     
 load\_sift
----------

  
`skimage.io.load_sift(f)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/sift.py#L72-L73)
 
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 [`skimage.feature.CENSURE`](skimage.feature#skimage.feature.CENSURE "skimage.feature.CENSURE") instead.

  Parameters 
 
`filelikestring 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 
 
`datarecord 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
----------

  
`skimage.io.load_surf(f)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/sift.py#L76-L77)
 
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 [`skimage.feature.CENSURE`](skimage.feature#skimage.feature.CENSURE "skimage.feature.CENSURE") instead.

  Parameters 
 
`filelikestring 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 
 
`datarecord 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

     
 plugin\_info
------------

  
`skimage.io.plugin_info(plugin)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L311-L328)
 
Return plugin meta-data.

  Parameters 
 
`pluginstr` 

Name of plugin.

    Returns 
 
`mdict` 

Meta data as specified in plugin `.ini`.

     
 plugin\_order
-------------

  
`skimage.io.plugin_order()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L331-L344)
 
Return the currently preferred plugin order.

  Returns 
 
`pdict` 

Dictionary of preferred plugin order, with function name as key and plugins (in order of preference) as value.

     
 pop
---

  
`skimage.io.pop()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_image_stack.py#L26-L35)
 
Pop an image from the shared image stack.

  Returns 
 
`imgndarray` 

Image popped from the stack.

     
 push
----

  
`skimage.io.push(img)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_image_stack.py#L11-L23)
 
Push an image onto the shared image stack.

  Parameters 
 
`imgndarray` 

Image to push.

     
 reset\_plugins
--------------

  
`skimage.io.reset_plugins()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L85-L87)

 show
----

  
`skimage.io.show()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L182-L201)
 
Display pending images.

 Launch the event loop of the current gui plugin, and display all pending images, queued via [`imshow`](#skimage.io.imshow "skimage.io.imshow"). This is required when using [`imshow`](#skimage.io.imshow "skimage.io.imshow") from non-interactive scripts.

 A call to [`show`](#skimage.io.show "skimage.io.show") will block execution of code until all windows have been closed.

 #### Examples

 
```
>>> import skimage.io as io

```
 
```
>>> for i in range(4):
...     ax_im = io.imshow(np.random.rand(50, 50))
>>> io.show() 

```
 
 use\_plugin
-----------

  
`skimage.io.use_plugin(name, kind=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L210-L263)
 
Set the default plugin for a specified operation. The plugin will be loaded if it hasn’t been already.

  Parameters 
 
`namestr` 

Name of plugin.

  
`kind{‘imsave’, ‘imread’, ‘imshow’, ‘imread_collection’, ‘imshow_collection’}, optional` 

Set the plugin for this function. By default, the plugin is set for all functions.

      See also

  
`available_plugins` 

List of available plugins

    #### Examples

 To use Matplotlib as the default image reader, you would write:

 
```
>>> from skimage import io
>>> io.use_plugin('matplotlib', 'imread')

```
 To see a list of available plugins run `io.available_plugins`. Note that this lists plugins that are defined, but the full list may not be usable if your system does not have the required libraries installed.

 
 ImageCollection
---------------

  
`class skimage.io.ImageCollection(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L109-L375)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Load and manage a collection of image files.

  Parameters 
 
`load_patternstr or list of str` 

Pattern string or list of strings to load. The filename path can be absolute or relative.

  
`conserve_memorybool, optional` 

If True, [`ImageCollection`](#skimage.io.ImageCollection "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_funccallable` 

`imread` by default. See notes below.

     #### Notes

 Note that files are always returned in alphanumerical order. Also note that slicing returns a new ImageCollection, *not* a view into the data.

 ImageCollection can be modified to load images from an arbitrary source by specifying a combination of `load_pattern` and `load_func`. For an ImageCollection `ic`, `ic[5]` uses `load_func(load_pattern[5])` to load the image.

 Imagine, for example, an ImageCollection that loads every third frame from a video file:

 
```
video_file = 'no_time_for_that_tiny.gif'

def vidread_step(f, step):
    vid = imageio.get_reader(f)
    seq = [v for v in vid.iter_data()]
    return seq[::step]

ic = ImageCollection(video_file, load_func=vidread_step, step=3)

ic  # is an ImageCollection object of length 1 because there is 1 file

x = ic[0]  # calls vidread_step(video_file, step=3)
x[5]  # is the sixth element of a list of length 8 (24 / 3)

```
 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 skimage.io as io
>>> from skimage import data_dir

```
 
```
>>> coll = io.ImageCollection(data_dir + '/chess*.png')
>>> len(coll)
2
>>> coll[0].shape
(200, 200)

```
 
```
>>> ic = io.ImageCollection(['/tmp/work/*.png', '/tmp/other/*.jpg'])

```
  Attributes 
 
`fileslist 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`.

      
`__init__(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L180-L214)
 
Load and manage a collection of images.

 
  
`concatenate()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L358-L375)
 
Concatenate all images in the collection into an array.

  Returns 
 
`arnp.ndarray` 

An array having one more dimension than the images in `self`.

    Raises 
 ValueError

If images in the [`ImageCollection`](#skimage.io.ImageCollection "skimage.io.ImageCollection") don’t have identical shapes.

      See also

  
[`concatenate_images`](#skimage.io.concatenate_images "skimage.io.concatenate_images")

  
  
`property conserve_memory` 
  
`property files` 
  
`reload(n=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L346-L356)
 
Clear the image cache.

  Parameters 
 
`nNone or int` 

Clear the cache for this image only. By default, the entire cache is erased.

     
 
 MultiImage
----------

  
`class skimage.io.MultiImage(filename, conserve_memory=True, dtype=None, **imread_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L404-L459)
 
Bases: `skimage.io.collection.ImageCollection`

 A class containing all frames from multi-frame images.

  Parameters 
 
`load_patternstr or list of str` 

Pattern glob or filenames to load. The path can be absolute or relative.

  
`conserve_memorybool, optional` 

Whether to conserve memory by only caching a single frame. Default is True.

    Other Parameters 
 
`load_funccallable` 

`imread` by default. See notes below.

     #### Notes

 If `conserve_memory=True` the memory footprint can be reduced, however the performance can be affected because frames have to be read from file more often.

 The last accessed frame is cached, all other frames will have to be read from file.

 The current implementation makes use of `tifffile` for Tiff files and PIL otherwise.

 #### Examples

 
```
>>> from skimage import data_dir

```
 
```
>>> img = MultiImage(data_dir + '/multipage.tif') 
>>> len(img) 
2
>>> for frame in img: 
...     print(frame.shape) 
(15, 10)
(15, 10)

```
  
`__init__(filename, conserve_memory=True, dtype=None, **imread_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L448-L455)
 
Load a multi-img.

 
  
`property filename` 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.io.html>

Module: measure
===============

 

|  |  |
| --- | --- |
| [`skimage.measure.approximate_polygon`](#skimage.measure.approximate_polygon "skimage.measure.approximate_polygon")(coords, …) | Approximate a polygonal chain with the specified tolerance. |
| [`skimage.measure.block_reduce`](#skimage.measure.block_reduce "skimage.measure.block_reduce")(image, block\_size) | Downsample image by applying function `func` to local blocks. |
| [`skimage.measure.euler_number`](#skimage.measure.euler_number "skimage.measure.euler_number")(image[, …]) | Calculate the Euler characteristic in binary image. |
| [`skimage.measure.find_contours`](#skimage.measure.find_contours "skimage.measure.find_contours")(image[, …]) | Find iso-valued contours in a 2D array for a given level value. |
| [`skimage.measure.grid_points_in_poly`](#skimage.measure.grid_points_in_poly "skimage.measure.grid_points_in_poly")(shape, verts) | Test whether points on a specified grid are inside a polygon. |
| [`skimage.measure.inertia_tensor`](#skimage.measure.inertia_tensor "skimage.measure.inertia_tensor")(image[, mu]) | Compute the inertia tensor of the input image. |
| [`skimage.measure.inertia_tensor_eigvals`](#skimage.measure.inertia_tensor_eigvals "skimage.measure.inertia_tensor_eigvals")(image) | Compute the eigenvalues of the inertia tensor of the image. |
| [`skimage.measure.label`](#skimage.measure.label "skimage.measure.label")(input[, background, …]) | Label connected regions of an integer array. |
| [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")(volume[, …]) | Marching cubes algorithm to find surfaces in 3d volumetric data. |
| [`skimage.measure.marching_cubes_classic`](#skimage.measure.marching_cubes_classic "skimage.measure.marching_cubes_classic")(volume) | Classic marching cubes algorithm to find surfaces in 3d volumetric data. |
| [`skimage.measure.marching_cubes_lewiner`](#skimage.measure.marching_cubes_lewiner "skimage.measure.marching_cubes_lewiner")(volume) | Lewiner marching cubes algorithm to find surfaces in 3d volumetric data. |
| [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area")(verts, faces) | Compute surface area, given vertices & triangular faces |
| [`skimage.measure.moments`](#skimage.measure.moments "skimage.measure.moments")(image[, order]) | Calculate all raw image moments up to a certain order. |
| [`skimage.measure.moments_central`](#skimage.measure.moments_central "skimage.measure.moments_central")(image[, …]) | Calculate all central image moments up to a certain order. |
| [`skimage.measure.moments_coords`](#skimage.measure.moments_coords "skimage.measure.moments_coords")(coords[, order]) | Calculate all raw image moments up to a certain order. |
| [`skimage.measure.moments_coords_central`](#skimage.measure.moments_coords_central "skimage.measure.moments_coords_central")(coords) | Calculate all central image moments up to a certain order. |
| [`skimage.measure.moments_hu`](#skimage.measure.moments_hu "skimage.measure.moments_hu")(nu) | Calculate Hu’s set of image moments (2D-only). |
| [`skimage.measure.moments_normalized`](#skimage.measure.moments_normalized "skimage.measure.moments_normalized")(mu[, order]) | Calculate all normalized central image moments up to a certain order. |
| [`skimage.measure.perimeter`](#skimage.measure.perimeter "skimage.measure.perimeter")(image[, neighbourhood]) | Calculate total perimeter of all objects in binary image. |
| [`skimage.measure.perimeter_crofton`](#skimage.measure.perimeter_crofton "skimage.measure.perimeter_crofton")(image[, …]) | Calculate total Crofton perimeter of all objects in binary image. |
| [`skimage.measure.points_in_poly`](#skimage.measure.points_in_poly "skimage.measure.points_in_poly")(points, verts) | Test whether points lie inside a polygon. |
| [`skimage.measure.profile_line`](#skimage.measure.profile_line "skimage.measure.profile_line")(image, src, dst) | Return the intensity profile of an image measured along a scan line. |
| [`skimage.measure.ransac`](#skimage.measure.ransac "skimage.measure.ransac")(data, model\_class, …) | Fit a model to data with the RANSAC (random sample consensus) algorithm. |
| [`skimage.measure.regionprops`](#skimage.measure.regionprops "skimage.measure.regionprops")(label\_image[, …]) | Measure properties of labeled image regions. |
| [`skimage.measure.regionprops_table`](#skimage.measure.regionprops_table "skimage.measure.regionprops_table")(label\_image) | Compute image properties and return them as a pandas-compatible table. |
| [`skimage.measure.shannon_entropy`](#skimage.measure.shannon_entropy "skimage.measure.shannon_entropy")(image[, base]) | Calculate the Shannon entropy of an image. |
| [`skimage.measure.subdivide_polygon`](#skimage.measure.subdivide_polygon "skimage.measure.subdivide_polygon")(coords[, …]) | Subdivision of polygonal curves using B-Splines. |
| [`skimage.measure.CircleModel`](#skimage.measure.CircleModel "skimage.measure.CircleModel")() | Total least squares estimator for 2D circles. |
| [`skimage.measure.EllipseModel`](#skimage.measure.EllipseModel "skimage.measure.EllipseModel")() | Total least squares estimator for 2D ellipses. |
| [`skimage.measure.LineModelND`](#skimage.measure.LineModelND "skimage.measure.LineModelND")() | Total least squares estimator for N-dimensional lines. |

 approximate\_polygon
--------------------

  
`skimage.measure.approximate_polygon(coords, tolerance)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_polygon.py#L5-L92)
 
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(N, 2) array` 

Coordinate array.

  
`tolerancefloat` 

Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.

    Returns 
 
`coords(M, 2) array` 

Approximated polygonal chain where M <= N.

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm>

   
 block\_reduce
-------------

  
`skimage.measure.block_reduce(image, block_size, func=<function sum>, cval=0, func_kwargs=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/block.py#L5-L87)
 
Downsample image by applying function `func` to local blocks.

 This function is useful for max and mean pooling, for example.

  Parameters 
 
`imagendarray` 

N-dimensional input image.

  
`block_sizearray_like` 

Array containing down-sampling integer factor along each axis.

  
`funccallable` 

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`.

  
`cvalfloat` 

Constant padding value if image is not perfectly divisible by the block size.

  
`func_kwargsdict` 

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 
 
`imagendarray` 

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 
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 
array([[[11]],
       [[23]],
       [[35]]])
>>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max)
>>> image_max2 
array([[[27],
        [31],
        [35]]])

```
 
 euler\_number
-------------

  
`skimage.measure.euler_number(image, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L58-L183)
 
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: (N, M) ndarray or (N, M, D) ndarray.**

2D or 3D images. If image is not binary, all values strictly greater than zero are considered as the object.

  
`connectivityint, 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_numberint` 

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 neighbourhood 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) 
1...
>>> SAMPLE[45:55,45:55,45:55] = 0;
>>> euler_number(SAMPLE) 
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

```
 
 ### Examples using `skimage.measure.euler_number`

 
 ![Euler number]

   find\_contours
--------------

  
`skimage.measure.find_contours(image, level=None, fully_connected='low', positive_orientation='low', *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_find_contours.py#L11-L154)
 
Find iso-valued contours in a 2D array for a given level value.

 Uses the “marching squares” method to compute a 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 
 
`image2D ndarray of double` 

Input image in which to find contours.

  
`levelfloat, optional` 

Value along which to find contours in the array. By default, the level is set to (max(image) + min(image)) / 2

  Changed in version 0.18: This parameter is now optional.

   
`fully_connectedstr, {‘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_orientationstr, {‘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.)

  
`mask2D 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 
 
`contourslist of (n,2)-ndarrays` 

Each contour is an ndarray of shape `(n, 2)`, consisting of n `(row, column)` coordinates along the contour.

      See also

  
[`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")

  #### Notes

 The marching squares algorithm is a special case of the marching cubes algorithm [[1]](#r8ed60f468bf9-1). A simple explanation is available here:

 <http://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](https://doi.org/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. ]])]

```
 
 ### Examples using `skimage.measure.find_contours`

 
 ![Contour finding]

  

 ![Measure region properties]

   grid\_points\_in\_poly
----------------------

  
`skimage.measure.grid_points_in_poly(shape, verts)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/pnpoly.py#L4-L29)
 
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.

  Parameters 
 
`shapetuple (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.

    Returns 
 
`mask(M, N) ndarray of bool` 

True where the grid falls inside the polygon.

      See also

  
[`points_in_poly`](#skimage.measure.points_in_poly "skimage.measure.points_in_poly")

  
 inertia\_tensor
---------------

  
`skimage.measure.inertia_tensor(image, mu=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L379-L428)
 
Compute the inertia tensor of the input image.

  Parameters 
 
`imagearray` 

The input image.

  
`muarray, 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`](#skimage.measure.regionprops "skimage.measure.regionprops")), then it is more efficient to pre-compute them and pass them to the inertia tensor call.

    Returns 
 
`Tarray, shape (image.ndim, image.ndim)` 

The inertia tensor of the input image. \(T\_{i, j}\) contains the covariance of image intensity along axes \(i\) and \(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
------------------------

  
`skimage.measure.inertia_tensor_eigvals(image, mu=None, T=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L431-L469)
 
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`](#skimage.measure.inertia_tensor "skimage.measure.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 
 
`imagearray` 

The input image.

  
`muarray, optional` 

The pre-computed central moments of `image`.

  
`Tarray, shape (image.ndim, image.ndim)` 

The pre-computed inertia tensor. If `T` is given, `mu` and `image` are ignored.

    Returns 
 
`eigvalslist 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.

 
 label
-----

  
`skimage.measure.label(input, background=None, return_num=False, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_label.py#L32-L120)
 
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 
 
`inputndarray of dtype int` 

Image to label.

  
`backgroundint, 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_numbool, optional` 

Whether to return the number of assigned labels.

  
`connectivityint, 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 
 
`labelsndarray of dtype int` 

Labeled array, where all connected regions are assigned the same integer value.

  
`numint, optional` 

Number of labels, which equals the maximum label index and is only returned if return\_num is `True`.

      See also

  
[`regionprops`](#skimage.measure.regionprops "skimage.measure.regionprops")


[`regionprops_table`](#skimage.measure.regionprops_table "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]]

```
 
 ### Examples using `skimage.measure.label`

 
 ![Measure region properties]

  

 ![Euler number]

  

 ![Segment human cells (in mitosis)]

   marching\_cubes
---------------

  
`skimage.measure.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)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_lewiner.py#L11-L153)
 
Marching cubes algorithm to find surfaces in 3d volumetric data.

 In contrast with Lorensen et al. approach [[2]](#rcddcc8f5d58b-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) array` 

Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.

  
`levelfloat, 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.

  
`spacinglength-3 tuple of floats, optional` 

Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`.

  
`gradient_directionstring, 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_sizeint, optional` 

Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.

  
`allow_degeneratebool, 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: str, optional**

One of ‘lewiner’, ‘lorensen’ or ‘\_lorensen’. Specify witch of Lewiner et al. or Lorensen et al. method will be used. The ‘\_lorensen’ flag correspond to an old implementation that will be deprecated in version 0.19.

  
`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.mesh_surface_area "skimage.measure.mesh_surface_area")


[`skimage.measure.find_contours`](#skimage.measure.find_contours "skimage.measure.find_contours")

  #### Notes

 The algorithm [[1]](#rcddcc8f5d58b-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`](#skimage.measure.mesh_surface_area "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](https://doi.org/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](https://doi.org/10.1145/37401.37422)

   
 marching\_cubes\_classic
------------------------

  
`skimage.measure.marching_cubes_classic(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_classic.py#L7-L111)
 
Classic marching cubes algorithm to find surfaces in 3d volumetric data.

 Note that the `marching_cubes()` algorithm is recommended over this algorithm, because it’s faster and produces better results.

  Parameters 
 
`volume(M, N, P) array of doubles` 

Input data volume to find isosurfaces. Will be cast to `np.float64`.

  
`levelfloat` 

Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used.

  
`spacinglength-3 tuple of floats` 

Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`.

  
`gradient_directionstring` 

Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite. The two options are: \* descent : Object was greater than exterior \* ascent : Exterior was greater than object

    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.

      See also

  
[`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")


[`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area")

  #### Notes

 The marching cubes algorithm is implemented as described in [[1]](#r1e43a330a523-1). A simple explanation is available here:

 
```
http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html

```
 There are several known ambiguous cases in the marching cubes algorithm. Using point labeling as in [[1]](#r1e43a330a523-1), Figure 4, as shown:

 
```
    v8 ------ v7
   / |       / |        y
  /  |      /  |        ^  z
v4 ------ v3   |        | /
 |  v5 ----|- v6        |/          (note: NOT right handed!)
 |  /      |  /          ----> x
 | /       | /
v1 ------ v2

```
 Most notably, if v4, v8, v2, and v6 are all >= `level` (or any generalization of this case) two parallel planes are generated by this algorithm, separating v4 and v8 from v2 and v6. An equally valid interpretation would be a single connected thin surface enclosing all four points. This is the best known ambiguity, though there are others.

 This algorithm does not attempt to resolve such ambiguities; it is a naive implementation of marching cubes as in [[1]](#r1e43a330a523-1), but may be a good beginning for work with more recent techniques (Dual Marching Cubes, Extended Marching Cubes, Cubic Marching Squares, etc.).

 Because of interactions between neighboring cubes, the isosurface(s) generated by this algorithm are NOT guaranteed to be closed, particularly for complicated contours. Furthermore, this algorithm does not guarantee a single contour will be returned. Indeed, ALL isosurfaces which cross `level` will be found, regardless of connectivity.

 The output is a triangular mesh consisting of a set of unique vertices and connecting triangles. The order of these vertices and triangles in the output list is determined by the position of the smallest `x,y,z` (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.

 The generated mesh guarantees coherent orientation as of version 0.12.

 To quantify the area of an isosurface generated by this algorithm, pass outputs directly into [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area").

 #### References

  
`1(1,2,3)`  
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](https://doi.org/10.1145/37401.37422)

   
 marching\_cubes\_lewiner
------------------------

  
`skimage.measure.marching_cubes_lewiner(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, use_classic=False, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_lewiner.py#L156-L277)
 
Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.

 In contrast to `marching_cubes_classic()`, this algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice, unless there is a specific need for the classic algorithm.

  Parameters 
 
`volume(M, N, P) array` 

Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.

  
`levelfloat` 

Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used.

  
`spacinglength-3 tuple of floats` 

Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`.

  
`gradient_directionstring` 

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_sizeint` 

Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.

  
`allow_degeneratebool` 

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.

  
`use_classicbool` 

If given and True, the classic marching cubes by Lorensen (1987) is used. This option is included for reference purposes. Note that this algorithm has ambiguities and is not guaranteed to produce a topologically correct result. The results with using this option are *not* generally the same as the `marching_cubes_classic()` function.

  
`mask(M, N, P) array` 

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.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")


[`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area")

  #### 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`](#skimage.measure.mesh_surface_area "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, normals, values = marching_cubes_lewiner(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_lewiner(myvolume, 0.0) 
>>> vv.mesh(np.fliplr(verts), faces, normals, values) 
>>> vv.use().Run() 

```
 #### 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](https://doi.org/10.1080/10867651.2003.10487582)

   
 mesh\_surface\_area
-------------------

  
`skimage.measure.mesh_surface_area(verts, faces)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_classic.py#L157-L196)
 
Compute surface area, given vertices & triangular faces

  Parameters 
 
`verts(V, 3) array of floats` 

Array containing (x, y, z) 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 
 
`areafloat` 

Surface area of mesh. Units now [coordinate units] \*\* 2.

      See also

  
[`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")


[`skimage.measure.marching_cubes_classic`](#skimage.measure.marching_cubes_classic "skimage.measure.marching_cubes_classic")

  #### Notes

 The arguments expected by this function are the first two outputs from [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes"). For unit correct output, ensure correct `spacing` was passed to [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes").

 This algorithm works properly only if the `faces` provided are all triangles.

 
 moments
-------

  
`skimage.measure.moments(image, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L149-L191)
 
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 
 
`imagenD double or uint8 array` 

Rasterized shape as image.

  
`orderint, optional` 

Maximum order of moments. Default is 3.

    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.double)
>>> 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
----------------

  
`skimage.measure.moments_central(image, center=None, order=3, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L194-L250)
 
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 
 
`imagenD double or uint8 array` 

Rasterized shape as image.

  
`centertuple of float, optional` 

Coordinates of the image centroid. This will be computed if it is not provided.

  
`orderint, optional` 

The maximum order of moments computed.

    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.double)
>>> 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
---------------

  
`skimage.measure.moments_coords(coords, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L7-L45)
 
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.

  
`orderint, 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.double)
>>> 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
------------------------

  
`skimage.measure.moments_coords_central(coords, center=None, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L48-L146)
 
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.

  
`centertuple of float, optional` 

Coordinates of the image centroid. This will be computed if it is not provided.

  
`orderint, 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)  
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
-----------

  
`skimage.measure.moments_hu(nu)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L308-L348)
 
Calculate Hu’s set of image moments (2D-only).

 Note that this set of moments is proofed 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.double)
>>> 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([7.45370370e-01, 3.51165981e-01, 1.04049179e-01, 4.06442107e-02,
       2.64312299e-03, 2.40854582e-02, 4.33680869e-19])

```
 
 moments\_normalized
-------------------

  
`skimage.measure.moments_normalized(mu, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L253-L305)
 
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`.

  
`orderint, optional` 

Maximum order of moments. Default is 3.

    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.double)
>>> 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.        ]])

```
 
 perimeter
---------

  
`skimage.measure.perimeter(image, neighbourhood=4)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L186-L249)
 
Calculate total perimeter of all objects in binary image.

  Parameters 
 
`image(N, M) ndarray` 

2D binary image.

  
`neighbourhood4 or 8, optional` 

Neighborhood connectivity for border pixel determination. It is used to compute the contour. A higher neighbourhood widens the border on which the perimeter is computed.

    Returns 
 
`perimeterfloat` 

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, neighbourhood=4)  
7796.867...
>>> perimeter(img_coins, neighbourhood=8)  
8806.268...

```
 
 ### Examples using `skimage.measure.perimeter`

 
 ![Different perimeters]

   perimeter\_crofton
------------------

  
`skimage.measure.perimeter_crofton(image, directions=4)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L252-L328)
 
Calculate total Crofton perimeter of all objects in binary image.

  Parameters 
 
`image(N, M) ndarray` 

2D image. If image is not binary, all values strictly greater than zero are considered as the object.

  
`directions2 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 
 
`perimeterfloat` 

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 [`perimeter()`](#skimage.measure.perimeter "skimage.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)  
8144.578...
>>> perimeter_crofton(img_coins, directions=4)  
7837.077...

```
 
 ### Examples using `skimage.measure.perimeter_crofton`

 
 ![Different perimeters]

   points\_in\_poly
----------------

  
`skimage.measure.points_in_poly(points, verts)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/pnpoly.py#L32-L53)
 
Test whether points lie inside a polygon.

  Parameters 
 
`points(N, 2) array` 

Input points, `(x, y)`.

  
`verts(M, 2) array` 

Vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.

    Returns 
 
`mask(N,) array of bool` 

True if corresponding point is inside the polygon.

      See also

  
[`grid_points_in_poly`](#skimage.measure.grid_points_in_poly "skimage.measure.grid_points_in_poly")

  
 profile\_line
-------------

  
`skimage.measure.profile_line(image, src, dst, linewidth=1, order=None, mode=None, cval=0.0, *, reduce_func=<function mean>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/profile.py#L8-L127)
 
Return the intensity profile of an image measured along a scan line.

  Parameters 
 
`imagendarray, shape (M, N[, C])` 

The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information).

  
`srcarray_like, shape (2, )` 

The coordinates of the start point of the scan line.

  
`dstarray_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.

  
`linewidthint, optional` 

Width of the scan, perpendicular to the line

  
`orderint 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`](skimage.transform#skimage.transform.warp "skimage.transform.warp") for detail.

  
`mode{‘constant’, ‘nearest’, ‘reflect’, ‘mirror’, ‘wrap’}, optional` 

How to compute any values falling outside of the image.

  
`cvalfloat, optional` 

If `mode` is ‘constant’, what constant value to use outside the image.

  
`reduce_funccallable, 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_valuearray` 

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., 4.])

```
 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., 0.])
>>> 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
------

  
`skimage.measure.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, random_state=None, initial_inliers=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L621-L881)
 
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_classobject` 

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_samplesint in range (0, N)` 

The minimum number of data points to fit a model to.

  
`residual_thresholdfloat larger than 0` 

Maximum distance for a data point to be classified as an inlier.

  
`is_data_validfunction, optional` 

This function is called with the randomly selected data before the model is fitted to it: `is_data_valid(*random_data)`.

  
`is_model_validfunction, optional` 

This function is called with the estimated model and the randomly selected data: `is_model_valid(model, *random_data)`, .

  
`max_trialsint, optional` 

Maximum number of iterations for random sample selection.

  
`stop_sample_numint, optional` 

Stop iteration if at least this number of inliers are found.

  
`stop_residuals_sumfloat, optional` 

Stop iteration if sum of residuals is less than or equal to this threshold.

  
`stop_probabilityfloat 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.

  
`random_stateint, RandomState instance or None, optional` 

If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`.

  
`initial_inliersarray-like of bool, shape (N,), optional` 

Initial samples selection for model estimation

    Returns 
 
`modelobject` 

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])
>>> np.random.seed(seed=1234)
>>> data += np.random.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)  
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))
array([20., 30.,  5., 10.,  0.])
>>> inliers 
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
>>> np.random.seed(0)
>>> src = 100 * np.random.rand(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))
>>> inliers
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
-----------

  
`skimage.measure.regionprops(label_image, intensity_image=None, cache=True, coordinates=None, *, extra_properties=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops.py#L867-L1159)
 
Measure properties of labeled image regions.

  Parameters 
 
`label_image(M, N[, P]) ndarray` 

Labeled input image. Labels with value 0 are ignored.

  Changed in version 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. Default is None.

  Changed in version 0.18.0: The ability to provide an extra dimension for channels was added.

   
`cachebool, optional` 

Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.

  
`coordinatesDEPRECATED` 

This argument is deprecated and will be removed in a future version of scikit-image.

 See [Coordinate conventions](../user_guide/numpy_images#numpy-images-coordinate-conventions) for more details.

  Deprecated since version 0.16.0: Use “rc” coordinates everywhere. It may be sufficient to call `numpy.transpose` on your label image to get the same values as 0.15 and earlier. However, for some properties, the transformation will be less trivial. For example, the new orientation is \(\frac{\pi}{2}\) plus the old orientation.

   
`extra_propertiesIterable 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 wil 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.

    Returns 
 
`propertieslist of RegionProperties` 

Each item describes one labeled region, and can be accessed using the attributes listed below.

      See also

  
[`label`](#skimage.measure.label "skimage.measure.label")

  #### Notes

 The following properties can be accessed as attributes or keys:

  
`areaint` 

Number of pixels of the region.

  
`bboxtuple` 

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)`.

  
`bbox_areaint` 

Number of pixels of bounding box.

  
`centroidarray` 

Centroid coordinate tuple `(row, col)`.

  
`convex_areaint` 

Number of pixels of convex hull image, which is the smallest convex polygon that encloses the region.

  
`convex_image(H, J) ndarray` 

Binary convex hull image which has the same size as bounding box.

  
`coords(N, 2) ndarray` 

Coordinate list `(row, col)` of the region.

  
`eccentricityfloat` 

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_diameterfloat` 

The diameter of a circle with the same area as the region.

  
`euler_numberint` 

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.

  
`extentfloat` 

Ratio of pixels in the region to pixels in the total bounding box. Computed as `area / (rows * cols)`

  
`feret_diameter_maxfloat` 

Maximum Feret’s diameter computed as the longest distance between points around a region’s convex hull contour as determined by `find_contours`. [[5]](#r4a29d8446b4f-5)

  
`filled_areaint` 

Number of pixels of the region will all the holes filled in. Describes the area of the filled\_image.

  
`filled_image(H, J) ndarray` 

Binary region image with filled holes which has the same size as bounding box.

  
`image(H, J) ndarray` 

Sliced binary region image which has the same size as bounding box.

  
`inertia_tensorndarray` 

Inertia tensor of the region for the rotation around its mass.

  
`inertia_tensor_eigvalstuple` 

The eigenvalues of the inertia tensor in decreasing order.

  
`intensity_imagendarray` 

Image inside region bounding box.

  
`labelint` 

The label in the labeled input image.

  
`local_centroidarray` 

Centroid coordinate tuple `(row, col)`, relative to region bounding box.

  
`major_axis_lengthfloat` 

The length of the major axis of the ellipse that has the same normalized second central moments as the region.

  
`max_intensityfloat` 

Value with the greatest intensity in the region.

  
`mean_intensityfloat` 

Value with the mean intensity in the region.

  
`min_intensityfloat` 

Value with the least intensity in the region.

  
`minor_axis_lengthfloat` 

The length of the minor axis of the ellipse that has the same normalized second central moments as the region.

  
`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_hutuple` 

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.

  
`orientationfloat` 

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.

  
`perimeterfloat` 

Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4-connectivity.

  
`perimeter_croftonfloat` 

Perimeter of object approximated by the Crofton formula in 4 directions.

  
`slicetuple of slices` 

A slice to extract the object from the source image.

  
`solidityfloat` 

Ratio of pixels in the region to pixels of the convex hull image.

  
`weighted_centroidarray` 

Centroid coordinate tuple `(row, col)` weighted with intensity image.

  
`weighted_local_centroidarray` 

Centroid coordinate tuple `(row, col)`, relative to region bounding box, weighted with intensity image.

  
`weighted_moments(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.

  
`weighted_moments_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.

  
`weighted_moments_hutuple` 

Hu moments (translation, scale and rotation invariant) of intensity image.

  
`weighted_moments_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).

   Each region also supports iteration, so that you can do:

 
```
for prop in region:
    print(prop, region[prop])

```
 #### 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

```
 
 ### Examples using `skimage.measure.regionprops`

 
 ![Measure region properties]

   regionprops\_table
------------------

  
`skimage.measure.regionprops_table(label_image, intensity_image=None, properties=('label', 'bbox'), *, cache=True, separator='-', extra_properties=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops.py#L705-L864)
 
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.

  New in version 0.16.

   Parameters 
 
`label_image(N, M[, 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. Default is None.

  Changed in version 0.18.0: The ability to provide an extra dimension for channels was added.

   
`propertiestuple or list of str, optional` 

Properties that will be included in the resulting dictionary For a list of available properties, please see [`regionprops()`](#skimage.measure.regionprops "skimage.measure.regionprops"). Users should remember to add “label” to keep track of region identities.

  
`cachebool, optional` 

Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.

  
`separatorstr, 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_propertiesIterable 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 wil 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.

    Returns 
 
`out_dictdict` 

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  
{'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  
>>> data = pd.DataFrame(props)  
>>> data.head()  
   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 
>>> pd.DataFrame(props).head() 
       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

```
 
 ### Examples using `skimage.measure.regionprops_table`

 
 ![Measure region properties]

   shannon\_entropy
----------------

  
`skimage.measure.shannon_entropy(image, base=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/entropy.py#L5-L41)
 
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(N, M) ndarray` 

Grayscale input image.

  
`basefloat, optional` 

The logarithmic base to use.

    Returns 
 
`entropyfloat` 
   #### Notes

 The returned value is measured in bits or shannon (Sh) for base=2, natural unit (nat) for base=np.e and hartley (Hart) for base=10.

 #### References

  
`1`  
<https://en.wikipedia.org/wiki/Entropy_(information_theory)>

  
`2`  
<https://en.wiktionary.org/wiki/Shannon_entropy>

   #### Examples

 
```
>>> from skimage import data
>>> from skimage.measure import shannon_entropy
>>> shannon_entropy(data.camera())
7.231695011055706

```
 
 subdivide\_polygon
------------------

  
`skimage.measure.subdivide_polygon(coords, degree=2, preserve_ends=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_polygon.py#L109-L168)
 
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(N, 2) array` 

Coordinate array.

  
`degree{1, 2, 3, 4, 5, 6, 7}, optional` 

Degree of B-Spline. Default is 2.

  
`preserve_endsbool, optional` 

Preserve first and last coordinate of non-circular polygon. Default is False.

    Returns 
 
`coords(M, 2) array` 

Subdivided coordinate array.

     #### References

  
`1`  
<http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf>

   
 CircleModel
-----------

  
`class skimage.measure.CircleModel` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L221-L347)
 
Bases: `skimage.measure.fit.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.

 #### 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.])

```
  Attributes 
 
`paramstuple` 

Circle model parameters in the following order `xc`, `yc`, `r`.

      
`__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L256-L295)
 
Estimate circle model from data using total least squares.

  Parameters 
 
`data(N, 2) array` 

N points with `(x, y)` coordinates, respectively.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`predict_xy(t, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L323-L347)
 
Predict x- and y-coordinates using the estimated model.

  Parameters 
 
`tarray` 

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(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L297-L321)
 
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.

     
 
 EllipseModel
------------

  
`class skimage.measure.EllipseModel` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L350-L578)
 
Bases: `skimage.measure.fit.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

```
 #### Examples

 
```
>>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25),
...                                params=(10, 15, 4, 8, np.deg2rad(30)))
>>> ellipse = EllipseModel()
>>> ellipse.estimate(xy)
True
>>> np.round(ellipse.params, 2)
array([10.  , 15.  ,  4.  ,  8.  ,  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.])

```
  Attributes 
 
`paramstuple` 

Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`, `theta`.

      
`__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L391-L483)
 
Estimate circle model from data using total least squares.

  Parameters 
 
`data(N, 2) array` 

N points with `(x, y)` coordinates, respectively.

    Returns 
 
`successbool` 

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(t, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L547-L578)
 
Predict x- and y-coordinates using the estimated model.

  Parameters 
 
`tarray` 

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(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L485-L545)
 
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.

     
 
 LineModelND
-----------

  
`class skimage.measure.LineModelND` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L30-L218)
 
Bases: `skimage.measure.fit.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

```
 #### 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])

```
  Attributes 
 
`paramstuple` 

Line model parameters in the following order `origin`, `direction`.

      
`__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L66-L101)
 
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 
 
`successbool` 

True, if model estimation succeeds.

     
  
`predict(x, axis=0, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L134-L172)
 
Predict intersection of the estimated line model with a hyperplane orthogonal to a given axis.

  Parameters 
 
`x(n, 1) array` 

Coordinates along an axis.

  
`axisint` 

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(y, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L174-L195)
 
Predict x-coordinates for 2D lines using the estimated model.

 Alias for:

 
```
predict(y, axis=1)[:, 0]

```
  Parameters 
 
`yarray` 

y-coordinates.

  
`params(2, ) array, optional` 

Optional custom parameter set in the form (`origin`, `direction`).

    Returns 
 
`xarray` 

Predicted x-coordinates.

     
  
`predict_y(x, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L197-L218)
 
Predict y-coordinates for 2D lines using the estimated model.

 Alias for:

 
```
predict(x, axis=0)[:, 1]

```
  Parameters 
 
`xarray` 

x-coordinates.

  
`params(2, ) array, optional` 

Optional custom parameter set in the form (`origin`, `direction`).

    Returns 
 
`yarray` 

Predicted y-coordinates.

     
  
`residuals(data, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L103-L132)
 
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.

     
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.measure.html>

Module: metrics
===============

 

|  |  |
| --- | --- |
| [`skimage.metrics.adapted_rand_error`](#skimage.metrics.adapted_rand_error "skimage.metrics.adapted_rand_error")([…]) | Compute Adapted Rand error as defined by the SNEMI3D contest. |
| [`skimage.metrics.contingency_table`](#skimage.metrics.contingency_table "skimage.metrics.contingency_table")(im\_true, …) | Return the contingency table for all regions in matched segmentations. |
| [`skimage.metrics.hausdorff_distance`](#skimage.metrics.hausdorff_distance "skimage.metrics.hausdorff_distance")(image0, …) | Calculate the Hausdorff distance between nonzero elements of given images. |
| [`skimage.metrics.mean_squared_error`](#skimage.metrics.mean_squared_error "skimage.metrics.mean_squared_error")(image0, …) | Compute the mean-squared error between two images. |
| [`skimage.metrics.normalized_root_mse`](#skimage.metrics.normalized_root_mse "skimage.metrics.normalized_root_mse")(…[, …]) | Compute the normalized root mean-squared error (NRMSE) between two images. |
| [`skimage.metrics.peak_signal_noise_ratio`](#skimage.metrics.peak_signal_noise_ratio "skimage.metrics.peak_signal_noise_ratio")(…) | Compute the peak signal to noise ratio (PSNR) for an image. |
| [`skimage.metrics.structural_similarity`](#skimage.metrics.structural_similarity "skimage.metrics.structural_similarity")(im1, …) | Compute the mean structural similarity index between two images. |
| [`skimage.metrics.variation_of_information`](#skimage.metrics.variation_of_information "skimage.metrics.variation_of_information")([…]) | Return symmetric conditional entropies associated with the VI. |

 adapted\_rand\_error
--------------------

  
`skimage.metrics.adapted_rand_error(image_true=None, image_test=None, *, table=None, ignore_labels=(0, ))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_adapted_rand_error.py#L7-L76)
 
Compute Adapted Rand error as defined by the SNEMI3D contest. [[1]](#rc4bf0a102856-1)

  Parameters 
 
`image_truendarray of int` 

Ground-truth label image, same shape as im\_test.

  
`image_testndarray of int` 

Test image.

  
`tablescipy.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_labelssequence 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 
 
`arefloat` 

The adapted Rand error; equal to \(1 - \frac{2pr}{p + r}\), where `p` and `r` are the precision and recall described below.

  
`precfloat` 

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.

  
`recfloat` 

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.

 #### 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](https://doi.org/10.3389/fnana.2015.00142)

   
 contingency\_table
------------------

  
`skimage.metrics.contingency_table(im_true, im_test, *, ignore_labels=None, normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_contingency_table.py#L7-L39)
 
Return the contingency table for all regions in matched segmentations.

  Parameters 
 
`im_truendarray of int` 

Ground-truth label image, same shape as im\_test.

  
`im_testndarray of int` 

Test image.

  
`ignore_labelssequence 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.

  
`normalizebool` 

Determines if the contingency table is normalized by pixel count.

    Returns 
 
`contscipy.sparse.csr_matrix` 

A contingency table. `cont[i, j]` will equal the number of voxels labeled `i` in `im_true` and `j` in `im_test`.

     
 hausdorff\_distance
-------------------

  
`skimage.metrics.hausdorff_distance(image0, image1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/set_metrics.py#L4-L51)
 
Calculate the Hausdorff distance between nonzero elements of given images.

 The Hausdorff distance [[1]](#rda3116704e68-1) is the maximum distance between any point on `image0` and its nearest point on `image1`, and vice-versa.

  Parameters 
 
`image0, image1ndarray` 

Arrays where `True` represents a point that is included in a set of points. Both arrays must have the same shape.

    Returns 
 
`distancefloat` 

The Hausdorff distance between coordinates of nonzero pixels in `image0` and `image1`, using the Euclidian distance.

     #### 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_distance(image_a, image_b)
3.0

```
 
 ### Examples using `skimage.metrics.hausdorff_distance`

 
 ![Hausdorff Distance]

   mean\_squared\_error
--------------------

  
`skimage.metrics.mean_squared_error(image0, image1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L21-L44)
 
Compute the mean-squared error between two images.

  Parameters 
 
`image0, image1ndarray` 

Images. Any dimensionality, must have same shape.

    Returns 
 
`msefloat` 

The mean-squared error (MSE) metric.

     #### Notes

  Changed in version 0.16: This function was renamed from `skimage.measure.compare_mse` to `skimage.metrics.mean_squared_error`.

  
 normalized\_root\_mse
---------------------

  
`skimage.metrics.normalized_root_mse(image_true, image_test, *, normalization='euclidean')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L47-L105)
 
Compute the normalized root mean-squared error (NRMSE) between two images.

  Parameters 
 
`image_truendarray` 

Ground-truth image, same shape as im\_test.

  
`image_testndarray` 

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]](#re6457782c209-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 
 
`nrmsefloat` 

The NRMSE metric.

     #### Notes

  Changed in version 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
--------------------------

  
`skimage.metrics.peak_signal_noise_ratio(image_true, image_test, *, data_range=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L108-L160)
 
Compute the peak signal to noise ratio (PSNR) for an image.

  Parameters 
 
`image_truendarray` 

Ground-truth image, same shape as im\_test.

  
`image_testndarray` 

Test image.

  
`data_rangeint, 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 
 
`psnrfloat` 

The PSNR metric.

     #### Notes

  Changed in version 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
----------------------

  
`skimage.metrics.structural_similarity(im1, im2, *, win_size=None, gradient=False, data_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_structural_similarity.py#L12-L232)
 
Compute the mean structural similarity index between two images.

  Parameters 
 
`im1, im2ndarray` 

Images. Any dimensionality with same shape.

  
`win_sizeint 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`.

  
`gradientbool, optional` 

If True, also return the gradient with respect to im2.

  
`data_rangefloat, 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.

  
`multichannelbool, optional` 

If True, treat the last dimension of the array as channels. Similarity calculations are done independently for each channel then averaged.

  
`gaussian_weightsbool, optional` 

If True, each patch has its mean and variance spatially weighted by a normalized Gaussian kernel of width sigma=1.5.

  
`fullbool, optional` 

If True, also return the full structural similarity image.

    Returns 
 
`mssimfloat` 

The mean structural similarity index over the image.

  
`gradndarray` 

The gradient of the structural similarity between im1 and im2 [[2]](#re0d1cfbcf329-2). This is only returned if `gradient` is set to True.

  
`Sndarray` 

The full SSIM image. This is only returned if `full` is set to True.

    Other Parameters 
 
`use_sample_covariancebool` 

If True, normalize covariances by N-1 rather than, N where N is the number of pixels within the sliding window.

  
`K1float` 

Algorithm parameter, K1 (small constant, see [[1]](#re0d1cfbcf329-1)).

  
`K2float` 

Algorithm parameter, K2 (small constant, see [[1]](#re0d1cfbcf329-1)).

  
`sigmafloat` 

Standard deviation for the Gaussian when `gaussian_weights` is True.

     #### Notes

 To match the implementation of Wang et. al. [[1]](#re0d1cfbcf329-1), set `gaussian_weights` to True, `sigma` to 1.5, and `use_sample_covariance` to False.

  Changed in version 0.16: This function was renamed from `skimage.measure.compare_ssim` to `skimage.metrics.structural_similarity`.

  #### References

  
`1(1,2,3)`  
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](https://doi.org/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](https://arxiv.org/abs/0901.0065) [DOI:10.1007/s10043-009-0119-z](https://doi.org/10.1007/s10043-009-0119-z)

   
 variation\_of\_information
--------------------------

  
`skimage.metrics.variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=())` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_variation_of_information.py#L9-L46)
 
Return symmetric conditional entropies associated with the VI. [[1]](#rb3845a1c7d1d-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(X|Y) 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, image1ndarray of int` 

Label images / segmentations, must have same shape.

  
`tablescipy.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_labelssequence 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 
 
`vindarray 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](https://doi.org/10.1016/j.jmva.2006.11.013).

   


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.metrics.html>

Module: morphology
==================

 

|  |  |
| --- | --- |
| [`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing")(image[, …]) | Perform an area closing of the image. |
| [`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening")(image[, …]) | Perform an area opening of the image. |
| [`skimage.morphology.ball`](#skimage.morphology.ball "skimage.morphology.ball")(radius[, dtype]) | Generates a ball-shaped structuring element. |
| [`skimage.morphology.binary_closing`](#skimage.morphology.binary_closing "skimage.morphology.binary_closing")(image[, …]) | Return fast binary morphological closing of an image. |
| [`skimage.morphology.binary_dilation`](#skimage.morphology.binary_dilation "skimage.morphology.binary_dilation")(image[, …]) | Return fast binary morphological dilation of an image. |
| [`skimage.morphology.binary_erosion`](#skimage.morphology.binary_erosion "skimage.morphology.binary_erosion")(image[, …]) | Return fast binary morphological erosion of an image. |
| [`skimage.morphology.binary_opening`](#skimage.morphology.binary_opening "skimage.morphology.binary_opening")(image[, …]) | Return fast binary morphological opening of an image. |
| [`skimage.morphology.black_tophat`](#skimage.morphology.black_tophat "skimage.morphology.black_tophat")(image[, …]) | Return black top hat of an image. |
| [`skimage.morphology.closing`](#skimage.morphology.closing "skimage.morphology.closing")(image[, selem, out]) | Return greyscale morphological closing of an image. |
| [`skimage.morphology.convex_hull_image`](#skimage.morphology.convex_hull_image "skimage.morphology.convex_hull_image")(image) | Compute the convex hull image of a binary image. |
| [`skimage.morphology.convex_hull_object`](#skimage.morphology.convex_hull_object "skimage.morphology.convex_hull_object")(image, \*) | Compute the convex hull image of individual objects in a binary image. |
| [`skimage.morphology.cube`](#skimage.morphology.cube "skimage.morphology.cube")(width[, dtype]) | Generates a cube-shaped structuring element. |
| [`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing")(image[, …]) | Perform a diameter closing of the image. |
| [`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening")(image[, …]) | Perform a diameter opening of the image. |
| [`skimage.morphology.diamond`](#skimage.morphology.diamond "skimage.morphology.diamond")(radius[, dtype]) | Generates a flat, diamond-shaped structuring element. |
| [`skimage.morphology.dilation`](#skimage.morphology.dilation "skimage.morphology.dilation")(image[, selem, …]) | Return greyscale morphological dilation of an image. |
| [`skimage.morphology.disk`](#skimage.morphology.disk "skimage.morphology.disk")(radius[, dtype]) | Generates a flat, disk-shaped structuring element. |
| [`skimage.morphology.erosion`](#skimage.morphology.erosion "skimage.morphology.erosion")(image[, selem, …]) | Return greyscale morphological erosion of an image. |
| [`skimage.morphology.flood`](#skimage.morphology.flood "skimage.morphology.flood")(image, seed\_point, \*) | Mask corresponding to a flood fill. |
| [`skimage.morphology.flood_fill`](#skimage.morphology.flood_fill "skimage.morphology.flood_fill")(image, …[, …]) | Perform flood filling on an image. |
| [`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima")(image, h[, selem]) | Determine all maxima of the image with height >= h. |
| [`skimage.morphology.h_minima`](#skimage.morphology.h_minima "skimage.morphology.h_minima")(image, h[, selem]) | Determine all minima of the image with depth >= h. |
| [`skimage.morphology.label`](#skimage.morphology.label "skimage.morphology.label")(input[, …]) | Label connected regions of an integer array. |
| [`skimage.morphology.local_maxima`](#skimage.morphology.local_maxima "skimage.morphology.local_maxima")(image[, …]) | Find local maxima of n-dimensional array. |
| [`skimage.morphology.local_minima`](#skimage.morphology.local_minima "skimage.morphology.local_minima")(image[, …]) | Find local minima of n-dimensional array. |
| [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree")(image[, …]) | Build the max tree from an image. |
| [`skimage.morphology.max_tree_local_maxima`](#skimage.morphology.max_tree_local_maxima "skimage.morphology.max_tree_local_maxima")(image) | Determine all local maxima of the image. |
| [`skimage.morphology.medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis")(image[, …]) | Compute the medial axis transform of a binary image |
| [`skimage.morphology.octagon`](#skimage.morphology.octagon "skimage.morphology.octagon")(m, n[, dtype]) | Generates an octagon shaped structuring element. |
| [`skimage.morphology.octahedron`](#skimage.morphology.octahedron "skimage.morphology.octahedron")(radius[, dtype]) | Generates a octahedron-shaped structuring element. |
| [`skimage.morphology.opening`](#skimage.morphology.opening "skimage.morphology.opening")(image[, selem, out]) | Return greyscale morphological opening of an image. |
| [`skimage.morphology.reconstruction`](#skimage.morphology.reconstruction "skimage.morphology.reconstruction")(seed, mask) | Perform a morphological reconstruction of an image. |
| [`skimage.morphology.rectangle`](#skimage.morphology.rectangle "skimage.morphology.rectangle")(nrows, ncols[, …]) | Generates a flat, rectangular-shaped structuring element. |
| [`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "skimage.morphology.remove_small_holes")(ar[, …]) | Remove contiguous holes smaller than the specified size. |
| [`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects")(ar) | Remove objects smaller than the specified size. |
| [`skimage.morphology.skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize")(image, \*[, …]) | Compute the skeleton of a binary image. |
| [`skimage.morphology.skeletonize_3d`](#skimage.morphology.skeletonize_3d "skimage.morphology.skeletonize_3d")(image) | Compute the skeleton of a binary image. |
| [`skimage.morphology.square`](#skimage.morphology.square "skimage.morphology.square")(width[, dtype]) | Generates a flat, square-shaped structuring element. |
| [`skimage.morphology.star`](#skimage.morphology.star "skimage.morphology.star")(a[, dtype]) | Generates a star shaped structuring element. |
| [`skimage.morphology.thin`](#skimage.morphology.thin "skimage.morphology.thin")(image[, max\_iter]) | Perform morphological thinning of a binary image. |
| [`skimage.morphology.watershed`](#skimage.morphology.watershed "skimage.morphology.watershed")(image[, …]) | **Deprecated function**. |
| [`skimage.morphology.white_tophat`](#skimage.morphology.white_tophat "skimage.morphology.white_tophat")(image[, …]) | Return white top hat of an image. |

 area\_closing
-------------

  
`skimage.morphology.area_closing(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L349-L472)
 
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 structuring element, 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 
 
`imagendarray` 

The input image for which the area\_closing is to be calculated. This image can be of any type.

  
`area_thresholdunsigned int` 

The size parameter (number of pixels). The default value is arbitrarily chosen to be 64.

  
`connectivityunsigned 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.

  
`parentndarray, 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_traverser1D 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 
 
`outputndarray` 

Output image of the same shape and type as input image.

      See also

  
[`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening")


[`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening")


[`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing")


[`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree")


[`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects")


[`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "skimage.morphology.remove_small_holes")

  #### 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)

 #### 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](https://doi.org/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](https://doi.org/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](https://doi.org/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](https://doi.org/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.

 
 area\_opening
-------------

  
`skimage.morphology.area_opening(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L146-L254)
 
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 structuring element, 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 
 
`imagendarray` 

The input image for which the area\_opening is to be calculated. This image can be of any type.

  
`area_thresholdunsigned int` 

The size parameter (number of pixels). The default value is arbitrarily chosen to be 64.

  
`connectivityunsigned 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.

  
`parentndarray, 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_traverser1D 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 
 
`outputndarray` 

Output image of the same shape and type as the input image.

      See also

  
[`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing")


[`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening")


[`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing")


[`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree")


[`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects")


[`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "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
----

  
`skimage.morphology.ball(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L231-L259)
 
Generates a ball-shaped structuring element.

 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 
 
`radiusint` 

The radius of the ball-shaped structuring element.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 ### Examples using `skimage.morphology.ball`

 
 ![Local Histogram Equalization]

  

 ![Rank filters]

   binary\_closing
---------------

  
`skimage.morphology.binary_closing(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L115-L146)
 
Return fast binary morphological closing of an image.

 This function returns the same result as greyscale 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 
 
`imagendarray` 

Binary input image.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1).

  
`outndarray of bool, optional` 

The array to store the result of the morphology. If None, is passed, a new array will be allocated.

    Returns 
 
`closingndarray of bool` 

The result of the morphological closing.

     
 ### Examples using `skimage.morphology.binary_closing`

 
 ![Flood Fill]

   binary\_dilation
----------------

  
`skimage.morphology.binary_dilation(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L46-L78)
 
Return fast binary morphological dilation of an image.

 This function returns the same result as greyscale 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 
 
`imagendarray` 

Binary input image.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1).

  
`outndarray of bool, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`dilatedndarray of bool or uint` 

The result of the morphological dilation with values in `[False, True]`.

     
 binary\_erosion
---------------

  
`skimage.morphology.binary_erosion(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L11-L43)
 
Return fast binary morphological erosion of an image.

 This function returns the same result as greyscale 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 
 
`imagendarray` 

Binary input image.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1).

  
`outndarray of bool, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`erodedndarray of bool or uint` 

The result of the morphological erosion taking values in `[False, True]`.

     
 binary\_opening
---------------

  
`skimage.morphology.binary_opening(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L81-L112)
 
Return fast binary morphological opening of an image.

 This function returns the same result as greyscale 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 
 
`imagendarray` 

Binary input image.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1).

  
`outndarray of bool, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`openingndarray of bool` 

The result of the morphological opening.

     
 ### Examples using `skimage.morphology.binary_opening`

 
 ![Flood Fill]

   black\_tophat
-------------

  
`skimage.morphology.black_tophat(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L429-L489)
 
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 structuring element. Note that dark spots in the original image are bright spots after the black top hat.

  Parameters 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarray, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`outarray, same shape and type as image` 

The result of the morphological black top hat.

      See also

  
[`white_tophat`](#skimage.morphology.white_tophat "skimage.morphology.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 square
>>> dark_on_grey = 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_grey, square(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
-------

  
`skimage.morphology.closing(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L305-L352)
 
Return greyscale morphological closing of an image.

 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 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarray, optional` 

The array to store the result of the morphology. If None, is passed, a new array will be allocated.

    Returns 
 
`closingarray, same shape and type as image` 

The result of the morphological closing.

     #### Examples

 
```
>>> # Close a gap between two bright lines
>>> import numpy as np
>>> from skimage.morphology import square
>>> 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, square(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
-------------------

  
`skimage.morphology.convex_hull_image(image, offset_coordinates=True, tolerance=1e-10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/convex_hull.py#L73-L145)
 
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 
 
`imagearray` 

Binary input image. This array is cast to bool before processing.

  
`offset_coordinatesbool, 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.

  
`tolerancefloat, 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.

    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
--------------------

  
`skimage.morphology.convex_hull_object(image, *, connectivity=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/convex_hull.py#L148-L197)
 
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 
 
`hullndarray 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`.

 
 cube
----

  
`skimage.morphology.cube(width, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L170-L194)
 
Generates a cube-shaped structuring element.

 This is the 3D equivalent of a square. Every pixel along the perimeter has a chessboard distance no greater than radius (radius=floor(width/2)) pixels.

  Parameters 
 
`widthint` 

The width, height and depth of the cube.

    Returns 
 
`selemndarray` 

A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 diameter\_closing
-----------------

  
`skimage.morphology.diameter_closing(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L475-L579)
 
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 
 
`imagendarray` 

The input image for which the diameter\_closing is to be calculated. This image can be of any type.

  
`diameter_thresholdunsigned int` 

The maximal extension parameter (number of pixels). The default value is 8.

  
`connectivityunsigned 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.

  
`parentndarray, 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_traverser1D 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 
 
`outputndarray` 

Output image of the same shape and type as input image.

      See also

  
[`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening")


[`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing")


[`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening")


[`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree")

  #### 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)

 #### 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](https://doi.org/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](https://doi.org/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.

 
 diameter\_opening
-----------------

  
`skimage.morphology.diameter_opening(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L257-L346)
 
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 
 
`imagendarray` 

The input image for which the area\_opening is to be calculated. This image can be of any type.

  
`diameter_thresholdunsigned int` 

The maximal extension parameter (number of pixels). The default value is 8.

  
`connectivityunsigned 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.

  
`parentndarray, 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_traverser1D 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 
 
`outputndarray` 

Output image of the same shape and type as the input image.

      See also

  
[`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening")


[`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing")


[`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing")


[`skimage.morphology.max_tree`](#skimage.morphology.max_tree "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](https://doi.org/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](https://doi.org/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
-------

  
`skimage.morphology.diamond(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L70-L97)
 
Generates a flat, diamond-shaped structuring element.

 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 
 
`radiusint` 

The radius of the diamond-shaped structuring element.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 dilation
--------

  
`skimage.morphology.dilation(image, selem=None, out=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L189-L252)
 
Return greyscale morphological dilation of an image.

 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 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarray, optional` 

The array to store the result of the morphology. If None, is passed, a new array will be allocated.

  
`shift_x, shift_ybool, optional` 

shift structuring element about center point. This only affects eccentric structuring elements (i.e. selem with even numbered sides).

    Returns 
 
`dilateduint8 array, same shape and type as image` 

The result of the morphological dilation.

     #### Notes

 For `uint8` (and `uint16` up to a certain bit-depth) data, the lower algorithm complexity makes the [`skimage.filters.rank.maximum`](skimage.filters.rank#skimage.filters.rank.maximum "skimage.filters.rank.maximum") function more efficient for larger images and structuring elements.

 #### Examples

 
```
>>> # Dilation enlarges bright regions
>>> import numpy as np
>>> from skimage.morphology import square
>>> 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, square(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)

```
 
 ### Examples using `skimage.morphology.dilation`

 
 ![Rank filters]

   disk
----

  
`skimage.morphology.disk(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L100-L124)
 
Generates a flat, disk-shaped structuring element.

 A pixel is within the neighborhood if the Euclidean distance between it and the origin is no greater than radius.

  Parameters 
 
`radiusint` 

The radius of the disk-shaped structuring element.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 ### Examples using `skimage.morphology.disk`

 
 ![Local Histogram Equalization]

  

 ![Entropy]

  

 ![Markers for watershed transform]

  

 ![Flood Fill]

  

 ![Segment human cells (in mitosis)]

  

 ![Rank filters]

   erosion
-------

  
`skimage.morphology.erosion(image, selem=None, out=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L130-L186)
 
Return greyscale 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 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarrays, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

  
`shift_x, shift_ybool, optional` 

shift structuring element about center point. This only affects eccentric structuring elements (i.e. selem with even numbered sides).

    Returns 
 
`erodedarray, same shape as image` 

The result of the morphological erosion.

     #### Notes

 For `uint8` (and `uint16` up to a certain bit-depth) data, the lower algorithm complexity makes the [`skimage.filters.rank.minimum`](skimage.filters.rank#skimage.filters.rank.minimum "skimage.filters.rank.minimum") function more efficient for larger images and structuring elements.

 #### Examples

 
```
>>> # Erosion shrinks bright regions
>>> import numpy as np
>>> from skimage.morphology import square
>>> 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, square(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
-----

  
`skimage.morphology.flood(image, seed_point, *, selem=None, connectivity=None, tolerance=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L124-L290)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`seed_pointtuple 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.

  
`selemndarray, optional` 

A 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).

  
`connectivityint, optional` 

A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is larger or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None.

  
`tolerancefloat 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 
 
`maskndarray` 

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`](https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html#numpy.nonzero "(in NumPy v1.19)") 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
-----------

  
`skimage.morphology.flood_fill(image, seed_point, new_value, *, selem=None, connectivity=None, tolerance=None, in_place=False, inplace=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L15-L121)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`seed_pointtuple 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_valueimage type` 

New value to set the entire fill. This must be chosen in agreement with the dtype of `image`.

  
`selemndarray, optional` 

A 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).

  
`connectivityint, 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 `selem` is not None.

  
`tolerancefloat 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_placebool, 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).

  
`inplacebool, optional` 

This parameter is deprecated and will be removed in version 0.19.0 in favor of in\_place. If True, flood filling is applied to `image` inplace. If False, the flood filled result is returned without modifying the input `image` (default).

    Returns 
 
`filledndarray` 

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]])

```
 
 h\_maxima
---------

  
`skimage.morphology.h_maxima(image, h, selem=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L48-L173)
 
Determine all maxima of the image with height >= h.

 The local maxima are defined as connected sets of pixels with equal grey level strictly greater than the grey 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 
 
`imagendarray` 

The input image for which the maxima are to be calculated.

  
`hunsigned integer` 

The minimal height of all extracted maxima.

  
`selemndarray, 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_maxndarray` 

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.extrema.h_minima` 

`skimage.morphology.extrema.local_maxima` 

`skimage.morphology.extrema.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
---------

  
`skimage.morphology.h_minima(image, h, selem=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L176-L269)
 
Determine all minima of the image with depth >= h.

 The local minima are defined as connected sets of pixels with equal grey level strictly smaller than the grey 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 
 
`imagendarray` 

The input image for which the minima are to be calculated.

  
`hunsigned integer` 

The minimal depth of all extracted minima.

  
`selemndarray, 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_minndarray` 

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.extrema.h_maxima` 

`skimage.morphology.extrema.local_maxima` 

`skimage.morphology.extrema.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.

 
 label
-----

  
`skimage.morphology.label(input, background=None, return_num=False, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_label.py#L32-L120)
 
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 
 
`inputndarray of dtype int` 

Image to label.

  
`backgroundint, 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_numbool, optional` 

Whether to return the number of assigned labels.

  
`connectivityint, 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 
 
`labelsndarray of dtype int` 

Labeled array, where all connected regions are assigned the same integer value.

  
`numint, optional` 

Number of labels, which equals the maximum label index and is only returned if return\_num is `True`.

      See also

  
`regionprops` 

`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
-------------

  
`skimage.morphology.local_maxima(image, selem=None, connectivity=None, indices=False, allow_borders=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L272-L432)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`selemndarray, optional` 

A 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 `selem` nor `connectivity` are given, all adjacent pixels are considered as part of the neighborhood.

  
`connectivityint, 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 `selem` is not None.

  
`indicesbool, 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_bordersbool, optional` 

If true, plateaus that touch the image border are valid maxima.

    Returns 
 
`maximandarray 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.local_minima "skimage.morphology.local_minima")


[`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima")


[`skimage.morphology.h_minima`](#skimage.morphology.h_minima "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
-------------

  
`skimage.morphology.local_minima(image, selem=None, connectivity=None, indices=False, allow_borders=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L435-L542)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`selemndarray, optional` 

A 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 `selem` nor `connectivity` are given, all adjacent pixels are considered as part of the neighborhood.

  
`connectivityint, 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 `selem` is not None.

  
`indicesbool, 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_bordersbool, optional` 

If true, plateaus that touch the image border are valid minima.

    Returns 
 
`minimandarray 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.local_maxima "skimage.morphology.local_maxima")


[`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima")


[`skimage.morphology.h_minima`](#skimage.morphology.h_minima "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
---------

  
`skimage.morphology.max_tree(image, connectivity=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L53-L143)
 
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 
 
`imagendarray` 

The input image for which the max-tree is to be calculated. This image can be of any type.

  
`connectivityunsigned 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 
 
`parentndarray, int64` 

Array of same shape as image. The value of each pixel is the index of its parent in the ravelled array.

  
`tree_traverser1D 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](https://doi.org/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](https://doi.org/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](https://doi.org/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](https://doi.org/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
------------------------

  
`skimage.morphology.max_tree_local_maxima(image, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L582-L670)
 
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 
 
`imagendarray` 

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_maxndarray, uint64` 

Labeled local maxima of the image.

      See also

  
[`skimage.morphology.local_maxima`](#skimage.morphology.local_maxima "skimage.morphology.local_maxima")


[`skimage.morphology.max_tree`](#skimage.morphology.max_tree "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](https://doi.org/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](https://doi.org/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](https://doi.org/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](https://doi.org/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
------------

  
`skimage.morphology.medial_axis(image, mask=None, return_distance=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L364-L510)
 
Compute the medial axis transform of a binary image

  Parameters 
 
`imagebinary ndarray, shape (M, N)` 

The image of the shape to be skeletonized.

  
`maskbinary 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_distancebool, optional` 

If true, the distance transform is returned as well as the skeleton.

    Returns 
 
`outndarray of bools` 

Medial axis transform of the image

  
`distndarray of ints, optional` 

Distance transform of the image (only returned if `return_distance` is True)

      See also

  
[`skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize")

  #### 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=np.uint8)
>>> square[1:-1, 2:-2] = 1
>>> square
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).astype(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)

```
 
 octagon
-------

  
`skimage.morphology.octagon(m, n, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L262-L300)
 
Generates an octagon shaped structuring element.

 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.

  Parameters 
 
`mint` 

The size of the horizontal and vertical sides.

  
`nint` 

The height or width of the slanted sides.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 octahedron
----------

  
`skimage.morphology.octahedron(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L197-L228)
 
Generates a octahedron-shaped structuring element.

 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 
 
`radiusint` 

The radius of the octahedron-shaped structuring element.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 opening
-------

  
`skimage.morphology.opening(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L255-L302)
 
Return greyscale morphological opening of an image.

 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 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarray, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`openingarray, same shape and type as image` 

The result of the morphological opening.

     #### Examples

 
```
>>> # Open up gap between two bright regions (but also shrink regions)
>>> import numpy as np
>>> from skimage.morphology import square
>>> 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, square(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)

```
 
 reconstruction
--------------

  
`skimage.morphology.reconstruction(seed, mask, method='dilation', selem=None, offset=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/greyreconstruct.py#L17-L211)
 
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 structuring element 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 structuring element, 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 
 
`seedndarray` 

The seed image (a.k.a. marker image), which specifies the values that are dilated or eroded.

  
`maskndarray` 

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’.

  
`selemndarray, 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.)

  
`offsetndarray, optional` 

The coordinates of the center of the structuring element. Default is located on the geometrical center of the selem, in that case selem dimensions must be odd.

    Returns 
 
`reconstructedndarray` 

The result of morphological reconstruction.

     #### Notes

 The algorithm is taken from [[1]](#r4e1a5d6f491d-1). Applications for greyscale reconstruction are discussed in [[2]](#r4e1a5d6f491d-2) and [[3]](#r4e1a5d6f491d-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.

   #### 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.

 
 rectangle
---------

  
`skimage.morphology.rectangle(nrows, ncols, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L34-L67)
 
Generates a flat, rectangular-shaped structuring element.

 Every pixel in the rectangle generated for a given width and given height belongs to the neighborhood.

  Parameters 
 
`nrowsint` 

The number of rows of the rectangle.

  
`ncolsint` 

The number of columns of the rectangle.

    Returns 
 
`selemndarray` 

A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     #### Notes

 * The use of `width` and `height` has been deprecated in version 0.18.0. Use `nrows` and `ncols` instead.

 
 remove\_small\_holes
--------------------

  
`skimage.morphology.remove_small_holes(ar, area_threshold=64, connectivity=1, in_place=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/misc.py#L142-L227)
 
Remove contiguous holes smaller than the specified size.

  Parameters 
 
`arndarray (arbitrary shape, int or bool type)` 

The array containing the connected components of interest.

  
`area_thresholdint, optional (default: 64)` 

The maximum area, in pixels, of a contiguous hole that will be filled. Replaces `min_size`.

  
`connectivityint, {1, 2, …, ar.ndim}, optional (default: 1)` 

The connectivity defining the neighborhood of a pixel.

  
`in_placebool, optional (default: False)` 

If `True`, remove the connected components in the input array itself. Otherwise, make a copy.

    Returns 
 
`outndarray, same shape and type as input ar` 

The input array with small holes within connected components removed.

    Raises 
 TypeError

If the input array is of an invalid type, such as float or string.

  ValueError

If the input array contains negative values.

     #### 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.

 #### 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, in_place=True)
>>> d is a
True

```
 
 ### Examples using `skimage.morphology.remove_small_holes`

 
 ![Measure region properties]

   remove\_small\_objects
----------------------

  
`skimage.morphology.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/misc.py#L51-L139)
 
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 
 
`arndarray (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_sizeint, optional (default: 64)` 

The smallest allowable object size.

  
`connectivityint, {1, 2, …, ar.ndim}, optional (default: 1)` 

The connectivity defining the neighborhood of a pixel. Used during labelling if `ar` is bool.

  
`in_placebool, optional (default: False)` 

If `True`, remove the objects in the input array itself. Otherwise, make a copy.

    Returns 
 
`outndarray, same shape and type as input ar` 

The input array with small connected components removed.

    Raises 
 TypeError

If the input array is of an invalid type, such as float or string.

  ValueError

If the input array contains negative values.

     #### 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, in_place=True)
>>> d is a
True

```
 
 ### Examples using `skimage.morphology.remove_small_objects`

 
 ![Measure region properties]

   skeletonize
-----------

  
`skimage.morphology.skeletonize(image, *, method=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L16-L90)
 
Compute the skeleton of a binary image.

 Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton.

  Parameters 
 
`imagendarray, 2D or 3D` 

A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground.

  
`method{‘zhang’, ‘lee’}, optional` 

Which algorithm to use. Zhang’s algorithm [[Zha84]](#rc75910d539e3-zha84) only works for 2D images, and is the default for 2D. Lee’s algorithm [[Lee94]](#rc75910d539e3-lee94) works for 2D or 3D images and is the default for 3D.

    Returns 
 
`skeletonndarray` 

The thinned image.

      See also

  
[`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.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(np.uint8)
>>> ellipse
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.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, 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)

```
 
 skeletonize\_3d
---------------

  
`skimage.morphology.skeletonize_3d(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L579-L647)
 
Compute the skeleton of a binary image.

 Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton.

  Parameters 
 
`imagendarray, 2D or 3D` 

A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground.

    Returns 
 
`skeletonndarray` 

The thinned image.

      See also

  
`skeletonize,` [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis")

  #### Notes

 The method of [[Lee94]](#rc9cdb497d267-lee94) uses an octree data structure to examine a 3x3x3 neighborhood of a pixel. The algorithm proceeds by iteratively sweeping over the image, and removing pixels at each iteration until the image stops changing. Each iteration consists of two steps: first, a list of candidates for removal is assembled; then pixels from this list are rechecked sequentially, to better preserve connectivity of the image.

 The algorithm this function implements is different from the algorithms used by either [`skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize") or [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis"), thus for 2D images the results produced by this function are generally different.

 #### References

  
`Lee94`  
T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models via 3-D medial surface/axis thinning algorithms. Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.

   
 square
------

  
`skimage.morphology.square(width, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L8-L31)
 
Generates a flat, square-shaped structuring element.

 Every pixel along the perimeter has a chessboard distance no greater than radius (radius=floor(width/2)) pixels.

  Parameters 
 
`widthint` 

The width and height of the square.

    Returns 
 
`selemndarray` 

A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 star
----

  
`skimage.morphology.star(a, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L303-L349)
 
Generates a star shaped structuring element.

 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 
 
`aint` 

Parameter deciding the size of the star structural element. The side of the square array returned is `2*a + 1 + 2*floor(a / 2)`.

    Returns 
 
`selemndarray` 

The structuring element where elements of the neighborhood are 1 and 0 otherwise.

    Other Parameters 
 
`dtypedata-type` 

The data type of the structuring element.

     
 thin
----

  
`skimage.morphology.thin(image, max_iter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L259-L356)
 
Perform morphological thinning of a binary image.

  Parameters 
 
`imagebinary (M, N) ndarray` 

The image to be thinned.

  
`max_iterint, 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 
 
`outndarray of bool` 

Thinned image.

      See also

  
`skeletonize,` [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis")

  #### Notes

 This algorithm [[1]](#r2b353e29d473-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]](#r2b353e29d473-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](https://doi.org/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](https://doi.org/10.1109/34.161346)

   #### Examples

 
```
>>> square = np.zeros((7, 7), dtype=np.uint8)
>>> square[1:-1, 2:-2] = 1
>>> square[0, 1] =  1
>>> square
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.astype(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)

```
 
 watershed
---------

  
`skimage.morphology.watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_deprecated.py#L4-L111)
 
**Deprecated function**. Use `skimage.segmentation.watershed` instead.

 Find watershed basins in `image` flooded from given `markers`.

  Parameters 
 
`imagendarray (2-D, 3-D, …) of integers` 

Data array where the lowest value points are labeled first.

  
`markersint, or ndarray of int, same shape as image, optional` 

The desired number of markers, or an array marking the basins with the values to be assigned in the label matrix. Zero means not a marker. If `None` (no markers given), the local minima of the image are used as markers.

  
`connectivityndarray, optional` 

An array with the same number of dimensions as `image` whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image.

  
`offsetarray_like of shape image.ndim, optional` 

offset of the connectivity (one offset per dimension)

  
`maskndarray of bools or 0s and 1s, optional` 

Array of same shape as `image`. Only points at which mask == True will be labeled.

  
`compactnessfloat, optional` 

Use compact watershed [[3]](#r91cba7b06893-3) with given compactness parameter. Higher values result in more regularly-shaped watershed basins.

  
`watershed_linebool, optional` 

If watershed\_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0.

    Returns 
 out: ndarray

A labeled matrix of the same type and shape as markers

      See also

  
[`skimage.segmentation.random_walker`](skimage.segmentation#skimage.segmentation.random_walker "skimage.segmentation.random_walker")


random walker segmentation 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 [[1]](#r91cba7b06893-1) [[2]](#r91cba7b06893-2) that apportions pixels into marked basins. The algorithm uses a priority queue to hold the pixels with the metric for the priority queue being pixel value, then the time of entry into the queue - this settles ties in favor of the closest marker. Some ideas taken from Soille, “Automated Basin Delineation from Digital Elevation Models Using Mathematical Morphology”, Signal Processing 20 (1990) 171-182 The most important insight in the paper is that entry time onto the queue solves two problems: a pixel should be assigned to the neighbor with the largest gradient or, if there is no gradient, pixels on a plateau should be split between markers on opposite sides. 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`  
<https://en.wikipedia.org/wiki/Watershed_%28image_processing%29>

  
`2`  
<http://cmm.ensmp.fr/~beucher/wtshed.html>

  
`3`  
Peer Neubert & Peter Protzel (2014). Compact Watershed and Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation Algorithms. ICPR 2014, pp 996-1001. [DOI:10.1109/ICPR.2014.181](https://doi.org/10.1109/ICPR.2014.181) <https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf>

   #### Examples

 The watershed algorithm is useful to separate overlapping objects.

 We first generate an initial image with two overlapping circles:

 
```
>>> import numpy as np
>>> 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
>>> local_maxi = peak_local_max(distance, labels=image,
...                             footprint=np.ones((3, 3)),
...                             indices=False)
>>> markers = ndi.label(local_maxi)[0]

```
 Finally, we run the watershed on the image and markers:

 
```
>>> labels = watershed(-distance, markers, mask=image)  

```
 The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres.

 
 white\_tophat
-------------

  
`skimage.morphology.white_tophat(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L355-L426)
 
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 structuring element.

  Parameters 
 
`imagendarray` 

Image array.

  
`selemndarray, optional` 

The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1).

  
`outndarray, optional` 

The array to store the result of the morphology. If None is passed, a new array will be allocated.

    Returns 
 
`outarray, same shape and type as image` 

The result of the morphological white top hat.

      See also

  
[`black_tophat`](#skimage.morphology.black_tophat "skimage.morphology.black_tophat")

  #### References

  
`1`  
<https://en.wikipedia.org/wiki/Top-hat_transform>

   #### Examples

 
```
>>> # Subtract grey background from bright peak
>>> import numpy as np
>>> from skimage.morphology import square
>>> bright_on_grey = 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_grey, square(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)

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.morphology.html>

Module: registration
====================

 

|  |  |
| --- | --- |
| [`skimage.registration.optical_flow_ilk`](#skimage.registration.optical_flow_ilk "skimage.registration.optical_flow_ilk")(…[, …]) | Coarse to fine optical flow estimator. |
| [`skimage.registration.optical_flow_tvl1`](#skimage.registration.optical_flow_tvl1 "skimage.registration.optical_flow_tvl1")(…) | Coarse to fine optical flow estimator. |
| [`skimage.registration.phase_cross_correlation`](#skimage.registration.phase_cross_correlation "skimage.registration.phase_cross_correlation")(…) | Efficient subpixel image translation registration by cross-correlation. |

 optical\_flow\_ilk
------------------

  
`skimage.registration.optical_flow_ilk(reference_image, moving_image, *, radius=7, num_warp=10, gaussian=False, prefilter=False, dtype=<class 'numpy.float32'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_optical_flow.py#L304-L374)
 
Coarse to fine optical flow estimator.

 The iterative Lucas-Kanade (iLK) solver is applied at each level of the image pyramid. iLK [[1]](#r8ab46b4fab1c-1) is a fast and robust alternative to TVL1 algorithm although less accurate for rendering flat surfaces and object boundaries (see [[2]](#r8ab46b4fab1c-2)).

  Parameters 
 
`reference_imagendarray, shape (M, N[, P[, …]])` 

The first gray scale image of the sequence.

  
`moving_imagendarray, shape (M, N[, P[, …]])` 

The second gray scale image of the sequence.

  
`radiusint, optional` 

Radius of the window considered around each pixel.

  
`num_warpint, optional` 

Number of times moving\_image is warped.

  
`gaussianbool, optional` 

If True, a Gaussian kernel is used for the local integration. Otherwise, a uniform kernel is used.

  
`prefilterbool, 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.

  
`dtypedtype, 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 
 
`flowndarray, 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]](#r8ab46b4fab1c-1).
* Color images are not supported.

 #### References

  
`1(1,2)`  
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](https://doi.org/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](https://doi.org/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)

```
 
 ### Examples using `skimage.registration.optical_flow_ilk`

 
 ![Registration using optical flow]

   optical\_flow\_tvl1
-------------------

  
`skimage.registration.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'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_optical_flow.py#L141-L222)
 
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]](#rda1bf5cbeff5-1), improved in [[2]](#rda1bf5cbeff5-2) and detailed in [[3]](#rda1bf5cbeff5-3).

  Parameters 
 
`reference_imagendarray, shape (M, N[, P[, …]])` 

The first gray scale image of the sequence.

  
`moving_imagendarray, shape (M, N[, P[, …]])` 

The second gray scale image of the sequence.

  
`attachmentfloat, optional` 

Attachment parameter (\(\lambda\) in [[1]](#rda1bf5cbeff5-1)). The smaller this parameter is, the smoother the returned result will be.

  
`tightnessfloat, optional` 

Tightness parameter (\(\tau\) in [[1]](#rda1bf5cbeff5-1)). It should have a small value in order to maintain attachement and regularization parts in correspondence.

  
`num_warpint, optional` 

Number of times image1 is warped.

  
`num_iterint, optional` 

Number of fixed point iteration.

  
`tolfloat, optional` 

Tolerance used as stopping criterion based on the L² distance between two consecutive values of (u, v).

  
`prefilterbool, 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.

  
`dtypedtype, 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 
 
`flowndarray, shape ((image0.ndim, M, N[, P[, …]])` 

The estimated optical flow components for each axis.

     #### Notes

 Color images are not supported.

 #### References

  
`1(1,2,3)`  
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](https://doi.org/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](https://doi.org/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](https://doi.org/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)

```
 
 ### Examples using `skimage.registration.optical_flow_tvl1`

 
 ![Registration using optical flow]

   phase\_cross\_correlation
-------------------------

  
`skimage.registration.phase_cross_correlation(reference_image, moving_image, *, upsample_factor=1, space='real', return_error=True, reference_mask=None, moving_mask=None, overlap_ratio=0.3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_phase_cross_correlation.py#L109-L276)
 
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.

  Parameters 
 
`reference_imagearray` 

Reference image.

  
`moving_imagearray` 

Image to register. Must be same dimensionality as `reference_image`.

  
`upsample_factorint, 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.

  
`spacestring, 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.

  
`return_errorbool, optional` 

Returns error and phase difference if on, otherwise only shifts are returned. Has noeffect if any of `reference_mask` or `moving_mask` is not None. In this case only shifts is returned.

  
`reference_maskndarray` 

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_maskndarray 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_ratiofloat, 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 None.

    Returns 
 
`shiftsndarray` 

Shift vector (in pixels) required to register `moving_image` with `reference_image`. Axis ordering is consistent with numpy (e.g. Z, Y, X)

  
`errorfloat` 

Translation invariant normalized RMS error between `reference_image` and `moving_image`.

  
`phasedifffloat` 

Global phase difference between the two images (should be zero if images are non-negative).

     #### 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](https://doi.org/10.1364/OL.33.000156)

  
`2`  
James R. Fienup, “Invariant error metrics for image reconstruction” Optics Letters 36, 8352-8357 (1997). [DOI:10.1364/AO.36.008352](https://doi.org/10.1364/AO.36.008352)

  
`3`  
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](https://doi.org/10.1109/TIP.2011.2181402)

  
`4`  
D. Padfield. “Masked FFT registration”. In Proc. Computer Vision and Pattern Recognition, pp. 2918-2925 (2010). [DOI:10.1109/CVPR.2010.5540032](https://doi.org/10.1109/CVPR.2010.5540032)

   
 ### Examples using `skimage.registration.phase_cross_correlation`

 
 ![Masked Normalized Cross-Correlation]

  

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.registration.html>

Module: segmentation
====================

 

|  |  |
| --- | --- |
| [`skimage.segmentation.active_contour`](#skimage.segmentation.active_contour "skimage.segmentation.active_contour")(image, snake) | Active contour model. |
| [`skimage.segmentation.chan_vese`](#skimage.segmentation.chan_vese "skimage.segmentation.chan_vese")(image[, mu, …]) | Chan-Vese segmentation algorithm. |
| [`skimage.segmentation.checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set")(…) | Create a checkerboard level set with binary values. |
| [`skimage.segmentation.circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set")(…[, …]) | Create a circle level set with binary values. |
| [`skimage.segmentation.clear_border`](#skimage.segmentation.clear_border "skimage.segmentation.clear_border")(labels[, …]) | Clear objects connected to the label image border. |
| [`skimage.segmentation.disk_level_set`](#skimage.segmentation.disk_level_set "skimage.segmentation.disk_level_set")(…[, …]) | Create a disk level set with binary values. |
| [`skimage.segmentation.expand_labels`](#skimage.segmentation.expand_labels "skimage.segmentation.expand_labels")(label\_image) | Expand labels in label image by `distance` pixels without overlapping. |
| [`skimage.segmentation.felzenszwalb`](#skimage.segmentation.felzenszwalb "skimage.segmentation.felzenszwalb")(image[, …]) | Computes Felsenszwalb’s efficient graph based image segmentation. |
| [`skimage.segmentation.find_boundaries`](#skimage.segmentation.find_boundaries "skimage.segmentation.find_boundaries")(label\_img) | Return bool array where boundaries between labeled regions are True. |
| [`skimage.segmentation.flood`](#skimage.segmentation.flood "skimage.segmentation.flood")(image, seed\_point, \*) | Mask corresponding to a flood fill. |
| [`skimage.segmentation.flood_fill`](#skimage.segmentation.flood_fill "skimage.segmentation.flood_fill")(image, …) | Perform flood filling on an image. |
| [`skimage.segmentation.inverse_gaussian_gradient`](#skimage.segmentation.inverse_gaussian_gradient "skimage.segmentation.inverse_gaussian_gradient")(image) | Inverse of gradient magnitude. |
| [`skimage.segmentation.join_segmentations`](#skimage.segmentation.join_segmentations "skimage.segmentation.join_segmentations")(s1, s2) | Return the join of the two input segmentations. |
| [`skimage.segmentation.mark_boundaries`](#skimage.segmentation.mark_boundaries "skimage.segmentation.mark_boundaries")(image, …) | Return image with boundaries between labeled regions highlighted. |
| [`skimage.segmentation.morphological_chan_vese`](#skimage.segmentation.morphological_chan_vese "skimage.segmentation.morphological_chan_vese")(…) | Morphological Active Contours without Edges (MorphACWE) |
| [`skimage.segmentation.morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour")(…) | Morphological Geodesic Active Contours (MorphGAC). |
| [`skimage.segmentation.quickshift`](#skimage.segmentation.quickshift "skimage.segmentation.quickshift")(image[, …]) | Segments image using quickshift clustering in Color-(x,y) space. |
| [`skimage.segmentation.random_walker`](#skimage.segmentation.random_walker "skimage.segmentation.random_walker")(data, labels) | Random walker algorithm for segmentation from markers. |
| [`skimage.segmentation.relabel_sequential`](#skimage.segmentation.relabel_sequential "skimage.segmentation.relabel_sequential")(…) | Relabel arbitrary labels to {`offset`, … |
| [`skimage.segmentation.slic`](#skimage.segmentation.slic "skimage.segmentation.slic")(image[, …]) | Segments image using k-means clustering in Color-(x,y,z) space. |
| [`skimage.segmentation.watershed`](#skimage.segmentation.watershed "skimage.segmentation.watershed")(image[, …]) | Find watershed basins in `image` flooded from given `markers`. |

 active\_contour
---------------

  
`skimage.segmentation.active_contour(image, snake, alpha=0.01, beta=0.1, w_line=0, w_edge=1, gamma=0.01, max_px_move=1.0, max_iterations=2500, convergence=0.1, *, boundary_condition='periodic', coordinates='rc')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/active_contour_model.py#L7-L227)
 
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(N, M) or (N, M, 3) ndarray` 

Input image.

  
`snake(N, 2) ndarray` 

Initial snake coordinates. For periodic boundary conditions, endpoints must not be duplicated.

  
`alphafloat, optional` 

Snake length shape parameter. Higher values makes snake contract faster.

  
`betafloat, optional` 

Snake smoothness shape parameter. Higher values makes snake smoother.

  
`w_linefloat, optional` 

Controls attraction to brightness. Use negative values to attract toward dark regions.

  
`w_edgefloat, optional` 

Controls attraction to edges. Use negative values to repel snake from edges.

  
`gammafloat, optional` 

Explicit time stepping parameter.

  
`max_px_movefloat, optional` 

Maximum pixel distance to move per iteration.

  
`max_iterationsint, optional` 

Maximum iterations to optimize snake shape.

  
`convergencefloat, optional` 

Convergence criteria.

  
`boundary_conditionstring, 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.

  
`coordinates{‘rc’}, optional` 

This option remains for compatibility purpose only and has no effect. It was introduced in 0.16 with the `'xy'` option, but since 0.18, only the `'rc'` option is valid. Coordinates must be set in a row-column format.

    Returns 
 
`snake(N, 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](https://doi.org/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, 2)

```
 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, coordinates='rc')  
>>> dist = np.sqrt((45-snake[:, 0])**2 + (35-snake[:, 1])**2)  
>>> int(np.mean(dist))  
25

```
 
 chan\_vese
----------

  
`skimage.segmentation.chan_vese(image, mu=0.25, lambda1=1.0, lambda2=1.0, tol=0.001, max_iter=500, dt=0.5, init_level_set='checkerboard', extended_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_chan_vese.py#L170-L338)
 
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.

  
`mufloat, optional` 

‘edge length’ weight parameter. Higher `mu` values will produce a ‘round’ edge, while values closer to zero will detect smaller objects.

  
`lambda1float, 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.

  
`lambda2float, 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.

  
`tolfloat, 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_iteruint, optional` 

Maximum number of iterations allowed before the algorithm interrupts itself.

  
`dtfloat, 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_setstr 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_outputbool, 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.

  
`energieslist 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]](#rb5da2c114fc8-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](https://doi.org/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](https://doi.org/10.5201/ipol.2012.g-cv)

  
`3`  
The Chan-Vese Algorithm - Project Report, Rami Cohen, 2011 [arXiv:1107.2782](https://arxiv.org/abs/1107.2782)

   
 checkerboard\_level\_set
------------------------

  
`skimage.segmentation.checkerboard_level_set(image_shape, square_size=5)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L193-L221)
 
Create a checkerboard level set with binary values.

  Parameters 
 
`image_shapetuple of positive integers` 

Shape of the image.

  
`square_sizeint, optional` 

Size of the squares of the checkerboard. It defaults to 5.

    Returns 
 
`outarray with shape image_shape` 

Binary level set of the checkerboard.

      See also

  
[`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set")

  
 circle\_level\_set
------------------

  
`skimage.segmentation.circle_level_set(image_shape, center=None, radius=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L117-L153)
 
Create a circle level set with binary values.

  Parameters 
 
`image_shapetuple of positive integers` 

Shape of the image

  
`centertuple of positive integers, optional` 

Coordinates of the center of the circle given in (row, column). If not given, it defaults to the center of the image.

  
`radiusfloat, optional` 

Radius of the circle. If not given, it is set to the 75% of the smallest image dimension.

    Returns 
 
`outarray with shape image_shape` 

Binary level set of the circle with the given `radius` and `center`.

    Warns 
 Deprecated:

 New in version 0.17: This function is deprecated and will be removed in scikit-image 0.19. Please use the function named `disk_level_set` instead.

       See also

  
[`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set")

  
 clear\_border
-------------

  
`skimage.segmentation.clear_border(labels, buffer_size=0, bgval=0, in_place=False, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_clear_border.py#L5-L106)
 
Clear objects connected to the label image border.

  Parameters 
 
`labels(M[, N[, …, P]]) array of int or bool` 

Imaging data labels.

  
`buffer_sizeint, optional` 

The width of the border examined. By default, only objects that touch the outside of the image are removed.

  
`bgvalfloat or int, optional` 

Cleared objects are set to this value.

  
`in_placebool, optional` 

Whether or not to manipulate the labels array in-place.

  
`maskndarray 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.

    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
----------------

  
`skimage.segmentation.disk_level_set(image_shape, *, center=None, radius=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L156-L190)
 
Create a disk level set with binary values.

  Parameters 
 
`image_shapetuple of positive integers` 

Shape of the image

  
`centertuple 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.

  
`radiusfloat, optional` 

Radius of the disk. If not given, it is set to the 75% of the smallest image dimension.

    Returns 
 
`outarray with shape image_shape` 

Binary level set of the disk with the given `radius` and `center`.

      See also

  
[`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set")

  
 expand\_labels
--------------

  
`skimage.segmentation.expand_labels(label_image, distance=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_expand_labels.py#L16-L106)
 
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` pixels 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. 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_imagendarray of dtype int` 

label image

  
`distancefloat` 

Euclidean distance in pixels by which to grow the labels. Default is one.

    Returns 
 
`enlarged_labelsndarray of dtype int` 

Labeled array, where all connected regions have been enlarged

      See also

  
`skimage.measure.label(), skimage.segmentation.watershed(),` [`skimage.morphology.dilation()`](skimage.morphology#skimage.morphology.dilation "skimage.morphology.dilation")

  #### 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]](#r700ff08b53f4-1), where it is known as module “IdentifySecondaryObjects (Distance-N)” [[2]](#r700ff08b53f4-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`.

 #### 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]])

```
 
 felzenszwalb
------------

  
`skimage.segmentation.felzenszwalb(image, scale=1, sigma=0.8, min_size=20, multichannel=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_felzenszwalb.py#L6-L64)
 
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(width, height, 3) or (width, height) ndarray` 

Input image.

  
`scalefloat` 

Free parameter. Higher means larger clusters.

  
`sigmafloat` 

Width (standard deviation) of Gaussian kernel used in preprocessing.

  
`min_sizeint` 

Minimum component size. Enforced using postprocessing.

  
`multichannelbool, optional (default: True)` 

Whether the last axis of the image is to be interpreted as multiple channels. A value of False, for a 3D image, is not currently supported.

    Returns 
 
`segment_mask(width, height) ndarray` 

Integer mask indicating segment labels.

     #### Notes

 The `k` parameter used in the original paper renamed to `scale` here.

 #### References

  
`1`  
Efficient graph-based image segmentation, Felzenszwalb, P.F. and Huttenlocher, D.P. International Journal of Computer Vision, 2004

   #### 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
----------------

  
`skimage.segmentation.find_boundaries(label_img, connectivity=1, mode='thick', background=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/boundaries.py#L48-L181)
 
Return bool array where boundaries between labeled regions are True.

  Parameters 
 
`label_imgarray of int or bool` 

An array in which different regions are labeled with either different integers or boolean values.

  
`connectivityint 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.

  
`modestring 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.

  
`backgroundint, optional` 

For modes ‘inner’ and ‘outer’, a definition of a background label is required. See `mode` for descriptions of these two.

    Returns 
 
`boundariesarray 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
-----

  
`skimage.segmentation.flood(image, seed_point, *, selem=None, connectivity=None, tolerance=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L124-L290)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`seed_pointtuple 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.

  
`selemndarray, optional` 

A 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).

  
`connectivityint, optional` 

A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is larger or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None.

  
`tolerancefloat 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 
 
`maskndarray` 

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`](https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html#numpy.nonzero "(in NumPy v1.19)") 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]])

```
 
 ### Examples using `skimage.segmentation.flood`

 
 ![Flood Fill]

   flood\_fill
-----------

  
`skimage.segmentation.flood_fill(image, seed_point, new_value, *, selem=None, connectivity=None, tolerance=None, in_place=False, inplace=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L15-L121)
 
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 
 
`imagendarray` 

An n-dimensional array.

  
`seed_pointtuple 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_valueimage type` 

New value to set the entire fill. This must be chosen in agreement with the dtype of `image`.

  
`selemndarray, optional` 

A 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).

  
`connectivityint, 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 `selem` is not None.

  
`tolerancefloat 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_placebool, 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).

  
`inplacebool, optional` 

This parameter is deprecated and will be removed in version 0.19.0 in favor of in\_place. If True, flood filling is applied to `image` inplace. If False, the flood filled result is returned without modifying the input `image` (default).

    Returns 
 
`filledndarray` 

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]])

```
 
 ### Examples using `skimage.segmentation.flood_fill`

 
 ![Flood Fill]

   inverse\_gaussian\_gradient
---------------------------

  
`skimage.segmentation.inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L224-L253)
 
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`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour").

  Parameters 
 
`image(M, N) or (L, M, N) array` 

Grayscale image or volume.

  
`alphafloat, 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.

  
`sigmafloat, 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`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour").

     
 join\_segmentations
-------------------

  
`skimage.segmentation.join_segmentations(s1, s2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_join.py#L5-L43)
 
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, s2numpy arrays` 

s1 and s2 are label fields of the same shape.

    Returns 
 
`jnumpy array` 

The join segmentation of s1 and 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]])

```
 
 mark\_boundaries
----------------

  
`skimage.segmentation.mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/boundaries.py#L184-L231)
 
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.

  
`colorlength-3 sequence, optional` 

RGB color of boundaries in the output image.

  
`outline_colorlength-3 sequence, optional` 

RGB color surrounding boundaries in the output image. If None, no outline is drawn.

  
`modestring in {‘thick’, ‘inner’, ‘outer’, ‘subpixel’}, optional` 

The mode for finding boundaries.

  
`background_labelint, 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`](#skimage.segmentation.find_boundaries "skimage.segmentation.find_boundaries")

  
 ### Examples using `skimage.segmentation.mark_boundaries`

 
 ![Trainable segmentation using local features and random forests]

   morphological\_chan\_vese
-------------------------

  
`skimage.segmentation.morphological_chan_vese(image, iterations, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=<function <lambda>>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L256-L356)
 
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.

  
`iterationsuint` 

Number of iterations to run

  
`init_level_setstr, (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 ‘circle’. See the documentation of [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") and [`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set") respectively for details about how these level sets are created.

  
`smoothinguint, optional` 

Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations.

  
`lambda1float, 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.

  
`lambda2float, 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_callbackfunction, 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

  
`circle_level_set,` [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.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]](#r81c856a3d0d3-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]](#r81c856a3d0d3-1).

 #### References

  
`1(1,2)`  
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](https://doi.org/10.1109/TPAMI.2013.106)

   
 morphological\_geodesic\_active\_contour
----------------------------------------

  
`skimage.segmentation.morphological_geodesic_active_contour(gimage, iterations, init_level_set='circle', smoothing=1, threshold='auto', balloon=0, iter_callback=<function <lambda>>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L359-L482)
 
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. [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour") will try to stop the contour evolution in areas where `gimage` is small. See `morphsnakes.inverse_gaussian_gradient` as an example function to perform this preprocessing. Note that the quality of [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour") might greatly depend on this preprocessing.

  
`iterationsuint` 

Number of iterations to run.

  
`init_level_setstr, (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 ‘circle’. See the documentation of [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") and [`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set") respectively for details about how these level sets are created.

  
`smoothinguint, optional` 

Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations.

  
`thresholdfloat, optional` 

Areas of the image with a value smaller than this threshold will be considered borders. The evolution of the contour will stop in this areas.

  
`balloonfloat, 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_callbackfunction, 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, circle_level_set,` [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.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]](#rb6daaf5d7730-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]](#rb6daaf5d7730-1).

 #### References

  
`1(1,2)`  
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](https://doi.org/10.1109/TPAMI.2013.106)

   
 quickshift
----------

  
`skimage.segmentation.quickshift(image, ratio=1.0, kernel_size=5, max_dist=10, return_tree=False, sigma=0, convert2lab=True, random_seed=42)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_quickshift.py#L11-L74)
 
Segments image using quickshift clustering in Color-(x,y) space.

 Produces an oversegmentation of the image using the quickshift mode-seeking algorithm.

  Parameters 
 
`image(width, height, channels) ndarray` 

Input image.

  
`ratiofloat, optional, between 0 and 1` 

Balances color-space proximity and image-space proximity. Higher values give more weight to color-space.

  
`kernel_sizefloat, optional` 

Width of Gaussian kernel used in smoothing the sample density. Higher means fewer clusters.

  
`max_distfloat, optional` 

Cut-off point for data distances. Higher means fewer clusters.

  
`return_treebool, optional` 

Whether to return the full segmentation hierarchy tree and distances.

  
`sigmafloat, optional` 

Width for Gaussian smoothing as preprocessing. Zero means no smoothing.

  
`convert2labbool, optional` 

Whether the input should be converted to Lab colorspace prior to segmentation. For this purpose, the input is assumed to be RGB.

  
`random_seedint, optional` 

Random seed used for breaking ties.

    Returns 
 
`segment_mask(width, height) 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
--------------

  
`skimage.segmentation.random_walker(data, labels, beta=130, mode='cg_j', tol=0.001, copy=True, multichannel=False, return_full_prob=False, spacing=None, *, prob_tol=0.001)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/random_walker_segmentation.py#L266-L514)
 
Random walker algorithm for segmentation from markers.

 Random walker algorithm is implemented for gray-level or multichannel images.

  Parameters 
 
`dataarray_like` 

Image to be segmented in phases. Gray-level `data` can be two- or three-dimensional; multichannel data can be three- or four- dimensional (multichannel=True) with the highest dimension denoting channels. Data spacing is assumed isotropic unless the `spacing` keyword argument is used.

  
`labelsarray of ints, of same shape as data without channels dimension` 

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.

  
`betafloat, optional` 

Penalization coefficient for the random walker motion (the greater `beta`, the more difficult the diffusion).

  
`modestring, 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 applyed 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.

  
`tolfloat, optional` 

Tolerance to achieve when solving the linear system using the conjugate gradient based modes (‘cg’, ‘cg\_j’ and ‘cg\_mg’).

  
`copybool, 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.

  
`multichannelbool, optional` 

If True, input data is parsed as multichannel data (see ‘data’ above for proper input format in this case).

  
`return_full_probbool, optional` 

If True, the probability that a pixel belongs to each of the labels will be returned, instead of only the most likely label.

  
`spacingiterable 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_tolfloat, optional` 

Tolerance on the resulting probability to be in the interval [0, 1]. If the tolerance is not satisfied, a warning is displayed.

    Returns 
 
`outputndarray` 

* 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.morphology.watershed`](skimage.morphology#skimage.morphology.watershed "skimage.morphology.watershed")


watershed segmentation 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]](#raf7f6bdcab09-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](https://doi.org/10.1109/TPAMI.2006.233).

   #### Examples

 
```
>>> np.random.seed(0)
>>> a = np.zeros((10, 10)) + 0.2 * np.random.rand(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)
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
-------------------

  
`skimage.segmentation.relabel_sequential(label_field, offset=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_join.py#L46-L154)
 
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_fieldnumpy array of int, arbitrary shape` 

An array of labels, which must be non-negative integers.

  
`offsetint, optional` 

The return labels will start at `offset`, which should be strictly positive.

    Returns 
 
`relabelednumpy 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_mapArrayMap` 

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_mapArrayMap` 

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
----

  
`skimage.segmentation.slic(image, n_segments=100, compactness=10.0, max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False, start_label=None, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/slic_superpixels.py#L107-L333)
 
Segments image using k-means clustering in Color-(x,y,z) space.

  Parameters 
 
`image2D, 3D or 4D ndarray` 

Input image, which can be 2D or 3D, and grayscale or multichannel (see `multichannel` parameter). Input image must either be NaN-free or the NaN’s must be masked out

  
`n_segmentsint, optional` 

The (approximate) number of labels in the segmented output image.

  
`compactnessfloat, 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_iterint, optional` 

Maximum number of iterations of k-means.

  
`sigmafloat or (3,) 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 a manual voxel spacing is provided (see Notes section).

  
`spacing(3,) array-like of floats, optional` 

The voxel spacing along each image dimension. By default, [`slic`](#skimage.segmentation.slic "skimage.segmentation.slic") assumes uniform spacing (same voxel resolution along z, y and x). This parameter controls the weights of the distances along z, y, and x during k-means clustering.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`convert2labbool, 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 `multichannel=True` *and* `image.shape[-1] == 3`.

  
`enforce_connectivitybool, optional` 

Whether the generated segments are connected or not

  
`min_size_factorfloat, optional` 

Proportion of the minimum segment size to be removed with respect to the supposed segment size ``depth*width*height/n_segments``

  
`max_size_factorfloat, optional` 

Proportion of the maximum connected segment size. A value of 3 works in most of the cases.

  
`slic_zerobool, optional` 

Run SLIC-zero, the zero-parameter mode of SLIC. [[2]](#rbeb231216055-2)

  **start\_label: int, optional**

The labels’ index start. Should be 0 or 1.

  New in version 0.17: `start_label` was introduced in 0.17

   
`mask2D 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.

  New in version 0.17: `mask` was introduced in 0.17

     Returns 
 
`labels2D 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.

     #### 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.
* 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 `multichannel=False`.
* `start_label` is introduced to handle the issue [[4]](#rbeb231216055-4). The labels indexing starting at 0 will be deprecated in future versions. If `mask` is not `None` labels indexing starts at 1 and masked area is set to 0.

 #### 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](https://doi.org/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](https://arxiv.org/abs/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
---------

  
`skimage.segmentation.watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_watershed.py#L94-L227)
 
Find watershed basins in `image` flooded from given `markers`.

  Parameters 
 
`imagendarray (2-D, 3-D, …) of integers` 

Data array where the lowest value points are labeled first.

  
`markersint, or ndarray of int, same shape as image, optional` 

The desired number of markers, or an array marking the basins with the values to be assigned in the label matrix. Zero means not a marker. If `None` (no markers given), the local minima of the image are used as markers.

  
`connectivityndarray, optional` 

An array with the same number of dimensions as `image` whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image.

  
`offsetarray_like of shape image.ndim, optional` 

offset of the connectivity (one offset per dimension)

  
`maskndarray of bools or 0s and 1s, optional` 

Array of same shape as `image`. Only points at which mask == True will be labeled.

  
`compactnessfloat, optional` 

Use compact watershed [[3]](#rc8002e235889-3) with given compactness parameter. Higher values result in more regularly-shaped watershed basins.

  
`watershed_linebool, optional` 

If watershed\_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0.

    Returns 
 
`outndarray` 

A labeled matrix of the same type and shape as markers

      See also

  
[`skimage.segmentation.random_walker`](#skimage.segmentation.random_walker "skimage.segmentation.random_walker")


random walker segmentation 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 [[1]](#rc8002e235889-1) [[2]](#rc8002e235889-2) that apportions pixels into marked basins. The algorithm uses a priority queue to hold the pixels with the metric for the priority queue being pixel value, then the time of entry into the queue - this settles ties in favor of the closest marker.

 Some ideas taken from Soille, “Automated Basin Delineation from Digital Elevation Models Using Mathematical Morphology”, Signal Processing 20 (1990) 171-182

 The most important insight in the paper is that entry time onto the queue solves two problems: a pixel should be assigned to the neighbor with the largest gradient or, if there is no gradient, pixels on a plateau should be split between markers on opposite sides.

 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`  
<https://en.wikipedia.org/wiki/Watershed_%28image_processing%29>

  
`2`  
<http://cmm.ensmp.fr/~beucher/wtshed.html>

  
`3`  
Peer Neubert & Peter Protzel (2014). Compact Watershed and Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation Algorithms. ICPR 2014, pp 996-1001. [DOI:10.1109/ICPR.2014.181](https://doi.org/10.1109/ICPR.2014.181) <https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf>

   #### 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
>>> local_maxi = peak_local_max(distance, labels=image,
...                             footprint=np.ones((3, 3)),
...                             indices=False)
>>> markers = ndi.label(local_maxi)[0]

```
 Finally, we run the watershed on the image and markers:

 
```
>>> labels = watershed(-distance, markers, mask=image)

```
 The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres.

 
 ### Examples using `skimage.segmentation.watershed`

 
 ![Watershed segmentation]

  

 ![Markers for watershed transform]

  

 ![Segment human cells (in mitosis)]

  

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.segmentation.html>

Module: transform
=================

 

|  |  |
| --- | --- |
| [`skimage.transform.downscale_local_mean`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean")(…) | Down-sample N-dimensional image by local averaging. |
| [`skimage.transform.estimate_transform`](#skimage.transform.estimate_transform "skimage.transform.estimate_transform")(ttype, …) | Estimate 2D geometric transformation parameters. |
| [`skimage.transform.frt2`](#skimage.transform.frt2 "skimage.transform.frt2")(a) | Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array. |
| [`skimage.transform.hough_circle`](#skimage.transform.hough_circle "skimage.transform.hough_circle")(image, radius) | Perform a circular Hough transform. |
| [`skimage.transform.hough_circle_peaks`](#skimage.transform.hough_circle_peaks "skimage.transform.hough_circle_peaks")(…[, …]) | Return peaks in a circle Hough transform. |
| [`skimage.transform.hough_ellipse`](#skimage.transform.hough_ellipse "skimage.transform.hough_ellipse")(image[, …]) | Perform an elliptical Hough transform. |
| [`skimage.transform.hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line")(image[, theta]) | Perform a straight line Hough transform. |
| [`skimage.transform.hough_line_peaks`](#skimage.transform.hough_line_peaks "skimage.transform.hough_line_peaks")(hspace, …) | Return peaks in a straight line Hough transform. |
| [`skimage.transform.ifrt2`](#skimage.transform.ifrt2 "skimage.transform.ifrt2")(a) | Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. |
| [`skimage.transform.integral_image`](#skimage.transform.integral_image "skimage.transform.integral_image")(image) | Integral image / summed area table. |
| [`skimage.transform.integrate`](#skimage.transform.integrate "skimage.transform.integrate")(ii, start, end) | Use an integral image to integrate over a given window. |
| [`skimage.transform.iradon`](#skimage.transform.iradon "skimage.transform.iradon")(radon\_image[, …]) | Inverse radon transform. |
| [`skimage.transform.iradon_sart`](#skimage.transform.iradon_sart "skimage.transform.iradon_sart")(radon\_image[, …]) | Inverse radon transform. |
| [`skimage.transform.matrix_transform`](#skimage.transform.matrix_transform "skimage.transform.matrix_transform")(coords, …) | Apply 2D matrix transform. |
| [`skimage.transform.order_angles_golden_ratio`](#skimage.transform.order_angles_golden_ratio "skimage.transform.order_angles_golden_ratio")(theta) | Order angles to reduce the amount of correlated information in subsequent projections. |
| [`skimage.transform.probabilistic_hough_line`](#skimage.transform.probabilistic_hough_line "skimage.transform.probabilistic_hough_line")(image) | Return lines from a progressive probabilistic line Hough transform. |
| [`skimage.transform.pyramid_expand`](#skimage.transform.pyramid_expand "skimage.transform.pyramid_expand")(image[, …]) | Upsample and then smooth image. |
| [`skimage.transform.pyramid_gaussian`](#skimage.transform.pyramid_gaussian "skimage.transform.pyramid_gaussian")(image[, …]) | Yield images of the Gaussian pyramid formed by the input image. |
| [`skimage.transform.pyramid_laplacian`](#skimage.transform.pyramid_laplacian "skimage.transform.pyramid_laplacian")(image[, …]) | Yield images of the laplacian pyramid formed by the input image. |
| [`skimage.transform.pyramid_reduce`](#skimage.transform.pyramid_reduce "skimage.transform.pyramid_reduce")(image[, …]) | Smooth and then downsample image. |
| [`skimage.transform.radon`](#skimage.transform.radon "skimage.transform.radon")(image[, theta, …]) | Calculates the radon transform of an image given specified projection angles. |
| [`skimage.transform.rescale`](#skimage.transform.rescale "skimage.transform.rescale")(image, scale[, …]) | Scale image by a certain factor. |
| [`skimage.transform.resize`](#skimage.transform.resize "skimage.transform.resize")(image, output\_shape) | Resize image to match a certain size. |
| [`skimage.transform.rotate`](#skimage.transform.rotate "skimage.transform.rotate")(image, angle[, …]) | Rotate image by a certain angle around its center. |
| [`skimage.transform.swirl`](#skimage.transform.swirl "skimage.transform.swirl")(image[, center, …]) | Perform a swirl transformation. |
| [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp")(image, inverse\_map[, …]) | Warp an image according to a given coordinate transformation. |
| [`skimage.transform.warp_coords`](#skimage.transform.warp_coords "skimage.transform.warp_coords")(coord\_map, shape) | Build the source coordinates for the output of a 2-D image warp. |
| [`skimage.transform.warp_polar`](#skimage.transform.warp_polar "skimage.transform.warp_polar")(image[, …]) | Remap image to polar or log-polar coordinates space. |
| [`skimage.transform.AffineTransform`](#skimage.transform.AffineTransform "skimage.transform.AffineTransform")([matrix, …]) | 2D affine transformation. |
| [`skimage.transform.EssentialMatrixTransform`](#skimage.transform.EssentialMatrixTransform "skimage.transform.EssentialMatrixTransform")([…]) | Essential matrix transformation. |
| [`skimage.transform.EuclideanTransform`](#skimage.transform.EuclideanTransform "skimage.transform.EuclideanTransform")([…]) | 2D Euclidean transformation. |
| [`skimage.transform.FundamentalMatrixTransform`](#skimage.transform.FundamentalMatrixTransform "skimage.transform.FundamentalMatrixTransform")([…]) | Fundamental matrix transformation. |
| [`skimage.transform.PiecewiseAffineTransform`](#skimage.transform.PiecewiseAffineTransform "skimage.transform.PiecewiseAffineTransform")() | 2D piecewise affine transformation. |
| [`skimage.transform.PolynomialTransform`](#skimage.transform.PolynomialTransform "skimage.transform.PolynomialTransform")([params]) | 2D polynomial transformation. |
| [`skimage.transform.ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")([matrix]) | Projective transformation. |
| [`skimage.transform.SimilarityTransform`](#skimage.transform.SimilarityTransform "skimage.transform.SimilarityTransform")([…]) | 2D similarity transformation. |

 downscale\_local\_mean
----------------------

  
`skimage.transform.downscale_local_mean(image, factors, cval=0, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L407-L451)
 
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`](#skimage.transform.resize "skimage.transform.resize") and [`skimage.transform.rescale`](#skimage.transform.rescale "skimage.transform.rescale") this function calculates the local mean of elements in each block of size `factors` in the input image.

  Parameters 
 
`imagendarray` 

N-dimensional input image.

  
`factorsarray_like` 

Array containing down-sampling integer factor along each axis.

  
`cvalfloat, optional` 

Constant padding value if image is not perfectly divisible by the integer factors.

  
`clipbool, 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 
 
`imagendarray` 

Down-sampled image with same number of dimensions as input image. For integer inputs, the output dtype will be `float64`. See [`numpy.mean()`](https://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.mean "(in NumPy v1.19)") 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
-------------------

  
`skimage.transform.estimate_transform(ttype, src, dst, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1342-L1413)
 
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.

  
`kwargsarray 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 
 
`tformGeometricTransform` 

Transform object containing the transformation parameters and providing access to forward and inverse transformation functions.

     #### Examples

 
```
>>> import numpy as np
>>> from skimage import transform

```
 
```
>>> # estimate transformation parameters
>>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
>>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))

```
 
```
>>> tform = transform.estimate_transform('similarity', src, dst)

```
 
```
>>> np.allclose(tform.inverse(tform(src)), src)
True

```
 
```
>>> # warp image using the estimated transformation
>>> from skimage import data
>>> image = data.camera()

```
 
```
>>> warp(image, inverse_map=tform.inverse) 

```
 
```
>>> # create transformation with explicit parameters
>>> tform2 = 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
----

  
`skimage.transform.frt2(a)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/finite_radon_transform.py#L12-L68)
 
Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array.

  Parameters 
 
`aarray_like` 

A 2-D square n x n integer array.

    Returns 
 
`FRT2-D ndarray` 

Finite Radon Transform array of (n+1) x n integer coefficients.

      See also

  
[`ifrt2`](#skimage.transform.ifrt2 "skimage.transform.ifrt2")


The two-dimensional inverse FRT.

    #### Notes

 The FRT has a unique inverse if and only if n is prime. [FRT] The idea for this algorithm is due to Vlad Negnevitski.

 #### 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)

   #### 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)

```
 
 hough\_circle
-------------

  
`skimage.transform.hough_circle(image, radius, normalize=True, full_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L72-L113)
 
Perform a circular Hough transform.

  Parameters 
 
`image(M, N) ndarray` 

Input image with nonzero values representing edges.

  
`radiusscalar or sequence of scalars` 

Radii at which to compute the Hough transform. Floats are converted to integers.

  
`normalizeboolean, optional (default True)` 

Normalize the accumulator with the number of pixels used to draw the radius.

  
`full_outputboolean, optional (default False)` 

Extend the output size by twice the largest radius in order to detect centers outside the input picture.

    Returns 
 
`H3D ndarray (radius index, (M + 2R, N + 2R) ndarray)` 

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
--------------------

  
`skimage.transform.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=inf, total_num_peaks=inf, normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L271-L377)
 
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(N, M) array` 

Hough spaces returned by the [`hough_circle`](#skimage.transform.hough_circle "skimage.transform.hough_circle") function.

  
`radii(M,) array` 

Radii corresponding to Hough spaces.

  
`min_xdistanceint, optional` 

Minimum distance separating centers in the x dimension.

  
`min_ydistanceint, optional` 

Minimum distance separating centers in the y dimension.

  
`thresholdfloat, optional` 

Minimum intensity of peaks in each Hough space. Default is `0.5 * max(hspace)`.

  
`num_peaksint, 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_peaksint, optional` 

Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` coordinates based on peak intensity.

  
`normalizebool, optional` 

If True, normalize the accumulator by the radius to sort the prominent peaks.

    Returns 
 
`accum, cx, cy, radtuple of array` 

Peak values in Hough space, x and y center coordinates and radii.

     #### 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.

 #### 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,])

```
 
 hough\_ellipse
--------------

  
`skimage.transform.hough_ellipse(image, threshold=4, accuracy=1, min_size=4, max_size=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L116-L165)
 
Perform an elliptical Hough transform.

  Parameters 
 
`image(M, N) ndarray` 

Input image with nonzero values representing edges.

  
`thresholdint, optional` 

Accumulator threshold value.

  
`accuracydouble, optional` 

Bin size on the minor axis used in the accumulator.

  
`min_sizeint, optional` 

Minimal major axis length.

  
`max_sizeint, optional` 

Maximal minor axis length. If None, the value is set to the half of the smaller image dimension.

    Returns 
 
`resultndarray 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 [`skimage.draw.ellipse_perimeter`](skimage.draw#skimage.draw.ellipse_perimeter "skimage.draw.ellipse_perimeter") convention.

     #### Notes

 The accuracy must be chosen to produce a peak in the accumulator distribution. In other words, a flat accumulator distribution with low values may be caused by a too low bin size.

 #### 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

   #### 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)]

```
 
 hough\_line
-----------

  
`skimage.transform.hough_line(image, theta=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L168-L223)
 
Perform a straight line Hough transform.

  Parameters 
 
`image(M, N) ndarray` 

Input image with nonzero values representing edges.

  
`theta1D ndarray of double, optional` 

Angles at which to compute the transform, in radians. Defaults to a vector of 180 angles evenly spaced from -pi/2 to pi/2.

    Returns 
 
`hspace2-D ndarray of uint64` 

Hough transform accumulator.

  
`anglesndarray` 

Angles at which the transform is computed, in radians.

  
`distancesndarray` 

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
>>> img += np.random.random(img.shape) > 0.95

```
 Apply the Hough transform:

 
```
>>> out, angles, d = hough_line(img)

```
 
```
import numpy as np
import matplotlib.pyplot as plt

from skimage.transform import hough_line
from skimage.draw import line

img = np.zeros((100, 150), dtype=bool)
img[30, :] = 1
img[:, 65] = 1
img[35:45, 35:50] = 1
rr, cc = line(60, 130, 80, 10)
img[rr, cc] = 1
img += np.random.random(img.shape) > 0.95

out, angles, d = hough_line(img)

fix, axes = plt.subplots(1, 2, figsize=(7, 4))

axes[0].imshow(img, cmap=plt.cm.gray)
axes[0].set_title('Input image')

axes[1].imshow(
    out, cmap=plt.cm.bone,
    extent=(np.rad2deg(angles[-1]), np.rad2deg(angles[0]), d[-1], d[0]))
axes[1].set_title('Hough transform')
axes[1].set_xlabel('Angle (degree)')
axes[1].set_ylabel('Distance (pixel)')

plt.tight_layout()
plt.show()

```
 ([Source code](https://scikit-image.org/docs/0.18.x/plots/hough_tf.py), [png](https://scikit-image.org/docs/0.18.x/plots/hough_tf.png), [pdf](https://scikit-image.org/docs/0.18.x/plots/hough_tf.pdf))

  ![../_images/hough_tf.png]  
 hough\_line\_peaks
------------------

  
`skimage.transform.hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, threshold=None, num_peaks=inf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L9-L69)
 
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(N, M) array` 

Hough space returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function.

  
`angles(M,) array` 

Angles returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function. Assumed to be continuous. (`angles[-1] - angles[0] == PI`).

  
`dists(N, ) array` 

Distances returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function.

  
`min_distanceint, optional` 

Minimum distance separating lines (maximum filter size for first dimension of hough space).

  
`min_angleint, optional` 

Minimum angle separating lines (maximum filter size for second dimension of hough space).

  
`thresholdfloat, optional` 

Minimum intensity of peaks. Default is `0.5 * max(hspace)`.

  
`num_peaksint, optional` 

Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` coordinates based on peak intensity.

    Returns 
 
`accum, angles, diststuple 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
-----

  
`skimage.transform.ifrt2(a)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/finite_radon_transform.py#L71-L134)
 
Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array.

  Parameters 
 
`aarray_like` 

A 2-D (n+1) row x n column integer array.

    Returns 
 
`iFRT2-D n x n ndarray` 

Inverse Finite Radon Transform array of n x n integer coefficients.

      See also

  
[`frt2`](#skimage.transform.frt2 "skimage.transform.frt2")


The two-dimensional FRT

    #### Notes

 The FRT has a unique inverse if and only if n is prime. See [[1]](#r3b76f892cb20-1) for an overview. The idea for this algorithm is due to Vlad Negnevitski.

 #### 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)

   #### 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

```
 
 integral\_image
---------------

  
`skimage.transform.integral_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/integral.py#L4-L33)
 
Integral image / summed area table.

 The integral image contains the sum of all elements above and to the left of it, i.e.:

  \[S[m, n] = \sum\_{i \leq m} \sum\_{j \leq n} X[i, j]\]  Parameters 
 
`imagendarray` 

Input image.

    Returns 
 
`Sndarray` 

Integral image/summed area table of same shape as input image.

     #### References

  
`1`  
F.C. Crow, “Summed-area tables for texture mapping,” ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212.

   
 integrate
---------

  
`skimage.transform.integrate(ii, start, end)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/integral.py#L36-L128)
 
Use an integral image to integrate over a given window.

  Parameters 
 
`iindarray` 

Integral image.

  
`startList 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,…), …]`.

  
`endList 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 
 
`Sscalar or ndarray` 

Integral (sum) over the given window(s).

     #### 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
------

  
`skimage.transform.iradon(radon_image, theta=None, output_size=None, filter_name='ramp', interpolation='linear', circle=True, preserve_range=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L184-L314)
 
Inverse radon transform.

 Reconstruct an image from the radon transform, using the filtered back projection algorithm.

  Parameters 
 
`radon_imagearray` 

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`.

  
`thetaarray_like, optional` 

Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)).

  
`output_sizeint, optional` 

Number of rows and columns in the reconstruction.

  
`filter_namestr, 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.

  
`interpolationstr, optional` 

Interpolation method used in reconstruction. Methods available: ‘linear’, ‘nearest’, and ‘cubic’ (‘cubic’ is slow).

  
`circleboolean, 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_rangebool, 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 
 
`reconstructedndarray` 

Reconstructed image. The rotation axis will be located in the pixel with indices `(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)`.

    Changed in version 0.19: In `iradon`, `filter` argument is deprecated in favor of `filter_name`.

    #### 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.

 #### 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

   
 iradon\_sart
------------

  
`skimage.transform.iradon_sart(radon_image, theta=None, image=None, projection_shifts=None, clip=None, relaxation=0.15, dtype=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L376-L515)
 
Inverse radon transform.

 Reconstruct an image from the radon transform, using a single iteration of the Simultaneous Algebraic Reconstruction Technique (SART) algorithm.

  Parameters 
 
`radon_image2D array` 

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`.

  
`theta1D array, optional` 

Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)).

  
`image2D array, optional` 

Image containing an initial reconstruction estimate. Shape of this array should be `(radon_image.shape[0], radon_image.shape[0])`. The default is an array of zeros.

  
`projection_shifts1D array, 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`.

  
`cliplength-2 sequence of floats, optional` 

Force all values in the reconstructed tomogram to lie in the range `[clip[0], clip[1]]`

  
`relaxationfloat, 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.

  
`dtypedtype, 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 
 
`reconstructedndarray` 

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
-----------------

  
`skimage.transform.matrix_transform(coords, matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1416-L1432)
 
Apply 2D matrix transform.

  Parameters 
 
`coords(N, 2) array` 

x, y coordinates to transform

  
`matrix(3, 3) array` 

Homogeneous transformation matrix.

    Returns 
 
`coords(N, 2) array` 

Transformed coordinates.

     
 order\_angles\_golden\_ratio
----------------------------

  
`skimage.transform.order_angles_golden_ratio(theta)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L317-L373)
 
Order angles to reduce the amount of correlated information in subsequent projections.

  Parameters 
 
`theta1D array of floats` 

Projection angles in degrees. Duplicate angles are not allowed.

    Returns 
 
`indices_generatorgenerator 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
--------------------------

  
`skimage.transform.probabilistic_hough_line(image, threshold=10, line_length=50, line_gap=10, theta=None, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L226-L268)
 
Return lines from a progressive probabilistic line Hough transform.

  Parameters 
 
`image(M, N) ndarray` 

Input image with nonzero values representing edges.

  
`thresholdint, optional` 

Threshold

  
`line_lengthint, optional` 

Minimum accepted length of detected lines. Increase the parameter to extract longer lines.

  
`line_gapint, optional` 

Maximum gap between pixels to still form a line. Increase the parameter to merge broken lines more aggressively.

  
`theta1D ndarray, dtype=double, optional` 

Angles at which to compute the transform, in radians. If None, use a range from -pi/2 to pi/2.

  
`seedint, optional` 

Seed to initialize the random number generator.

    Returns 
 
`lineslist` 

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
---------------

  
`skimage.transform.pyramid_expand(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L85-L142)
 
Upsample and then smooth image.

  Parameters 
 
`imagendarray` 

Input image.

  
`upscalefloat, optional` 

Upscale factor.

  
`sigmafloat, 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.

  
`orderint, optional` 

Order of splines used in interpolation of upsampling. See [`skimage.transform.warp`](#skimage.transform.warp "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’.

  
`cvalfloat, optional` 

Value to fill past edges of input if mode is ‘constant’.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`preserve_rangebool, 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 
 
`outarray` 

Upsampled and smoothed float image.

     #### References

  
`1`  
<http://persci.mit.edu/pub_pdfs/pyramid83.pdf>

   
 pyramid\_gaussian
-----------------

  
`skimage.transform.pyramid_gaussian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L145-L224)
 
Yield images of the Gaussian pyramid formed by the input image.

 Recursively applies the [`pyramid_reduce`](#skimage.transform.pyramid_reduce "skimage.transform.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 
 
`imagendarray` 

Input image.

  
`max_layerint, optional` 

Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers.

  
`downscalefloat, optional` 

Downscale factor.

  
`sigmafloat, 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.

  
`orderint, optional` 

Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "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’.

  
`cvalfloat, optional` 

Value to fill past edges of input if mode is ‘constant’.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`preserve_rangebool, 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 
 
`pyramidgenerator` 

Generator yielding pyramid layers as float images.

     #### References

  
`1`  
<http://persci.mit.edu/pub_pdfs/pyramid83.pdf>

   
 pyramid\_laplacian
------------------

  
`skimage.transform.pyramid_laplacian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L227-L317)
 
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 
 
`imagendarray` 

Input image.

  
`max_layerint, optional` 

Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers.

  
`downscalefloat, optional` 

Downscale factor.

  
`sigmafloat, 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.

  
`orderint, optional` 

Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "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’.

  
`cvalfloat, optional` 

Value to fill past edges of input if mode is ‘constant’.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`preserve_rangebool, 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 
 
`pyramidgenerator` 

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
---------------

  
`skimage.transform.pyramid_reduce(image, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L25-L82)
 
Smooth and then downsample image.

  Parameters 
 
`imagendarray` 

Input image.

  
`downscalefloat, optional` 

Downscale factor.

  
`sigmafloat, 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.

  
`orderint, optional` 

Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "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’.

  
`cvalfloat, optional` 

Value to fill past edges of input if mode is ‘constant’.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`preserve_rangebool, 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 
 
`outarray` 

Smoothed and downsampled float image.

     #### References

  
`1`  
<http://persci.mit.edu/pub_pdfs/pyramid83.pdf>

   
 radon
-----

  
`skimage.transform.radon(image, theta=None, circle=True, *, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L24-L115)
 
Calculates the radon transform of an image given specified projection angles.

  Parameters 
 
`imagearray_like` 

Input image. The rotation axis will be located in the pixel with indices `(image.shape[0] // 2, image.shape[1] // 2)`.

  
`thetaarray_like, optional` 

Projection angles (in degrees). If `None`, the value is set to np.arange(180).

  
`circleboolean, 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_rangebool, 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_imagendarray` 

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`.

     #### Notes

 Based on code of Justin K. Romberg (<https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html>)

 #### 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

   
 rescale
-------

  
`skimage.transform.rescale(image, scale, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, multichannel=False, anti_aliasing=None, anti_aliasing_sigma=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L201-L293)
 
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`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean").

  Parameters 
 
`imagendarray` 

Input image.

  
`scale{float, tuple of floats}` 

Scale factors. Separate scale factors can be defined as `(rows, cols[, …][, dim])`.

    Returns 
 
`scaledndarray` 

Scaled version of the input.

    Other Parameters 
 
`orderint, 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`](#skimage.transform.warp "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`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)").

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`clipbool, 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_rangebool, 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>

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`anti_aliasingbool, 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.

     #### 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
------

  
`skimage.transform.resize(image, output_shape, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L19-L198)
 
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 down-sampling with an integer factor also see [`skimage.transform.downscale_local_mean`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean").

  Parameters 
 
`imagendarray` 

Input image.

  
`output_shapetuple or ndarray` 

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 
 
`resizedndarray` 

Resized version of the input.

    Other Parameters 
 
`orderint, 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`](#skimage.transform.warp "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`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)").

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`clipbool, 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_rangebool, 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_aliasingbool, 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, 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)

```
 
 rotate
------

  
`skimage.transform.rotate(image, angle, resize=False, center=None, order=None, mode='constant', cval=0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L296-L404)
 
Rotate image by a certain angle around its center.

  Parameters 
 
`imagendarray` 

Input image.

  
`anglefloat` 

Rotation angle in degrees in counter-clockwise direction.

  
`resizebool, optional` 

Determine whether the shape of the output image will be automatically calculated, so the complete rotated image exactly fits. Default is False.

  
`centeriterable 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 
 
`rotatedndarray` 

Rotated version of the input.

    Other Parameters 
 
`orderint, 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`](#skimage.transform.warp "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`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)").

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`clipbool, 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_rangebool, 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)

```
 
 ### Examples using `skimage.transform.rotate`

 
 ![Different perimeters]

  

 ![Measure region properties]

   swirl
-----

  
`skimage.transform.swirl(image, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=None, mode='reflect', cval=0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L473-L534)
 
Perform a swirl transformation.

  Parameters 
 
`imagendarray` 

Input image.

  
`center(column, row) tuple or (2,) ndarray, optional` 

Center coordinate of transformation.

  
`strengthfloat, optional` 

The amount of swirling applied.

  
`radiusfloat, optional` 

The extent of the swirl in pixels. The effect dies out rapidly beyond `radius`.

  
`rotationfloat, optional` 

Additional rotation applied to the image.

    Returns 
 
`swirledndarray` 

Swirled version of the input.

    Other Parameters 
 
`output_shapetuple (rows, cols), optional` 

Shape of the output image generated. By default the shape of the input image is preserved.

  
`orderint, 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`](#skimage.transform.warp "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 ‘constant’ used as the default. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)").

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`clipbool, 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_rangebool, 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
----

  
`skimage.transform.warp(image, inverse_map, map_args={}, output_shape=None, order=None, mode='constant', cval=0.0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L684-L932)
 
Warp an image according to a given coordinate transformation.

  Parameters 
 
`imagendarray` 

Input image.

  
`inverse_maptransformation 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`](#skimage.transform.SimilarityTransform "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`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html#scipy.ndimage.map_coordinates "(in SciPy v1.5.4)") 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_argsdict, optional` 

Keyword arguments passed to `inverse_map`.

  
`output_shapetuple (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.

  
`orderint, 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`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)").

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`clipbool, 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_rangebool, 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 
 
`warpeddouble ndarray` 

The warped input image.

     #### Notes

 * The input image is converted to a `double` image.
* In case of a [`SimilarityTransform`](#skimage.transform.SimilarityTransform "skimage.transform.SimilarityTransform"), [`AffineTransform`](#skimage.transform.AffineTransform "skimage.transform.AffineTransform") and [`ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.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])
>>> cube = np.random.rand(*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)

```
 
 ### Examples using `skimage.transform.warp`

 
 ![Registration using optical flow]

   warp\_coords
------------

  
`skimage.transform.warp_coords(coord_map, shape, dtype=<class 'numpy.float64'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L560-L635)
 
Build the source coordinates for the output of a 2-D image warp.

  Parameters 
 
`coord_mapcallable 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.

  
`shapetuple` 

Shape of output image `(rows, cols[, bands])`.

  
`dtypenp.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`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html#scipy.ndimage.map_coordinates "(in SciPy v1.5.4)"), 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`](#skimage.transform.warp "skimage.transform.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`](#skimage.transform.warp "skimage.transform.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
-----------

  
`skimage.transform.warp_polar(image, center=None, *, radius=None, output_shape=None, scaling='linear', multichannel=False, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L997-L1095)
 
Remap image to polar or log-polar coordinates space.

  Parameters 
 
`imagendarray` 

Input image. Only 2-D arrays are accepted by default. If `multichannel=True`, 3-D arrays are accepted and the last axis is interpreted as multiple channels.

  
`centertuple (row, col), optional` 

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 the image.

  
`radiusfloat, optional` 

Radius of the circle that bounds the area to be transformed.

  
`output_shapetuple (row, col), optional` 

`scaling{‘linear’, ‘log’}, optional` 

Specify whether the image warp is polar or log-polar. Defaults to ‘linear’.

  
`multichannelbool, optional` 

Whether the image is a 3-D array in which the third axis is to be interpreted as multiple channels. If set to `False` (default), only 2-D arrays are accepted.

  
`**kwargskeyword arguments` 

Passed to `transform.warp`.

    Returns 
 
`warpedndarray` 

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', multichannel=True)

```
 
 AffineTransform
---------------

  
`class skimage.transform.AffineTransform(matrix=None, scale=None, rotation=None, shear=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L746-L844)
 
Bases: `skimage.transform._geometric.ProjectiveTransform`

 2D affine transformation.

 Has the following form:

 
```
X = a0*x + a1*y + a2 =
  = sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2

Y = b0*x + b1*y + b2 =
  = sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2

```
 where `sx` and `sy` are scale factors in the x and y directions, and the homogeneous transformation matrix is:

 
```
[[a0  a1  a2]
 [b0  b1  b2]
 [0   0    1]]

```
  Parameters 
 
`matrix(3, 3) array, optional` 

Homogeneous transformation matrix.

  
`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.

  New in version 0.17: Added support for supplying a single scalar value.

   
`rotationfloat, optional` 

Rotation angle in counter-clockwise direction as radians.

  
`shearfloat, optional` 

Shear angle in counter-clockwise direction as radians.

  
`translation(tx, ty) as array, list or tuple, optional` 

Translation parameters.

    Attributes 
 
`params(3, 3) array` 

Homogeneous transformation matrix.

      
`__init__(matrix=None, scale=None, rotation=None, shear=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L790-L825)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property rotation` 
  
`property scale` 
  
`property shear` 
  
`property translation` 
 
 EssentialMatrixTransform
------------------------

  
`class skimage.transform.EssentialMatrixTransform(rotation=None, translation=None, matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L399-L494)
 
Bases: `skimage.transform._geometric.FundamentalMatrixTransform`

 Essential matrix transformation.

 The essential matrix relates corresponding points between a pair of calibrated images. The matrix transforms normalized, homogeneous image points in one image to epipolar lines in the other image.

 The essential matrix is only defined for a pair of moving images capturing a non-planar scene. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images ([`ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")). If the intrinsic calibration of the images is unknown, the fundamental matrix describes the projective relation between the two images ([`FundamentalMatrixTransform`](#skimage.transform.FundamentalMatrixTransform "skimage.transform.FundamentalMatrixTransform")).

  Parameters 
 
`rotation(3, 3) array, optional` 

Rotation matrix of the relative camera motion.

  
`translation(3, 1) array, optional` 

Translation vector of the relative camera motion. The vector must have unit length.

  
`matrix(3, 3) array, optional` 

Essential matrix.

     #### References

  
`1`  
Hartley, Richard, and Andrew Zisserman. Multiple view geometry in computer vision. Cambridge university press, 2003.

    Attributes 
 
`params(3, 3) array` 

Essential matrix.

      
`__init__(rotation=None, translation=None, matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L435-L458)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L460-L494)
 
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` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
 
 EuclideanTransform
------------------

  
`class skimage.transform.EuclideanTransform(matrix=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L981-L1077)
 
Bases: `skimage.transform._geometric.ProjectiveTransform`

 2D Euclidean transformation.

 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.

  Parameters 
 
`matrix(3, 3) array, optional` 

Homogeneous transformation matrix.

  
`rotationfloat, optional` 

Rotation angle in counter-clockwise direction as radians.

  
`translation(tx, ty) as array, list or tuple, optional` 

x, y translation parameters.

    Attributes 
 
`params(3, 3) array` 

Homogeneous transformation matrix.

      
`__init__(matrix=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1018-L1043)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1045-L1069)
 
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` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`property rotation` 
  
`property translation` 
 
 FundamentalMatrixTransform
--------------------------

  
`class skimage.transform.FundamentalMatrixTransform(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L211-L396)
 
Bases: `skimage.transform._geometric.GeometricTransform`

 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`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")). If the intrinsic calibration of the images is known, the essential matrix describes the metric relation between the two images ([`EssentialMatrixTransform`](#skimage.transform.EssentialMatrixTransform "skimage.transform.EssentialMatrixTransform")).

  Parameters 
 
`matrix(3, 3) array, optional` 

Fundamental matrix.

     #### References

  
`1`  
Hartley, Richard, and Andrew Zisserman. Multiple view geometry in computer vision. Cambridge university press, 2003.

    Attributes 
 
`params(3, 3) array` 

Fundamental matrix.

      
`__init__(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L241-L247)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L335-L367)
 
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` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L266-L281)
 
Apply inverse transformation.

  Parameters 
 
`coords(N, 2) array` 

Destination coordinates.

    Returns 
 
`coords(N, 3) array` 

Epipolar lines in the source image.

     
  
`residuals(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L369-L396)
 
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.

     
 
 PiecewiseAffineTransform
------------------------

  
`class skimage.transform.PiecewiseAffineTransform` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L847-L978)
 
Bases: `skimage.transform._geometric.GeometricTransform`

 2D 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 
 
`affineslist of AffineTransform objects` 

Affine transformations for each triangle in the mesh.

  
`inverse_affineslist of AffineTransform objects` 

Inverse affine transformations for each triangle in the mesh.

      
`__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L863-L867)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L869-L908)
 
Estimate the transformation from a set of corresponding points.

 Number of source and destination coordinates must match.

  Parameters 
 
`src(N, 2) array` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L945-L978)
 
Apply inverse transformation.

 Coordinates outside of the mesh will be set to `- 1`.

  Parameters 
 
`coords(N, 2) array` 

Source coordinates.

    Returns 
 
`coords(N, 2) array` 

Transformed coordinates.

     
 
 PolynomialTransform
-------------------

  
`class skimage.transform.PolynomialTransform(params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1182-L1327)
 
Bases: `skimage.transform._geometric.GeometricTransform`

 2D polynomial transformation.

 Has the following form:

 
```
X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

```
  Parameters 
 
`params(2, N) array, 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, :]`.

      
`__init__(params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1204-L1210)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst, order=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1212-L1290)
 
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.

  Parameters 
 
`src(N, 2) array` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

  
`orderint, optional` 

Polynomial order (number of coefficients is order + 1).

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1322-L1327)
 
Apply inverse transformation.

  Parameters 
 
`coords(N, 2) array` 

Destination coordinates.

    Returns 
 
`coords(N, 2) array` 

Source coordinates.

     
 
 ProjectiveTransform
-------------------

  
`class skimage.transform.ProjectiveTransform(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L497-L743)
 
Bases: `skimage.transform._geometric.GeometricTransform`

 Projective transformation.

 Apply a projective transformation (homography) on coordinates.

 For each homogeneous coordinate \(\mathbf{x} = [x, y, 1]^T\), its target position is calculated by multiplying with the given matrix, \(H\), to give \(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(3, 3) array, optional` 

Homogeneous transformation matrix.

    Attributes 
 
`params(3, 3) array` 

Homogeneous transformation matrix.

      
`__init__(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L536-L542)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L596-L703)
 
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.

 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` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L580-L594)
 
Apply inverse transformation.

  Parameters 
 
`coords(N, 2) array` 

Destination coordinates.

    Returns 
 
`coords(N, 2) array` 

Source coordinates.

     
 
 SimilarityTransform
-------------------

  
`class skimage.transform.SimilarityTransform(matrix=None, scale=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1080-L1179)
 
Bases: `skimage.transform._geometric.EuclideanTransform`

 2D similarity transformation.

 Has the following form:

 
```
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(3, 3) array, optional` 

Homogeneous transformation matrix.

  
`scalefloat, optional` 

Scale factor.

  
`rotationfloat, optional` 

Rotation angle in counter-clockwise direction as radians.

  
`translation(tx, ty) as array, list or tuple, optional` 

x, y translation parameters.

    Attributes 
 
`params(3, 3) array` 

Homogeneous transformation matrix.

      
`__init__(matrix=None, scale=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1119-L1148)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1150-L1174)
 
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` 

Source coordinates.

  
`dst(N, 2) array` 

Destination coordinates.

    Returns 
 
`successbool` 

True, if model estimation succeeds.

     
  
`property scale` 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.transform.html>

Module: future.graph
====================

 

|  |  |
| --- | --- |
| [`skimage.future.graph.cut_normalized`](#skimage.future.graph.cut_normalized "skimage.future.graph.cut_normalized")(labels, rag) | Perform Normalized Graph cut on the Region Adjacency Graph. |
| [`skimage.future.graph.cut_threshold`](#skimage.future.graph.cut_threshold "skimage.future.graph.cut_threshold")(labels, …) | Combine regions separated by weight less than threshold. |
| [`skimage.future.graph.merge_hierarchical`](#skimage.future.graph.merge_hierarchical "skimage.future.graph.merge_hierarchical")(…) | Perform hierarchical merging of a RAG. |
| [`skimage.future.graph.ncut`](#skimage.future.graph.ncut "skimage.future.graph.ncut")(labels, rag[, …]) | Perform Normalized Graph cut on the Region Adjacency Graph. |
| [`skimage.future.graph.rag_boundary`](#skimage.future.graph.rag_boundary "skimage.future.graph.rag_boundary")(labels, …) | Comouter RAG based on region boundaries |
| [`skimage.future.graph.rag_mean_color`](#skimage.future.graph.rag_mean_color "skimage.future.graph.rag_mean_color")(image, …) | Compute the Region Adjacency Graph using mean colors. |
| [`skimage.future.graph.show_rag`](#skimage.future.graph.show_rag "skimage.future.graph.show_rag")(labels, rag, image) | Show a Region Adjacency Graph on an image. |
| [`skimage.future.graph.RAG`](#skimage.future.graph.RAG "skimage.future.graph.RAG")([label\_image, …]) | The Region Adjacency Graph (RAG) of an image, subclasses [networx.Graph](http://networkx.github.io/documentation/latest/reference/classes/graph.html) |

 cut\_normalized
---------------

  
`skimage.future.graph.cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True, max_edge=1.0, *, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L73-L145)
 
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 
 
`labelsndarray` 

The array of labels.

  
`ragRAG` 

The region adjacency graph.

  
`threshfloat` 

The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds `thresh`.

  
`num_cutsint` 

The number or N-cuts to perform before determining the optimal one.

  
`in_placebool` 

If set, modifies `rag` in place. For each node `n` the function will set a new attribute `rag.nodes[n]['ncut label']`.

  
`max_edgefloat, 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.

  
`random_stateint, RandomState instance or None, optional` 

If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used for the starting point of [`scipy.sparse.linalg.eigsh`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html#scipy.sparse.linalg.eigsh "(in SciPy v1.5.4)").

    Returns 
 
`outndarray` 

The new labeled array.

     #### 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.

   #### Examples

 
```
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels, mode='similarity')
>>> new_labels = graph.cut_normalized(labels, rag)

```
 
 cut\_threshold
--------------

  
`skimage.future.graph.cut_threshold(labels, rag, thresh, in_place=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L9-L70)
 
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 
 
`labelsndarray` 

The array of labels.

  
`ragRAG` 

The region adjacency graph.

  
`threshfloat` 

The threshold. Regions connected by edges with smaller weights are combined.

  
`in_placebool` 

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 
 
`outndarray` 

The new labelled array.

     #### References

  
`1`  
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” [DOI:10.1109/83.841950](https://doi.org/10.1109/83.841950)

   #### Examples

 
```
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
>>> new_labels = graph.cut_threshold(labels, rag, 10)

```
 
 merge\_hierarchical
-------------------

  
`skimage.future.graph.merge_hierarchical(labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_merge.py#L59-L137)
 
Perform hierarchical merging of a RAG.

 Greedily merges the most similar pair of nodes until no edges lower than `thresh` remain.

  Parameters 
 
`labelsndarray` 

The array of labels.

  
`ragRAG` 

The Region Adjacency Graph.

  
`threshfloat` 

Regions connected by an edge with weight smaller than `thresh` are merged.

  
`rag_copybool` 

If set, the RAG copied before modifying.

  
`in_place_mergebool` 

If set, the nodes are merged in place. Otherwise, a new node is created for each merge..

  
`merge_funccallable` 

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_funccallable` 

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 
 
`outndarray` 

The new labeled array.

     
 ncut
----

  
`skimage.future.graph.ncut(labels, rag, thresh=0.001, num_cuts=10, in_place=True, max_edge=1.0, *, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L73-L145)
 
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 
 
`labelsndarray` 

The array of labels.

  
`ragRAG` 

The region adjacency graph.

  
`threshfloat` 

The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds `thresh`.

  
`num_cutsint` 

The number or N-cuts to perform before determining the optimal one.

  
`in_placebool` 

If set, modifies `rag` in place. For each node `n` the function will set a new attribute `rag.nodes[n]['ncut label']`.

  
`max_edgefloat, 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.

  
`random_stateint, RandomState instance or None, optional` 

If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used for the starting point of [`scipy.sparse.linalg.eigsh`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html#scipy.sparse.linalg.eigsh "(in SciPy v1.5.4)").

    Returns 
 
`outndarray` 

The new labeled array.

     #### 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.

   #### Examples

 
```
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels, mode='similarity')
>>> new_labels = graph.cut_normalized(labels, rag)

```
 
 rag\_boundary
-------------

  
`skimage.future.graph.rag_boundary(labels, edge_map, connectivity=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L385-L446)
 
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.

  
`labelsndarray` 

The labelled image.

  
`edge_mapndarray` 

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.

  
`connectivityint, 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.filters.generate_binary_structure`.

   #### Examples

 
```
>>> from skimage import data, segmentation, filters, color
>>> from skimage.future import 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
----------------

  
`skimage.future.graph.rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L295-L382)
 
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 
 
`imagendarray, shape(M, N, […, P,] 3)` 

Input image.

  
`labelsndarray, 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)`.

  
`connectivityint, 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 \(|c\_1 - c\_2|\), where \(c\_1\) and \(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 \(e^{-d^2/sigma}\) where \(d=|c\_1 - c\_2|\), where \(c\_1\) and \(c\_2\) are the mean colors of the two regions. It represents how similar two regions are.

  
`sigmafloat, 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 
 
`outRAG` 

The region adjacency graph.

     #### References

  
`1`  
Alain Tremeau and Philippe Colantoni “Regions Adjacency Graph Applied To Color Image Segmentation” [DOI:10.1109/83.841950](https://doi.org/10.1109/83.841950)

   #### Examples

 
```
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)

```
 
 show\_rag
---------

  
`skimage.future.graph.show_rag(labels, rag, image, border_color='black', edge_width=1.5, edge_cmap='magma', img_cmap='bone', in_place=True, ax=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L449-L558)
 
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 
 
`labelsndarray, shape (M, N)` 

The labelled image.

  
`ragRAG` 

The Region Adjacency Graph.

  
`imagendarray, shape (M, N[, 3])` 

Input image. If `colormap` is `None`, the image should be in RGB format.

  
`border_colorcolor spec, optional` 

Color with which the borders between regions are drawn.

  
`edge_widthfloat, optional` 

The thickness with which the RAG edges are drawn.

  
`edge_cmapmatplotlib.colors.Colormap, optional` 

Any matplotlib colormap with which the edges are drawn.

  
`img_cmapmatplotlib.colors.Colormap, optional` 

Any matplotlib colormap with which the image is draw. If set to `None` the image is drawn as it is.

  
`in_placebool, optional` 

If set, the RAG is modified in place. For each node `n` the function will set a new attribute `rag.nodes[n]['centroid']`.

  
`axmatplotlib.axes.Axes, optional` 

The axes to draw on. If not specified, new axes are created and drawn on.

    Returns 
 
`lcmatplotlib.collections.LineCollection` 

A colection of lines that represent the edges of the graph. It can be passed to the [`matplotlib.figure.Figure.colorbar()`](https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.colorbar "(in Matplotlib v3.3.3)") function.

     #### Examples

 
```
>>> from skimage import data, segmentation
>>> from skimage.future import 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)

```
 
 RAG
---

  
`class skimage.future.graph.RAG(label_image=None, connectivity=1, data=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L107-L292)
 
Bases: `networkx.classes.graph.Graph`

 The Region Adjacency Graph (RAG) of an image, subclasses [networx.Graph](http://networkx.github.io/documentation/latest/reference/classes/graph.html)

  Parameters 
 
`label_imagearray 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.

  
`connectivityint 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 [`scipy.ndimage.generate_binary_structure`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generate_binary_structure.html#scipy.ndimage.generate_binary_structure "(in SciPy v1.5.4)").

  
`datanetworkx Graph specification, optional` 

Initial or additional edges to pass to the NetworkX Graph constructor. See `networkx.Graph`. Valid edge specifications include edge list (list of tuples), NumPy arrays, and SciPy sparse matrices.

  
`**attrkeyword arguments, optional` 

Additional attributes to add to the graph.

      
`__init__(label_image=None, connectivity=1, data=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L133-L158)
 
Initialize a graph with edges, name, or graph attributes.

  Parameters 
 
`incoming_graph_datainput 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 NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

  
`attrkeyword 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(u, v, attr_dict=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L233-L242)
 
Add an edge between `u` and `v` while updating max node id.

  See also

 `networkx.Graph.add_edge()`.

  
  
`add_node(n, attr_dict=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L222-L231)
 
Add node `n` while updating the maximum node id.

  See also

 `networkx.Graph.add_node()`.

  
  
`copy()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L244-L250)
 
Copy the graph with its max node id.

  See also

 `networkx.Graph.copy()`.

  
  
`fresh_copy()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L252-L272)
 
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(src, dst, weight_func=<function min_weight>, in_place=True, extra_arguments=[], extra_keywords={})` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L160-L220)
 
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, dstint` 

Nodes to be merged.

  
`weight_funccallable, 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 `networkx.Graph`. It is expected to return a dict of attributes of the resulting edge.

  
`in_placebool, optional` 

If set to `True`, the merged node has the id `dst`, else merged node has a new id which is returned.

  
`extra_argumentssequence, optional` 

The sequence of extra positional arguments passed to `weight_func`.

  
`extra_keywordsdictionary, optional` 

The dict of keyword arguments passed to the `weight_func`.

    Returns 
 
`idint` 

The id of the new node.

     #### Notes

 If `in_place` is `False` the resulting node has a new id, rather than `dst`.

 
  
`next_id()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L274-L284)
 
Returns the `id` for the new node to be inserted.

 The current implementation returns one more than the maximum `id`.

  Returns 
 
`idint` 

The `id` of the new node to be inserted.

     
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.future.graph.html>

Module: data
============

 Standard test images.

 For more images, see

 * <http://sipi.usc.edu/database/database.php>

 

|  |  |
| --- | --- |
| [`skimage.data.astronaut`](#skimage.data.astronaut "skimage.data.astronaut")() | Color image of the astronaut Eileen Collins. |
| [`skimage.data.binary_blobs`](#skimage.data.binary_blobs "skimage.data.binary_blobs")([length, …]) | Generate synthetic binary image with several rounded blob-like objects. |
| [`skimage.data.brain`](#skimage.data.brain "skimage.data.brain")() | Subset of data from the University of North Carolina Volume Rendering Test Data Set. |
| [`skimage.data.brick`](#skimage.data.brick "skimage.data.brick")() | Brick wall. |
| [`skimage.data.camera`](#skimage.data.camera "skimage.data.camera")() | Gray-level “camera” image. |
| [`skimage.data.cat`](#skimage.data.cat "skimage.data.cat")() | Chelsea the cat. |
| [`skimage.data.cell`](#skimage.data.cell "skimage.data.cell")() | Cell floating in saline. |
| [`skimage.data.cells3d`](#skimage.data.cells3d "skimage.data.cells3d")() | 3D fluorescence microscopy image of cells. |
| [`skimage.data.checkerboard`](#skimage.data.checkerboard "skimage.data.checkerboard")() | Checkerboard image. |
| [`skimage.data.chelsea`](#skimage.data.chelsea "skimage.data.chelsea")() | Chelsea the cat. |
| [`skimage.data.clock`](#skimage.data.clock "skimage.data.clock")() | Motion blurred clock. |
| [`skimage.data.coffee`](#skimage.data.coffee "skimage.data.coffee")() | Coffee cup. |
| [`skimage.data.coins`](#skimage.data.coins "skimage.data.coins")() | Greek coins from Pompeii. |
| [`skimage.data.colorwheel`](#skimage.data.colorwheel "skimage.data.colorwheel")() | Color Wheel. |
| [`skimage.data.download_all`](#skimage.data.download_all "skimage.data.download_all")([directory]) | Download all datasets for use with scikit-image offline. |
| [`skimage.data.eagle`](#skimage.data.eagle "skimage.data.eagle")() | A golden eagle. |
| [`skimage.data.grass`](#skimage.data.grass "skimage.data.grass")() | Grass. |
| [`skimage.data.gravel`](#skimage.data.gravel "skimage.data.gravel")() | Gravel |
| [`skimage.data.horse`](#skimage.data.horse "skimage.data.horse")() | Black and white silhouette of a horse. |
| [`skimage.data.hubble_deep_field`](#skimage.data.hubble_deep_field "skimage.data.hubble_deep_field")() | Hubble eXtreme Deep Field. |
| [`skimage.data.human_mitosis`](#skimage.data.human_mitosis "skimage.data.human_mitosis")() | Image of human cells undergoing mitosis. |
| [`skimage.data.immunohistochemistry`](#skimage.data.immunohistochemistry "skimage.data.immunohistochemistry")() | Immunohistochemical (IHC) staining with hematoxylin counterstaining. |
| [`skimage.data.kidney`](#skimage.data.kidney "skimage.data.kidney")() | Mouse kidney tissue. |
| [`skimage.data.lbp_frontal_face_cascade_filename`](#skimage.data.lbp_frontal_face_cascade_filename "skimage.data.lbp_frontal_face_cascade_filename")() | Return the path to the XML file containing the weak classifier cascade. |
| [`skimage.data.lfw_subset`](#skimage.data.lfw_subset "skimage.data.lfw_subset")() | Subset of data from the LFW dataset. |
| [`skimage.data.lily`](#skimage.data.lily "skimage.data.lily")() | Lily of the valley plant stem. |
| [`skimage.data.logo`](#skimage.data.logo "skimage.data.logo")() | Scikit-image logo, a RGBA image. |
| [`skimage.data.microaneurysms`](#skimage.data.microaneurysms "skimage.data.microaneurysms")() | Gray-level “microaneurysms” image. |
| [`skimage.data.moon`](#skimage.data.moon "skimage.data.moon")() | Surface of the moon. |
| [`skimage.data.page`](#skimage.data.page "skimage.data.page")() | Scanned page. |
| [`skimage.data.retina`](#skimage.data.retina "skimage.data.retina")() | Human retina. |
| [`skimage.data.rocket`](#skimage.data.rocket "skimage.data.rocket")() | Launch photo of DSCOVR on Falcon 9 by SpaceX. |
| [`skimage.data.shepp_logan_phantom`](#skimage.data.shepp_logan_phantom "skimage.data.shepp_logan_phantom")() | Shepp Logan Phantom. |
| [`skimage.data.skin`](#skimage.data.skin "skimage.data.skin")() | Microscopy image of dermis and epidermis (skin layers). |
| [`skimage.data.stereo_motorcycle`](#skimage.data.stereo_motorcycle "skimage.data.stereo_motorcycle")() | Rectified stereo image pair with ground-truth disparities. |
| [`skimage.data.text`](#skimage.data.text "skimage.data.text")() | Gray-level “text” image used for corner detection. |

 astronaut
---------

  
`skimage.data.astronaut()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L394-L413)
 
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.

     
 ### Examples using `skimage.data.astronaut`

 
 ![Flood Fill]

   binary\_blobs
-------------

  
`skimage.data.binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/_binary_blobs.py#L4-L57)
 
Generate synthetic binary image with several rounded blob-like objects.

  Parameters 
 
`lengthint, optional` 

Linear size of output image.

  
`blob_size_fractionfloat, optional` 

Typical linear size of blob, as a fraction of `length`, should be smaller than 1.

  
`n_dimint, optional` 

Number of dimensions of output image.

  
`volume_fractionfloat, default 0.5` 

Fraction of image pixels covered by the blobs (where the output is 1). Should be in [0, 1].

  
`seedint, optional` 

Seed to initialize the random number generator. If `None`, a random seed from the operating system is used.

    Returns 
 
`blobsndarray of bools` 

Output binary image

     #### Examples

 
```
>>> from skimage import data
>>> data.binary_blobs(length=5, blob_size_fraction=0.2, seed=1)
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
-----

  
`skimage.data.brain()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1162-L1181)
 
Subset of data from the University of North Carolina Volume Rendering Test Data Set.

 The full dataset is available at [[1]](#r77fa297eebeb-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/>

   
 ### Examples using `skimage.data.brain`

 
 ![Local Histogram Equalization]

  

 ![Rank filters]

   brick
-----

  
`skimage.data.brick()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L416-L479)
 
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
------

  
`skimage.data.camera()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L351-L373)
 
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).

  Changed in version 0.18: This image was replaced due to copyright restrictions. For more information, please see [[1]](#r2f100140753e-1).

  #### References

  
`1`  
<https://github.com/scikit-image/scikit-image/issues/3927>

   
 ### Examples using `skimage.data.camera`

 
 ![Tinting gray-scale images]

  

 ![Masked Normalized Cross-Correlation]

  

 ![Entropy]

  

 ![GLCM Texture Features]

  

 ![Multi-Otsu Thresholding]

  

 ![Flood Fill]

  

 ![Rank filters]

   cat
---

  
`skimage.data.cat()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L902-L917)
 
Chelsea the cat.

 An example with texture, prominent edges in horizontal and diagonal directions, as well as features of differing scales.

  Returns 
 
`chelsea(300, 451, 3) uint8 ndarray` 

Chelsea image.

     #### Notes

 No copyright restrictions. CC0 by the photographer (Stefan van der Walt).

 
 cell
----

  
`skimage.data.cell()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L677-L705)
 
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]](#r02365d02e4e0-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](https://doi.org/10.1364/OE.26.010729)

   
 cells3d
-------

  
`skimage.data.cells3d()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L619-L645)
 
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)`.

 
 ### Examples using `skimage.data.cells3d`

 
 ![3D adaptive histogram equalization]

  

 ![Use rolling-ball algorithm for estimating background intensity]

  

 ![Explore 3D images (of cells)]

   checkerboard
------------

  
`skimage.data.checkerboard()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L604-L616)
 
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.

     
 ### Examples using `skimage.data.checkerboard`

 
 ![Flood Fill]

   chelsea
-------

  
`skimage.data.chelsea()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L902-L917)
 
Chelsea the cat.

 An example with texture, prominent edges in horizontal and diagonal directions, as well as features of differing scales.

  Returns 
 
`chelsea(300, 451, 3) uint8 ndarray` 

Chelsea image.

     #### Notes

 No copyright restrictions. CC0 by the photographer (Stefan van der Walt).

 
 ### Examples using `skimage.data.chelsea`

 
 ![Phase Unwrapping]

  

 ![Flood Fill]

   clock
-----

  
`skimage.data.clock()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L865-L879)
 
Motion blurred clock.

 This photograph of a wall clock was taken while moving the camera in an aproximately 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
------

  
`skimage.data.coffee()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L924-L940)
 
Coffee cup.

 This photograph is courtesy of Pikolo Espresso Bar. It contains several elliptical shapes as well as varying texture (smooth porcelain to course wood grain).

  Returns 
 
`coffee(400, 600, 3) uint8 ndarray` 

Coffee image.

     #### Notes

 No copyright restrictions. CC0 by the photographer (Rachel Michetti).

 
 coins
-----

  
`skimage.data.coins()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L708-L730)
 
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.

  Returns 
 
`coins(303, 384) uint8 ndarray` 

Coins image.

     #### Notes

 This image was downloaded from the [Brooklyn Museum Collection](https://www.brooklynmuseum.org/opencollection/archives/image/51611).

 No known copyright restrictions.

 
 ### Examples using `skimage.data.coins`

 
 ![Finding local maxima]

  

 ![Measure region properties]

  

 ![Use rolling-ball algorithm for estimating background intensity]

   colorwheel
----------

  
`skimage.data.colorwheel()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1011-L1019)
 
Color Wheel.

  Returns 
 
`colorwheel(370, 371, 3) uint8 image` 

A colorwheel.

     
 download\_all
-------------

  
`skimage.data.download_all(directory=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L263-L312)
 
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/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
-----

  
`skimage.data.eagle()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L376-L391)
 
A golden eagle.

 Suitable for examples on segmentation, Hough transforms, and corner detection.

  Returns 
 
`eagle(2019, 1826) uint8 ndarray` 

Eagle image.

     #### Notes

 No copyright restrictions. CC0 by the photographer (Dayane Machado).

 
 ### Examples using `skimage.data.eagle`

 
 ![Markers for watershed transform]

   grass
-----

  
`skimage.data.grass()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L482-L527)
 
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 underthe 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
------

  
`skimage.data.gravel()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L530-L582)
 
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
-----

  
`skimage.data.horse()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L849-L862)
 
Black and white silhouette of a horse.

 This image was downloaded from `openclipart`

 No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)).

  Returns 
 
`horse(328, 400) bool ndarray` 

Horse image.

     
 hubble\_deep\_field
-------------------

  
`skimage.data.hubble_deep_field()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L943-L964)
 
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.

  Returns 
 
`hubble_deep_field(872, 1000, 3) uint8 ndarray` 

Hubble deep field image.

     #### 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).

 
 human\_mitosis
--------------

  
`skimage.data.human_mitosis()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L648-L674)
 
Image of human cells undergoing mitosis.

  Returns 
 human\_mitosis: (512, 512) uint8 ndimage

Data of human cells undergoing mitosis taken during the preperation of the manuscript in [[1]](#r2b0a1772c690-1).

     #### Notes

 Copyright David Root. Licensed under CC-0 [[2]](#r2b0a1772c690-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>

   
 ### Examples using `skimage.data.human_mitosis`

 
 ![Segment human cells (in mitosis)]

   immunohistochemistry
--------------------

  
`skimage.data.immunohistochemistry()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L882-L899)
 
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
------

  
`skimage.data.kidney()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L733-L755)
 
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.

  Returns 
 
`kidney(16, 512, 512, 3) uint16 ndarray` 

Kidney 3D multichannel image.

     #### Notes

 This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in 2018. License: CC0

 
 lbp\_frontal\_face\_cascade\_filename
-------------------------------------

  
`skimage.data.lbp_frontal_face_cascade_filename()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L315-L327)
 
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]](#rde45415ad1b5-1).

 #### References

  
`1`  
OpenCV lbpcascade trained files <https://github.com/opencv/opencv/tree/master/data/lbpcascades>

   
 lfw\_subset
-----------

  
`skimage.data.lfw_subset()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1106-L1135)
 
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]](#r9c6d6b06eb8d-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/>

   
 ### Examples using `skimage.data.lfw_subset`

 
 ![Specific images]

   lily
----

  
`skimage.data.lily()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L758-L779)
 
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.

  Returns 
 
`lily(922, 922, 4) uint16 ndarray` 

Lily 2D multichannel image.

     #### Notes

 This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in 2018. License: CC0

 
 logo
----

  
`skimage.data.logo()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L782-L790)
 
Scikit-image logo, a RGBA image.

  Returns 
 
`logo(500, 500, 4) uint8 ndarray` 

Logo image.

     
 microaneurysms
--------------

  
`skimage.data.microaneurysms()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L793-L818)
 
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/>

  Returns 
 
`microaneurysms(102, 102) uint8 ndarray` 

Retina image with lesions.

     #### Notes

 No copyright restrictions. CC0 given by owner (Andreas Maier).

 #### 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](https://doi.org/10.1155/2013/154860)

   
 moon
----

  
`skimage.data.moon()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L821-L832)
 
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.

     
 ### Examples using `skimage.data.moon`

 
 ![Local Histogram Equalization]

   page
----

  
`skimage.data.page()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L835-L846)
 
Scanned page.

 This image of printed text is useful for demonstrations requiring uneven background illumination.

  Returns 
 
`page(191, 384) uint8 ndarray` 

Page image.

     
 ### Examples using `skimage.data.page`

 
 ![Use rolling-ball algorithm for estimating background intensity]

  

 ![Rank filters]

   retina
------

  
`skimage.data.retina()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L967-L991)
 
Human retina.

 This image of a retina is useful for demonstrations requiring circular images.

  Returns 
 
`retina(1411, 1411, 3) uint8 ndarray` 

Retina image in RGB.

     #### Notes

 This image was downloaded from `wikimedia`. This file is made available under the Creative Commons CC0 1.0 Universal Public Domain Dedication.

 #### References

  
`1`  
Häggström, Mikael (2014). “Medical gallery of Mikael Häggström 2014”. WikiJournal of Medicine 1 (2). [DOI:10.15347/wjm/2014.008](https://doi.org/10.15347/wjm/2014.008). ISSN 2002-4436. Public Domain

   
 rocket
------

  
`skimage.data.rocket()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1022-L1042)
 
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.

  Returns 
 
`rocket(427, 640, 3) uint8 ndarray` 

Rocket image.

     #### 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/).

 
 shepp\_logan\_phantom
---------------------

  
`skimage.data.shepp_logan_phantom()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L994-L1008)
 
Shepp Logan Phantom.

  Returns 
 
`phantom(400, 400) float64 image` 

Image of the Shepp-Logan phantom in grayscale.

     #### 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](https://doi.org/10.1109/TNS.1974.6499235)

   
 skin
----

  
`skimage.data.skin()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1138-L1159)
 
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.

  Returns 
 
`skin(960, 1280, 3) RGB image of uint8` 
   #### 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.

 
 ### Examples using `skimage.data.skin`

 
 ![Trainable segmentation using local features and random forests]

   stereo\_motorcycle
------------------

  
`skimage.data.stereo_motorcycle()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1045-L1103)
 
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]](#re12479cea6aa-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`](skimage.transform#skimage.transform.downscale_local_mean "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]](#re12479cea6aa-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/>

   
 ### Examples using `skimage.data.stereo_motorcycle`

 
 ![Specific images]

  

 ![Registration using optical flow]

   text
----

  
`skimage.data.text()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L585-L601)
 
Gray-level “text” image used for corner detection.

  Returns 
 
`text(172, 448) uint8 ndarray` 

Text image.

     #### Notes

 This image was downloaded from Wikipedia <<https://en.wikipedia.org/wiki/File:Corner.png>>`\_\_.

 No known copyright restrictions, released into the public domain.

 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.data.html>

Module: feature
===============

 

|  |  |
| --- | --- |
| [`skimage.feature.blob_dog`](#skimage.feature.blob_dog "skimage.feature.blob_dog")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. |
| [`skimage.feature.blob_doh`](#skimage.feature.blob_doh "skimage.feature.blob_doh")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. |
| [`skimage.feature.blob_log`](#skimage.feature.blob_log "skimage.feature.blob_log")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. |
| [`skimage.feature.canny`](#skimage.feature.canny "skimage.feature.canny")(image[, sigma, …]) | Edge filter an image using the Canny algorithm. |
| [`skimage.feature.corner_fast`](#skimage.feature.corner_fast "skimage.feature.corner_fast")(image[, n, …]) | Extract FAST corners for a given image. |
| [`skimage.feature.corner_foerstner`](#skimage.feature.corner_foerstner "skimage.feature.corner_foerstner")(image[, sigma]) | Compute Foerstner corner measure response image. |
| [`skimage.feature.corner_harris`](#skimage.feature.corner_harris "skimage.feature.corner_harris")(image[, …]) | Compute Harris corner measure response image. |
| [`skimage.feature.corner_kitchen_rosenfeld`](#skimage.feature.corner_kitchen_rosenfeld "skimage.feature.corner_kitchen_rosenfeld")(image) | Compute Kitchen and Rosenfeld corner measure response image. |
| [`skimage.feature.corner_moravec`](#skimage.feature.corner_moravec "skimage.feature.corner_moravec")(image[, …]) | Compute Moravec corner measure response image. |
| [`skimage.feature.corner_orientations`](#skimage.feature.corner_orientations "skimage.feature.corner_orientations")(image, …) | Compute the orientation of corners. |
| [`skimage.feature.corner_peaks`](#skimage.feature.corner_peaks "skimage.feature.corner_peaks")(image[, …]) | Find peaks in corner measure response image. |
| [`skimage.feature.corner_shi_tomasi`](#skimage.feature.corner_shi_tomasi "skimage.feature.corner_shi_tomasi")(image[, sigma]) | Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. |
| [`skimage.feature.corner_subpix`](#skimage.feature.corner_subpix "skimage.feature.corner_subpix")(image, corners) | Determine subpixel position of corners. |
| [`skimage.feature.daisy`](#skimage.feature.daisy "skimage.feature.daisy")(image[, step, radius, …]) | Extract DAISY feature descriptors densely for the given image. |
| [`skimage.feature.draw_haar_like_feature`](#skimage.feature.draw_haar_like_feature "skimage.feature.draw_haar_like_feature")(…) | Visualization of Haar-like features. |
| [`skimage.feature.draw_multiblock_lbp`](#skimage.feature.draw_multiblock_lbp "skimage.feature.draw_multiblock_lbp")(image, …) | Multi-block local binary pattern visualization. |
| [`skimage.feature.greycomatrix`](#skimage.feature.greycomatrix "skimage.feature.greycomatrix")(image, …[, …]) | Calculate the grey-level co-occurrence matrix. |
| [`skimage.feature.greycoprops`](#skimage.feature.greycoprops "skimage.feature.greycoprops")(P[, prop]) | Calculate texture properties of a GLCM. |
| [`skimage.feature.haar_like_feature`](#skimage.feature.haar_like_feature "skimage.feature.haar_like_feature")(int\_image, …) | Compute the Haar-like features for a region of interest (ROI) of an integral image. |
| [`skimage.feature.haar_like_feature_coord`](#skimage.feature.haar_like_feature_coord "skimage.feature.haar_like_feature_coord")(…) | Compute the coordinates of Haar-like features. |
| [`skimage.feature.hessian_matrix`](#skimage.feature.hessian_matrix "skimage.feature.hessian_matrix")(image[, …]) | Compute Hessian matrix. |
| [`skimage.feature.hessian_matrix_det`](#skimage.feature.hessian_matrix_det "skimage.feature.hessian_matrix_det")(image[, …]) | Compute the approximate Hessian Determinant over an image. |
| [`skimage.feature.hessian_matrix_eigvals`](#skimage.feature.hessian_matrix_eigvals "skimage.feature.hessian_matrix_eigvals")(H\_elems) | Compute eigenvalues of Hessian matrix. |
| [`skimage.feature.hog`](#skimage.feature.hog "skimage.feature.hog")(image[, orientations, …]) | Extract Histogram of Oriented Gradients (HOG) for a given image. |
| [`skimage.feature.local_binary_pattern`](#skimage.feature.local_binary_pattern "skimage.feature.local_binary_pattern")(image, P, R) | Gray scale and rotation invariant LBP (Local Binary Patterns). |
| [`skimage.feature.masked_register_translation`](#skimage.feature.masked_register_translation "skimage.feature.masked_register_translation")(…) | **Deprecated function**. |
| [`skimage.feature.match_descriptors`](#skimage.feature.match_descriptors "skimage.feature.match_descriptors")(…[, …]) | Brute-force matching of descriptors. |
| [`skimage.feature.match_template`](#skimage.feature.match_template "skimage.feature.match_template")(image, template) | Match a template to a 2-D or 3-D image using normalized correlation. |
| [`skimage.feature.multiblock_lbp`](#skimage.feature.multiblock_lbp "skimage.feature.multiblock_lbp")(int\_image, r, …) | Multi-block local binary pattern (MB-LBP). |
| [`skimage.feature.multiscale_basic_features`](#skimage.feature.multiscale_basic_features "skimage.feature.multiscale_basic_features")(image) | Local features for a single- or multi-channel nd image. |
| [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max")(image[, …]) | Find peaks in an image as coordinate list or boolean mask. |
| [`skimage.feature.plot_matches`](#skimage.feature.plot_matches "skimage.feature.plot_matches")(ax, image1, …) | Plot matched features. |
| [`skimage.feature.register_translation`](#skimage.feature.register_translation "skimage.feature.register_translation")(…[, …]) | **Deprecated function**. |
| [`skimage.feature.shape_index`](#skimage.feature.shape_index "skimage.feature.shape_index")(image[, sigma, …]) | Compute the shape index. |
| [`skimage.feature.structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.structure_tensor")(image[, …]) | Compute structure tensor using sum of squared differences. |
| [`skimage.feature.structure_tensor_eigenvalues`](#skimage.feature.structure_tensor_eigenvalues "skimage.feature.structure_tensor_eigenvalues")(A\_elems) | Compute eigenvalues of structure tensor. |
| [`skimage.feature.structure_tensor_eigvals`](#skimage.feature.structure_tensor_eigvals "skimage.feature.structure_tensor_eigvals")(…) | Compute eigenvalues of structure tensor. |
| [`skimage.feature.BRIEF`](#skimage.feature.BRIEF "skimage.feature.BRIEF")([descriptor\_size, …]) | BRIEF binary descriptor extractor. |
| [`skimage.feature.CENSURE`](#skimage.feature.CENSURE "skimage.feature.CENSURE")([min\_scale, …]) | CENSURE keypoint detector. |
| [`skimage.feature.Cascade`](#skimage.feature.Cascade "skimage.feature.Cascade") | Class for cascade of classifiers that is used for object detection. |
| [`skimage.feature.ORB`](#skimage.feature.ORB "skimage.feature.ORB")([downscale, n\_scales, …]) | Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor. |

 blob\_dog
---------

  
`skimage.feature.blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0, overlap=0.5, *, exclude_border=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L217-L375)
 
Finds blobs in the given grayscale image.

 Blobs are found using the Difference of Gaussian (DoG) method [[1]](#rf5218630e229-1). For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob.

  Parameters 
 
`image2D or 3D ndarray` 

Input grayscale image, blobs are assumed to be light on dark background (white on black).

  
`min_sigmascalar 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_sigmascalar 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_ratiofloat, optional` 

The ratio between the standard deviation of Gaussian Kernels used for computing the Difference of Gaussians

  
`thresholdfloat, optional.` 

The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect blobs with less intensities.

  
`overlapfloat, 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.

  
`exclude_bordertuple 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, and 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`](skimage.filters#skimage.filters.difference_of_gaussians "skimage.filters.difference_of_gaussians")

  #### Notes

 The radius of each blob is approximately \(\sqrt{2}\sigma\) for a 2-D image and \(\sqrt{3}\sigma\) for a 3-D image.

 #### References

  
`1`  
<https://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach>

   #### Examples

 
```
>>> from skimage import data, feature
>>> feature.blob_dog(data.coins(), threshold=.5, max_sigma=40)
array([[120.      , 272.      ,  16.777216],
       [193.      , 213.      ,  16.777216],
       [263.      , 245.      ,  16.777216],
       [185.      , 347.      ,  16.777216],
       [128.      , 154.      ,  10.48576 ],
       [198.      , 155.      ,  10.48576 ],
       [124.      , 337.      ,  10.48576 ],
       [ 45.      , 336.      ,  16.777216],
       [195.      , 102.      ,  16.777216],
       [125.      ,  45.      ,  16.777216],
       [261.      , 173.      ,  16.777216],
       [194.      , 277.      ,  16.777216],
       [127.      , 102.      ,  10.48576 ],
       [125.      , 208.      ,  10.48576 ],
       [267.      , 115.      ,  10.48576 ],
       [263.      , 302.      ,  16.777216],
       [196.      ,  43.      ,  10.48576 ],
       [260.      ,  46.      ,  16.777216],
       [267.      , 359.      ,  16.777216],
       [ 54.      , 276.      ,  10.48576 ],
       [ 58.      , 100.      ,  10.48576 ],
       [ 52.      , 155.      ,  16.777216],
       [ 52.      , 216.      ,  16.777216],
       [ 54.      ,  42.      ,  16.777216]])

```
 
 blob\_doh
---------

  
`skimage.feature.blob_doh(image, min_sigma=1, max_sigma=30, num_sigma=10, threshold=0.01, overlap=0.5, log_scale=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L538-L646)
 
Finds blobs in the given grayscale image.

 Blobs are found using the Determinant of Hessian method [[1]](#ra19a7aed16ca-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]](#ra19a7aed16ca-2).

  Parameters 
 
`image2D ndarray` 

Input grayscale image.Blobs can either be light on dark or vice versa.

  
`min_sigmafloat, optional` 

The minimum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this low to detect smaller blobs.

  
`max_sigmafloat, optional` 

The maximum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this high to detect larger blobs.

  
`num_sigmaint, optional` 

The number of intermediate values of standard deviations to consider between `min_sigma` and `max_sigma`.

  
`thresholdfloat, optional.` 

The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect less prominent blobs.

  
`overlapfloat, 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_scalebool, optional` 

If set intermediate values of standard deviations are interpolated using a logarithmic scale to the base `10`. If not, linear interpolation is used.

    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.

     #### 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 [`blob_dog()`](#skimage.feature.blob_dog "skimage.feature.blob_dog") and [`blob_log()`](#skimage.feature.blob_log "skimage.feature.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.

 #### 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]])

```
 
 blob\_log
---------

  
`skimage.feature.blob_log(image, min_sigma=1, max_sigma=50, num_sigma=10, threshold=0.2, overlap=0.5, log_scale=False, *, exclude_border=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L378-L535)
 
Finds blobs in the given grayscale image.

 Blobs are found using the Laplacian of Gaussian (LoG) method [[1]](#r520e53dd5fa2-1). For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob.

  Parameters 
 
`image2D or 3D ndarray` 

Input grayscale image, blobs are assumed to be light on dark background (white on black).

  
`min_sigmascalar 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_sigmascalar 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_sigmaint, optional` 

The number of intermediate values of standard deviations to consider between `min_sigma` and `max_sigma`.

  
`thresholdfloat, optional.` 

The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect blobs with less intensities.

  
`overlapfloat, 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_scalebool, optional` 

If set intermediate values of standard deviations are interpolated using a logarithmic scale to the base `10`. If not, linear interpolation is used.

  
`exclude_bordertuple 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, and 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.

     #### Notes

 The radius of each blob is approximately \(\sqrt{2}\sigma\) for a 2-D image and \(\sqrt{3}\sigma\) for a 3-D image.

 #### 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.        ]])

```
 
 canny
-----

  
`skimage.feature.canny(image, sigma=1.0, low_threshold=None, high_threshold=None, mask=None, use_quantiles=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_canny.py#L53-L297)
 
Edge filter an image using the Canny algorithm.

  Parameters 
 
`image2D array` 

Grayscale input image to detect edges on; can be of any dtype.

  
`sigmafloat, optional` 

Standard deviation of the Gaussian filter.

  
`low_thresholdfloat, optional` 

Lower bound for hysteresis thresholding (linking edges). If None, low\_threshold is set to 10% of dtype’s max.

  
`high_thresholdfloat, optional` 

Upper bound for hysteresis thresholding (linking edges). If None, high\_threshold is set to 20% of dtype’s max.

  
`maskarray, dtype=bool, optional` 

Mask to limit the application of Canny to a certain area.

  
`use_quantilesbool, 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].

    Returns 
 
`output2D array (image)` 

The binary edge map.

      See also

  
`skimage.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](https://doi.org/10.1109/TPAMI.1986.4767851)

  
`2`  
William Green’s Canny tutorial <https://en.wikipedia.org/wiki/Canny_edge_detector>

   #### Examples

 
```
>>> from skimage import feature
>>> # Generate noisy image of a square
>>> im = np.zeros((256, 256))
>>> im[64:-64, 64:-64] = 1
>>> im += 0.2 * np.random.rand(*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
------------

  
`skimage.feature.corner_fast(image, n=12, threshold=0.15)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L762-L824)
 
Extract FAST corners for a given image.

  Parameters 
 
`image2D ndarray` 

Input image.

  
`nint, 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.

  
`thresholdfloat, 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 
 
`responsendarray` 

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](https://doi.org/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
-----------------

  
`skimage.feature.corner_foerstner(image, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L678-L759)
 
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 
 
`imagendarray` 

Input image.

  
`sigmafloat, optional` 

Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.

    Returns 
 
`wndarray` 

Error ellipse sizes.

  
`qndarray` 

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
--------------

  
`skimage.feature.corner_harris(image, method='k', k=0.05, eps=1e-06, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L536-L613)
 
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 
 
`imagendarray` 

Input image.

  
`method{‘k’, ‘eps’}, optional` 

Method to compute the response image from the auto-correlation matrix.

  
`kfloat, optional` 

Sensitivity factor to separate corners from edges, typically in range `[0, 0.2]`. Small values of k result in detection of sharp corners.

  
`epsfloat, optional` 

Normalisation factor (Noble’s corner measure).

  
`sigmafloat, optional` 

Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.

    Returns 
 
`responsendarray` 

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
--------------------------

  
`skimage.feature.corner_kitchen_rosenfeld(image, mode='constant', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L488-L533)
 
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 
 
`imagendarray` 

Input image.

  
`mode{‘constant’, ‘reflect’, ‘wrap’, ‘nearest’, ‘mirror’}, optional` 

How to handle values outside the image borders.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`responsendarray` 

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](https://doi.org/10.1016/0167-8655(82)90020-4)

   
 corner\_moravec
---------------

  
`skimage.feature.corner_moravec(image, window_size=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1108-L1152)
 
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 
 
`imagendarray` 

Input image.

  
`window_sizeint, optional` 

Window size.

    Returns 
 
`responsendarray` 

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
--------------------

  
`skimage.feature.corner_orientations(image, corners, mask)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1155-L1219)
 
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 
 
`image2D array` 

Input grayscale image.

  
`corners(N, 2) array` 

Corner coordinates as `(row, col)`.

  
`mask2D array` 

Mask defining the local neighborhood of the corner used for the calculation of the central moment.

    Returns 
 
`orientations(N, 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
-------------

  
`skimage.feature.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)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1005-L1105)
 
Find peaks in corner measure response image.

 This differs from [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max") in that it suppresses multiple connected peaks with the same accumulator value.

  Parameters 
 
`imagendarray` 

Input image.

  
`min_distanceint, optional` 

The minimal allowed distance separating peaks.

  
`**` 

See [`skimage.feature.peak_local_max()`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max").

  
`p_normfloat` 

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 
 
`outputndarray 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`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max")

  #### Notes

  Changed in version 0.18: The default value of `threshold_rel` has changed to None, which corresponds to letting [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "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
-------------------

  
`skimage.feature.corner_shi_tomasi(image, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L616-L675)
 
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 
 
`imagendarray` 

Input image.

  
`sigmafloat, optional` 

Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.

    Returns 
 
`responsendarray` 

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
--------------

  
`skimage.feature.corner_subpix(image, corners, window_size=11, alpha=0.99)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L827-L1002)
 
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 
 
`imagendarray` 

Input image.

  
`corners(N, 2) ndarray` 

Corner coordinates `(row, col)`.

  
`window_sizeint, optional` 

Search window size for subpixel estimation.

  
`alphafloat, optional` 

Significance level for corner classification.

    Returns 
 
`positions(N, 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
-----

  
`skimage.feature.daisy(image, step=4, radius=15, rings=3, histograms=8, orientations=8, normalization='l1', sigmas=None, ring_radii=None, visualize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_daisy.py#L9-L222)
 
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]](#r3f18658b3c6d-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]](#r3f18658b3c6d-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]](#r3f18658b3c6d-1) and, therefore, it is omitted.

  Parameters 
 
`image(M, N) array` 

Input image (grayscale).

  
`stepint, optional` 

Distance between descriptor sampling points.

  
`radiusint, optional` 

Radius (in pixels) of the outermost ring.

  
`ringsint, optional` 

Number of rings.

  
`histogramsint, optional` 

Number of histograms sampled per ring.

  
`orientationsint, 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.

  
`sigmas1D 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_radii1D 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`

  
`visualizebool, optional` 

Generate a visualization of the DAISY descriptors

    Returns 
 
`descsarray` 

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(1,2)`  
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
-------------------------

  
`skimage.feature.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, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L222-L321)
 
Visualization of Haar-like features.

  Parameters 
 
`image(M, N) ndarray` 

The region of an integral image for which the features need to be computed.

  
`rint` 

Row-coordinate of top left corner of the detection window.

  
`cint` 

Column-coordinate of top left corner of the detection window.

  
`widthint` 

Width of the detection window.

  
`heightint` 

Height of the detection window.

  
`feature_coordndarray 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 [`haar_like_feature_coord()`](#skimage.feature.haar_like_feature_coord "skimage.feature.haar_like_feature_coord"). By default, all coordinates are computed.

  
`color_positive_rectangletuple 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_blocktuple 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).

  
`alphafloat` 

Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque.

  
`max_n_featuresint, default=None` 

The maximum number of features to be returned. By default, all features are returned.

  
`random_stateint, RandomState instance or None, optional` 

If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used when generating a set of features smaller than the total number of available features.

    Returns 
 
`features(M, N), ndarray` 

An image in which the different features will be added.

     #### Examples

 
```
>>> import numpy as np
>>> from skimage.feature import haar_like_feature_coord
>>> from skimage.feature import draw_haar_like_feature
>>> feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4')
>>> image = draw_haar_like_feature(np.zeros((2, 2)),
...                                0, 0, 2, 2,
...                                feature_coord,
...                                max_n_features=1)
>>> image
array([[[0. , 0.5, 0. ],
        [0.5, 0. , 0. ]],

       [[0.5, 0. , 0. ],
        [0. , 0.5, 0. ]]])

```
 
 draw\_multiblock\_lbp
---------------------

  
`skimage.feature.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)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L386-L493)
 
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 
 
`imagendarray of float or uint` 

Image on which to visualize the pattern.

  
`rint` 

Row-coordinate of top left corner of a rectangle containing feature.

  
`cint` 

Column-coordinate of top left corner of a rectangle containing feature.

  
`widthint` 

Width of one of 9 equal rectangles that will be used to compute a feature.

  
`heightint` 

Height of one of 9 equal rectangles that will be used to compute a feature.

  
`lbp_codeint` 

The descriptor of feature to visualize. If not provided, the descriptor with 0 value will be used.

  
`color_greater_blocktuple 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_blocktuple 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).

  
`alphafloat` 

Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque.

    Returns 
 
`outputndarray of float` 

Image with MB-LBP visualization.

     #### References

  
`1`  
Face Detection Based on Multi-Block LBP Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao, Stan Z. Li <http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf>

   
 greycomatrix
------------

  
`skimage.feature.greycomatrix(image, distances, angles, levels=None, symmetric=False, normed=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L15-L155)
 
Calculate the grey-level co-occurrence matrix.

 A grey level co-occurrence matrix is a histogram of co-occurring greyscale values at a given offset over an image.

  Parameters 
 
`imagearray_like` 

Integer typed input image. Only positive valued images are supported. If type is other than uint8, the argument `levels` needs to be set.

  
`distancesarray_like` 

List of pixel pair distance offsets.

  
`anglesarray_like` 

List of pixel pair angles in radians.

  
`levelsint, optional` 

The input image should contain integers in [0, `levels`-1], where levels indicate the number of grey-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`.

  
`symmetricbool, 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.

  
`normedbool, 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 
 
`P4-D ndarray` 

The grey-level co-occurrence histogram. The value `P[i,j,d,theta]` is the number of times that grey-level `j` occurs at a distance `d` and at an angle `theta` from grey-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`  
The GLCM Tutorial Home Page, <http://www.fp.ucalgary.ca/mhallbey/tutorial.htm>

  
`2`  
Haralick, RM.; Shanmugam, K., “Textural features for image classification” IEEE Transactions on systems, man, and cybernetics 6 (1973): 610-621. [DOI:10.1109/TSMC.1973.4309314](https://doi.org/10.1109/TSMC.1973.4309314)

  
`3`  
Pattern Recognition Engineering, Morton Nadler & Eric P. Smith

  
`4`  
Wikipedia, <https://en.wikipedia.org/wiki/Co-occurrence_matrix>

   #### Examples

 Compute 2 GLCMs: One for a 1-pixel offset to the right, and one for a 1-pixel offset upwards.

 
```
>>> image = np.array([[0, 0, 1, 1],
...                   [0, 0, 1, 1],
...                   [0, 2, 2, 2],
...                   [2, 2, 3, 3]], dtype=np.uint8)
>>> result = greycomatrix(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)

```
 
 ### Examples using `skimage.feature.greycomatrix`

 
 ![GLCM Texture Features]

   greycoprops
-----------

  
`skimage.feature.greycoprops(P, prop='contrast')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L158-L278)
 
Calculate texture properties of a GLCM.

 Compute a feature of a grey level co-occurrence matrix to serve as a compact summary of the matrix. The properties are computed as follows:

 * ‘contrast’: \(\sum\_{i,j=0}^{levels-1} P\_{i,j}(i-j)^2\)
* ‘dissimilarity’: \(\sum\_{i,j=0}^{levels-1}P\_{i,j}|i-j|\)
* ‘homogeneity’: \(\sum\_{i,j=0}^{levels-1}\frac{P\_{i,j}}{1+(i-j)^2}\)
* ‘ASM’: \(\sum\_{i,j=0}^{levels-1} P\_{i,j}^2\)
* ‘energy’: \(\sqrt{ASM}\)
* ‘correlation’:

 \[\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]\]

 Each GLCM is normalized to have a sum of 1 before the computation of texture properties.

  Parameters 
 
`Pndarray` 

Input array. `P` is the grey-level co-occurrence histogram for which to compute the specified property. The value `P[i,j,d,theta]` is the number of times that grey-level j occurs at a distance d and at an angle theta from grey-level i.

  
`prop{‘contrast’, ‘dissimilarity’, ‘homogeneity’, ‘energy’, ‘correlation’, ‘ASM’}, optional` 

The property of the GLCM to compute. The default is ‘contrast’.

    Returns 
 
`results2-D ndarray` 

2-dimensional array. `results[d, a]` is the property ‘prop’ for the d’th distance and the a’th angle.

     #### References

  
`1`  
The GLCM Tutorial Home Page, <http://www.fp.ucalgary.ca/mhallbey/tutorial.htm>

   #### 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 = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4,
...                  normed=True, symmetric=True)
>>> contrast = greycoprops(g, 'contrast')
>>> contrast
array([[0.58333333, 1.        ],
       [1.25      , 2.75      ]])

```
 
 ### Examples using `skimage.feature.greycoprops`

 
 ![GLCM Texture Features]

   haar\_like\_feature
-------------------

  
`skimage.feature.haar_like_feature(int_image, r, c, width, height, feature_type=None, feature_coord=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L87-L219)
 
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]](#rbcb83f52fce4-1). It has been used for real-time face detection algorithm proposed in [[2]](#rbcb83f52fce4-2).

  Parameters 
 
`int_image(M, N) ndarray` 

Integral image for which the features need to be computed.

  
`rint` 

Row-coordinate of top left corner of the detection window.

  
`cint` 

Column-coordinate of top left corner of the detection window.

  
`widthint` 

Width of the detection window.

  
`heightint` 

Height of the detection window.

  
`feature_typestr 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_coordndarray 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 [`haar_like_feature_coord()`](#skimage.feature.haar_like_feature_coord "skimage.feature.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 [Face classification using Haar-like feature descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_haar_extraction_selection_classification.html#sphx-glr-auto-examples-applications-plot-haar-extraction-selection-classification-py) for more insights.

 #### 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](https://doi.org/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](https://doi.org/10.1109/CVPR.2001.990517)

   #### 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, -1, -2, -3, -4, -1, -2, -3, -4, -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, -1, -3, -1, -3, -1, -3, -1, -3, -1,
       -3, -1, -3, -1, -3, -2, -1, -3, -2, -2, -2, -1])

```
 
 haar\_like\_feature\_coord
--------------------------

  
`skimage.feature.haar_like_feature_coord(width, height, feature_type=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L36-L84)
 
Compute the coordinates of Haar-like features.

  Parameters 
 
`widthint` 

Width of the detection window.

  
`heightint` 

Height of the detection window.

  
`feature_typestr 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 
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
---------------

  
`skimage.feature.hessian_matrix(image, sigma=1, mode='constant', cval=0, order='rc')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L133-L199)
 
Compute Hessian matrix.

 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.

  Parameters 
 
`imagendarray` 

Input image.

  
`sigmafloat` 

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.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`order{‘rc’, ‘xy’}, optional` 

This parameter allows for the use of reverse or forward order of the image axes in gradient computation. ‘rc’ indicates the use of the first axis initially (Hrr, Hrc, Hcc), whilst ‘xy’ indicates the usage of the last axis initially (Hxx, Hxy, Hyy)

    Returns 
 
`Hrrndarray` 

Element of the Hessian matrix for each pixel in the input image.

  
`Hrcndarray` 

Element of the Hessian matrix for each pixel in the input image.

  
`Hccndarray` 

Element of the Hessian matrix for each pixel in the input image.

     #### 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')
>>> 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
--------------------

  
`skimage.feature.hessian_matrix_det(image, sigma=1, approximate=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L202-L244)
 
Compute the approximate Hessian Determinant over an image.

 The 2D approximate method uses box filters over integral images to compute the approximate Hessian Determinant, as described in [[1]](#r48e33a732c34-1).

  Parameters 
 
`imagearray` 

The image over which to compute Hessian Determinant.

  
`sigmafloat, optional` 

Standard deviation used for the Gaussian kernel, used for the Hessian matrix.

  
`approximatebool, 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 
 
`outarray` 

The array of the Determinant of Hessians.

     #### 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.

 #### 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>

   
 hessian\_matrix\_eigvals
------------------------

  
`skimage.feature.hessian_matrix_eigvals(H_elems)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L384-L413)
 
Compute eigenvalues of Hessian matrix.

  Parameters 
 
`H_elemslist of ndarray` 

The upper-diagonal elements of the Hessian matrix, as returned by [`hessian_matrix`](#skimage.feature.hessian_matrix "skimage.feature.hessian_matrix").

    Returns 
 
`eigsndarray` 

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')
>>> 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
---

  
`skimage.feature.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, multichannel=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_hog.py#L46-L295)
 
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.

  
`orientationsint, optional` 

Number of orientation bins.

  
`pixels_per_cell2-tuple (int, int), optional` 

Size (in pixels) of a cell.

  
`cells_per_block2-tuple (int, int), optional` 

Number of cells in each block.

  
`block_normstr {‘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]](#ra159ccd8c91f-3), [[4]](#ra159ccd8c91f-4).

    
`visualizebool, 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_sqrtbool, 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_vectorbool, optional` 

Return the data as a feature vector by calling .ravel() on the result just before returning.

  
`multichannelboolean, optional` 

If True, the last `image` dimension is considered as a color channel, otherwise as spatial.

    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.

     #### Notes

 The presented code implements the HOG extraction method from [[2]](#ra159ccd8c91f-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.

 #### 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](https://doi.org/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](https://doi.org/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>

   
 local\_binary\_pattern
----------------------

  
`skimage.feature.local_binary_pattern(image, P, R, method='default')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L281-L337)
 
Gray scale and rotation invariant LBP (Local Binary Patterns).

 LBP is an invariant descriptor that can be used for texture classification.

  Parameters 
 
`image(N, M) array` 

Graylevel image.

  
`Pint` 

Number of circularly symmetric neighbour set points (quantization of the angular space).

  
`Rfloat` 

Radius of circle (spatial resolution of the operator).

  
`method{‘default’, ‘ror’, ‘uniform’, ‘var’}` 

Method to determine the pattern.

 * ‘default’: original local binary pattern which is gray scale but not

rotation invariant.
* ‘ror’: extension of default implementation which is gray scale and

rotation invariant.
* ‘uniform’: improved rotation invariance with uniform patterns and

finer quantization of the angular space which is gray scale and rotation invariant.
* ‘nri\_uniform’: non rotation-invariant uniform patterns variant

which is only gray scale invariant [[2]](#r648eb9e75080-2).
* ‘var’: rotation invariant variance measures of the contrast of local

image texture which is rotation but not gray scale invariant.

    Returns 
 
`output(N, M) array` 

LBP image.

     #### References

  
`1`  
Multiresolution Gray-Scale and Rotation Invariant Texture Classification with Local Binary Patterns. Timo Ojala, Matti Pietikainen, Topi Maenpaa. <http://www.ee.oulu.fi/research/mvmp/mvg/files/pdf/pdf_94.pdf>, 2002.

  
`2`  
Face recognition with local binary patterns. Timo Ahonen, Abdenour Hadid, Matti Pietikainen, <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851>, 2004.

   
 masked\_register\_translation
-----------------------------

  
`skimage.feature.masked_register_translation(src_image, target_image, src_mask, target_mask=None, overlap_ratio=0.3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/__init__.py#L33-L41)
 
**Deprecated function**. Use `skimage.registration.phase_cross_correlation` instead.

 
 match\_descriptors
------------------

  
`skimage.feature.match_descriptors(descriptors1, descriptors2, metric=None, p=2, max_distance=inf, cross_check=True, max_ratio=1.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/match.py#L5-L97)
 
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`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist "(in SciPy v1.5.4)") 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.

  
`pint, optional` 

The p-norm to apply for `metric='minkowski'`.

  
`max_distancefloat, optional` 

Maximum allowed distance between descriptors of two keypoints in separate images to be regarded as a match.

  
`cross_checkbool, 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_ratiofloat, 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
---------------

  
`skimage.feature.match_template(image, template, pad_input=False, mode='constant', constant_values=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/template.py#L31-L179)
 
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[, D]) array` 

2-D or 3-D input image.

  
`template(m, n[, d]) array` 

Template to locate. It must be `(m <= M, n <= N[, d <= D])`.

  
`pad_inputbool` 

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.

  
`modesee numpy.pad, optional` 

Padding mode.

  
`constant_valuessee numpy.pad, optional` 

Constant values used in conjunction with `mode='constant'`.

    Returns 
 
`outputarray` 

Response image with correlation coefficients.

     #### Notes

 Details on the cross-correlation are presented in [[1]](#r7bfca17c0278-1). This implementation uses FFT convolutions of the image and the template. Reference [[2]](#r7bfca17c0278-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](https://doi.org/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
---------------

  
`skimage.feature.multiblock_lbp(int_image, r, c, width, height)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L340-L383)
 
Multi-block local binary pattern (MB-LBP).

 The features are calculated similarly to local binary patterns (LBPs), (See [`local_binary_pattern()`](#skimage.feature.local_binary_pattern "skimage.feature.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.

  
`rint` 

Row-coordinate of top left corner of a rectangle containing feature.

  
`cint` 

Column-coordinate of top left corner of a rectangle containing feature.

  
`widthint` 

Width of one of the 9 equal rectangles that will be used to compute a feature.

  
`heightint` 

Height of one of the 9 equal rectangles that will be used to compute a feature.

    Returns 
 
`outputint` 

8-bit MB-LBP feature descriptor.

     #### References

  
`1`  
Face Detection Based on Multi-Block LBP Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao, Stan Z. Li <http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf>

   
 multiscale\_basic\_features
---------------------------

  
`skimage.feature.multiscale_basic_features(image, multichannel=False, intensity=True, edges=True, texture=True, sigma_min=0.5, sigma_max=16, num_sigma=None, num_workers=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_basic_features.py#L99-L172)
 
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 
 
`imagendarray` 

Input image, which can be grayscale or multichannel.

  
`multichannelbool, default False` 

True if the last dimension corresponds to color channels.

  
`intensitybool, default True` 

If True, pixel intensities averaged over the different scales are added to the feature set.

  
`edgesbool, default True` 

If True, intensities of local gradients averaged over the different scales are added to the feature set.

  
`texturebool, default True` 

If True, eigenvalues of the Hessian matrix after Gaussian blurring at different scales are added to the feature set.

  
`sigma_minfloat, optional` 

Smallest value of the Gaussian kernel used to average local neighbourhoods before extracting features.

  
`sigma_maxfloat, optional` 

Largest value of the Gaussian kernel used to average local neighbourhoods before extracting features.

  
`num_sigmaint, 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_workersint or None, optional` 

The number of parallel threads to use. If set to `None`, the full set of available cores are used.

    Returns 
 
`featuresnp.ndarray` 

Array of shape `image.shape + (n_features,)`

     
 ### Examples using `skimage.feature.multiscale_basic_features`

 
 ![Trainable segmentation using local features and random forests]

   peak\_local\_max
----------------

  
`skimage.feature.peak_local_max(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)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/peak.py#L113-L319)
 
Find peaks in an image as coordinate list or boolean mask.

 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.

  Changed in version 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 
 
`imagendarray` 

Input image.

  
`min_distanceint, optional` 

The minimal allowed distance separating peaks. To find the maximum number of peaks, use `min_distance=1`.

  
`threshold_absfloat, optional` 

Minimum intensity of peaks. By default, the absolute threshold is the minimum intensity of the image.

  
`threshold_relfloat, optional` 

Minimum intensity of peaks, calculated as `max(image) * threshold_rel`.

  
`exclude_borderint, 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.

  
`indicesbool, optional` 

If True, the output will be an array representing peak coordinates. The coordinates are sorted according to peaks values (Larger first). If False, the output will be a boolean array shaped as `image.shape` with peaks present at True elements. `indices` is deprecated and will be removed in version 0.20. Default behavior will be to always return peak coordinates. You can obtain a mask as shown in the example below.

  
`num_peaksint, optional` 

Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` peaks based on highest peak intensity.

  
`footprintndarray of bools, optional` 

If provided, `footprint == 1` represents the local region within which to search for peaks at every point in `image`.

  
`labelsndarray 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_labelint, optional` 

Maximum number of peaks for each label.

  
`p_normfloat` 

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 
 
`outputndarray 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.corner_peaks`](#skimage.feature.corner_peaks "skimage.feature.corner_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 image, this function returns the coordinates or a mask of the peaks where the dilated image equals the original image.

 #### 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]])

```
 
 ### Examples using `skimage.feature.peak_local_max`

 
 ![Finding local maxima]

  

 ![Watershed segmentation]

  

 ![Segment human cells (in mitosis)]

   plot\_matches
-------------

  
`skimage.feature.plot_matches(ax, image1, image2, keypoints1, keypoints2, matches, keypoints_color='k', matches_color=None, only_matches=False, alignment='horizontal')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/util.py#L43-L137)
 
Plot matched features.

  Parameters 
 
`axmatplotlib.axes.Axes` 

Matches and image are drawn in this ax.

  
`image1(N, M [, 3]) array` 

First grayscale or color image.

  
`image2(N, M [, 3]) array` 

Second grayscale or color image.

  
`keypoints1(K1, 2) array` 

First keypoint coordinates as `(row, col)`.

  
`keypoints2(K2, 2) array` 

Second keypoint coordinates as `(row, col)`.

  
`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.

  
`keypoints_colormatplotlib color, optional` 

Color for keypoint locations.

  
`matches_colormatplotlib color, optional` 

Color for lines which connect keypoint matches. By default the color is chosen randomly.

  
`only_matchesbool, optional` 

Whether to only plot matches and not plot the keypoint locations.

  
`alignment{‘horizontal’, ‘vertical’}, optional` 

Whether to show images side by side, `'horizontal'`, or one above the other, `'vertical'`.

     
 register\_translation
---------------------

  
`skimage.feature.register_translation(src_image, target_image, upsample_factor=1, space='real', return_error=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/__init__.py#L44-L51)
 
**Deprecated function**. Use `skimage.registration.phase_cross_correlation` instead.

 
 shape\_index
------------

  
`skimage.feature.shape_index(image, sigma=1, mode='constant', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L416-L485)
 
Compute the shape index.

 The shape index, as defined by Koenderink & van Doorn [[1]](#rc8faae48965f-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 eigen values of the Hessian, and its value ranges from -1 to 1 (and is undefined (=NaN) in *flat* regions), with following ranges representing following shapes:

 

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 
 
`imagendarray` 

Input image.

  
`sigmafloat, 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

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

    Returns 
 
`sndarray` 

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](https://doi.org/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
-----------------

  
`skimage.feature.structure_tensor(image, sigma=1, mode='constant', cval=0, order=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L45-L130)
 
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]](#r0bb93eb224ab-1)).

  Parameters 
 
`imagendarray` 

Input image.

  
`sigmafloat, optional` 

Standard deviation used for the Gaussian kernel, which is used as a weighting function for the local summation of squared differences.

  
`mode{‘constant’, ‘reflect’, ‘wrap’, ‘nearest’, ‘mirror’}, optional` 

How to handle values outside the image borders.

  
`cvalfloat, optional` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`order{‘rc’, ‘xy’}, optional` 

NOTE: Only applies in 2D. 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_elemslist of ndarray` 

Upper-diagonal elements of the structure tensor for each pixel in the input image.

      See also

  
[`structure_tensor_eigenvalues`](#skimage.feature.structure_tensor_eigenvalues "skimage.feature.structure_tensor_eigenvalues")

  #### References

  
`1`  
<https://en.wikipedia.org/wiki/Structure_tensor>

   #### 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.]])

```
 
 structure\_tensor\_eigenvalues
------------------------------

  
`skimage.feature.structure_tensor_eigenvalues(A_elems)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L306-L340)
 
Compute eigenvalues of structure tensor.

  Parameters 
 
`A_elemslist of ndarray` 

The upper-diagonal elements of the structure tensor, as returned by [`structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.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).

      See also

  
[`structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.structure_tensor")

  #### 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.]])

```
 
 structure\_tensor\_eigvals
--------------------------

  
`skimage.feature.structure_tensor_eigvals(Axx, Axy, Ayy)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L343-L381)
 
Compute eigenvalues of structure tensor.

  Parameters 
 
`Axxndarray` 

Element of the structure tensor for each pixel in the input image.

  
`Axyndarray` 

Element of the structure tensor for each pixel in the input image.

  
`Ayyndarray` 

Element of the structure tensor for each pixel in the input image.

    Returns 
 
`l1ndarray` 

Larger eigen value for each input matrix.

  
`l2ndarray` 

Smaller eigen value for each input matrix.

     #### Examples

 
```
>>> from skimage.feature import structure_tensor, structure_tensor_eigvals
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 1
>>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc')
>>> structure_tensor_eigvals(Acc, Arc, Arr)[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.]])

```
 
 BRIEF
-----

  
`class skimage.feature.BRIEF(descriptor_size=256, patch_size=49, mode='normal', sigma=1, sample_seed=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L11-L184)
 
Bases: `skimage.feature.util.DescriptorExtractor`

 BRIEF binary descriptor extractor.

 BRIEF (Binary Robust Independent Elementary Features) is an efficient feature point descriptor. It is highly discriminative even when using relatively few bits and is computed using simple intensity difference tests.

 For each keypoint, intensity comparisons are carried out for a specifically distributed number N of pixel-pairs resulting in a binary descriptor of length N. For binary descriptors the Hamming distance can be used for feature matching, which leads to lower computational cost in comparison to the L2 norm.

  Parameters 
 
`descriptor_sizeint, optional` 

Size of BRIEF descriptor for each keypoint. Sizes 128, 256 and 512 recommended by the authors. Default is 256.

  
`patch_sizeint, 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.

  
`sample_seedint, optional` 

Seed 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. The value of `sample_seed` must be the same for the images to be matched while building the descriptors.

  
`sigmafloat, 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.

     #### 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]])

```
  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`).

      
`__init__(descriptor_size=256, patch_size=49, mode='normal', sigma=1, sample_seed=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L114-L128)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`extract(image, keypoints)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L130-L184)
 
Extract BRIEF binary descriptors for given keypoints in image.

  Parameters 
 
`image2D array` 

Input image.

  
`keypoints(N, 2) array` 

Keypoint coordinates as `(row, col)`.

     
 
 CENSURE
-------

  
`class skimage.feature.CENSURE(min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L111-L296)
 
Bases: `skimage.feature.util.FeatureDetector`

 CENSURE keypoint detector.

  
`min_scaleint, optional` 

Minimum scale to extract keypoints from.

  
`max_scaleint, 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_thresholdfloat, optional` 

Threshold value used to suppress maximas and minimas with a weak magnitude response obtained after Non-Maximal Suppression.

  
`line_thresholdfloat, optional` 

Threshold for rejecting interest points which have ratio of principal curvatures greater than this value.

   #### 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](https://doi.org/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](https://doi.org/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])

```
  Attributes 
 
`keypoints(N, 2) array` 

Keypoint coordinates as `(row, col)`.

  
`scales(N, ) array` 

Corresponding scales.

      
`__init__(min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L198-L216)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`detect(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L218-L296)
 
Detect CENSURE keypoints along with the corresponding scale.

  Parameters 
 
`image2D ndarray` 

Input image.

     
 
 Cascade
-------

  
`class skimage.feature.Cascade`  
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 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 
 
`epscnp.float32_t` 

Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases.

  
`stages_numberPy_ssize_t` 

Amount of stages in a cascade. Each cascade consists of stumps i.e. trained features.

  
`stumps_numberPy_ssize_t` 

The overall amount of stumps in all the stages of cascade.

  
`features_numberPy_ssize_t` 

The overall amount of different features used by cascade. Two stumps can use the same features but has different trained values.

  
`window_widthPy_ssize_t` 

The width of a detection window that is used. Objects smaller than this window can’t be detected.

  
`window_heightPy_ssize_t` 

The height of a detection window.

  
`stagesStage*` 

A link to the c array that stores stages information using Stage struct.

  
`featuresMBLBP*` 

Link to the c array that stores MBLBP features using MBLBP struct.

  
`LUTscnp.uint32_t*` 

The ling to the array with look-up tables that are used by trained MBLBP features (MBLBPStumps) to evaluate a particular region.

      
`__init__()`  
Initialize cascade classifier.

  Parameters 
 
`xml_filefile’s path or file’s object` 

A file in a OpenCv format from which all the cascade classifier’s parameters are loaded.

  
`epscnp.float32_t` 

Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases.

     
  
`detect_multi_scale()`  
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 
 
`img2-D or 3-D ndarray` 

Ndarray that represents the input image.

  
`scale_factorcnp.float32_t` 

The scale by which searching window is multiplied on each step.

  
`step_ratiocnp.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_sizetyple (int, int)` 

Minimum size of the search window.

  
`max_sizetyple (int, int)` 

Maximum size of the search window.

  
`min_neighbour_numberint` 

Minimum amount of intersecting detections in order for detection to be approved by the function.

  
`intersection_score_thresholdcnp.float32_t` 

The minimum value of value of ratio (intersection area) / (small rectangle ratio) in order to merge two detections into one.

    Returns 
 
`outputlist 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.

     
  
`eps` 
  
`features_number` 
  
`stages_number` 
  
`stumps_number` 
  
`window_height` 
  
`window_width` 
 
 ORB
---

  
`class skimage.feature.ORB(downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L22-L348)
 
Bases: `skimage.feature.util.FeatureDetector`, `skimage.feature.util.DescriptorExtractor`

 Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor.

  Parameters 
 
`n_keypointsint, 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_nint, optional` 

The `n` parameter in [`skimage.feature.corner_fast`](#skimage.feature.corner_fast "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_thresholdfloat, 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_kfloat, optional` 

The `k` parameter in [`skimage.feature.corner_harris`](#skimage.feature.corner_harris "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.

  
`downscalefloat, 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_scalesint, optional` 

Maximum number of scales from the bottom of the image pyramid to extract the features from.

     #### 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)
>>> np.random.seed(1)
>>> square = np.random.rand(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, 3],
       [4, 4]])
>>> detector_extractor1.keypoints[matches[:, 0]]
array([[42., 40.],
       [47., 58.],
       [44., 40.],
       [59., 42.],
       [45., 44.]])
>>> detector_extractor2.keypoints[matches[:, 1]]
array([[55., 53.],
       [60., 71.],
       [57., 53.],
       [72., 55.],
       [58., 57.]])

```
  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)`.

      
`__init__(downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L117-L131)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`detect(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L163-L211)
 
Detect oriented FAST keypoints along with the corresponding scale.

  Parameters 
 
`image2D array` 

Input image.

     
  
`detect_and_extract(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L278-L348)
 
Detect oriented FAST keypoints and extract rBRIEF descriptors.

 Note that this is faster than first calling [`detect`](#skimage.feature.ORB.detect "skimage.feature.ORB.detect") and then [`extract`](#skimage.feature.ORB.extract "skimage.feature.ORB.extract").

  Parameters 
 
`image2D array` 

Input image.

     
  
`extract(image, keypoints, scales, orientations)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L225-L276)
 
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`](#skimage.feature.ORB.detect_and_extract "skimage.feature.ORB.detect_and_extract").

  Parameters 
 
`image2D array` 

Input image.

  
`keypoints(N, 2) array` 

Keypoint coordinates as `(row, col)`.

  
`scales(N, ) array` 

Corresponding scales.

  
`orientations(N, ) array` 

Corresponding orientations in radians.

     
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.feature.html>

Module: restoration
===================

 Image restoration module.

 

|  |  |
| --- | --- |
| [`skimage.restoration.ball_kernel`](#skimage.restoration.ball_kernel "skimage.restoration.ball_kernel")(radius, ndim) | Create a ball kernel for restoration.rolling\_ball. |
| [`skimage.restoration.calibrate_denoiser`](#skimage.restoration.calibrate_denoiser "skimage.restoration.calibrate_denoiser")(…) | Calibrate a denoising function and return optimal J-invariant version. |
| [`skimage.restoration.cycle_spin`](#skimage.restoration.cycle_spin "skimage.restoration.cycle_spin")(x, func, …) | Cycle spinning (repeatedly apply func to shifted versions of x). |
| [`skimage.restoration.denoise_bilateral`](#skimage.restoration.denoise_bilateral "skimage.restoration.denoise_bilateral")(image) | Denoise image using bilateral filter. |
| [`skimage.restoration.denoise_nl_means`](#skimage.restoration.denoise_nl_means "skimage.restoration.denoise_nl_means")(image) | Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images. |
| [`skimage.restoration.denoise_tv_bregman`](#skimage.restoration.denoise_tv_bregman "skimage.restoration.denoise_tv_bregman")(…) | Perform total-variation denoising using split-Bregman optimization. |
| [`skimage.restoration.denoise_tv_chambolle`](#skimage.restoration.denoise_tv_chambolle "skimage.restoration.denoise_tv_chambolle")(image) | Perform total-variation denoising on n-dimensional images. |
| [`skimage.restoration.denoise_wavelet`](#skimage.restoration.denoise_wavelet "skimage.restoration.denoise_wavelet")(image[, …]) | Perform wavelet denoising on an image. |
| [`skimage.restoration.ellipsoid_kernel`](#skimage.restoration.ellipsoid_kernel "skimage.restoration.ellipsoid_kernel")(shape, …) | Create an ellipoid kernel for restoration.rolling\_ball. |
| [`skimage.restoration.estimate_sigma`](#skimage.restoration.estimate_sigma "skimage.restoration.estimate_sigma")(image[, …]) | Robust wavelet-based estimator of the (Gaussian) noise standard deviation. |
| [`skimage.restoration.inpaint_biharmonic`](#skimage.restoration.inpaint_biharmonic "skimage.restoration.inpaint_biharmonic")(…) | Inpaint masked points in image with biharmonic equations. |
| [`skimage.restoration.richardson_lucy`](#skimage.restoration.richardson_lucy "skimage.restoration.richardson_lucy")(image, psf) | Richardson-Lucy deconvolution. |
| [`skimage.restoration.rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball")(image, \*[, …]) | Estimate background intensity by rolling/translating a kernel. |
| [`skimage.restoration.unsupervised_wiener`](#skimage.restoration.unsupervised_wiener "skimage.restoration.unsupervised_wiener")(…) | Unsupervised Wiener-Hunt deconvolution. |
| [`skimage.restoration.unwrap_phase`](#skimage.restoration.unwrap_phase "skimage.restoration.unwrap_phase")(image[, …]) | Recover the original from a wrapped phase image. |
| [`skimage.restoration.wiener`](#skimage.restoration.wiener "skimage.restoration.wiener")(image, psf, balance) | Wiener-Hunt deconvolution |

 ball\_kernel
------------

  
`skimage.restoration.ball_kernel(radius, ndim)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L117-L152)
 
Create a ball kernel for restoration.rolling\_ball.

  Parameters 
 
`radiusint` 

Radius of the ball.

  
`ndimint` 

Number of dimensions of the ball. `ndim` should match the dimensionality of the image the kernel will be applied to.

    Returns 
 
`kernelndarray` 

The kernel containing the surface intensity of the top half of the ellipsoid.

      See also

  
[`rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball")

  
 calibrate\_denoiser
-------------------

  
`skimage.restoration.calibrate_denoiser(image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True, extra_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/j_invariant.py#L161-L254)
 
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 
 
`imagendarray` 

Input data to be denoised (converted using `img_as_float`).

  
`denoise_functionfunction` 

Denoising function to be calibrated.

  
`denoise_parametersdict of list` 

Ranges of parameters for `denoise_function` to be calibrated over.

  
`strideint, optional` 

Stride used in masking procedure that converts `denoise_function` to J-invariance.

  
`approximate_lossbool, 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_outputbool, optional` 

If True, return parameters and losses in addition to the calibrated denoising function

    Returns 
 
`best_denoise_functionfunction` 

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_wavelet
>>> import numpy as np
>>> img = color.rgb2gray(data.astronaut()[:50, :50])
>>> noisy = img + 0.5 * img.std() * np.random.randn(*img.shape)
>>> parameters = {'sigma': np.arange(0.1, 0.4, 0.02)}
>>> denoising_function = calibrate_denoiser(noisy, denoise_wavelet,
...                                         denoise_parameters=parameters)
>>> denoised_img = denoising_function(img)

```
 
 cycle\_spin
-----------

  
`skimage.restoration.cycle_spin(x, func, max_shifts, shift_steps=1, num_workers=None, multichannel=False, func_kw={})` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_cycle_spin.py#L49-L145)
 
Cycle spinning (repeatedly apply func to shifted versions of x).

  Parameters 
 
`xarray-like` 

Data for input to `func`.

  
`funcfunction` 

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_shiftsint 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_stepsint 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_workersint 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.

  
`multichannelbool, optional` 

Whether to treat the final axis as channels (no cycle shifts are performed over the channels axis).

  
`func_kwdict, optional` 

Additional keyword arguments to supply to `func`.

    Returns 
 
`avg_ynp.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]](#r67eed921dbd3-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](https://doi.org/10.1007/978-1-4612-2544-7_9)

   #### Examples

 
```
>>> import skimage.data
>>> from skimage import img_as_float
>>> from skimage.restoration import denoise_wavelet, 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_wavelet,
...                       max_shifts=3)

```
 
 denoise\_bilateral
------------------

  
`skimage.restoration.denoise_bilateral(image, win_size=None, sigma_color=None, sigma_spatial=1, bins=10000, mode='constant', cval=0, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L91-L232)
 
Denoise image using bilateral filter.

  Parameters 
 
`imagendarray, shape (M, N[, 3])` 

Input image, 2D grayscale or RGB.

  
`win_sizeint` 

Window size for filtering. If win\_size is not specified, it is calculated as `max(5, 2 * ceil(3 * sigma_spatial) + 1)`.

  
`sigma_colorfloat` 

Standard deviation for grayvalue/color distance (radiometric similarity). A larger value results in averaging of pixels with larger radiometric differences. Note, that the image will be converted using the `img_as_float` function and thus the standard deviation is in respect to the range `[0, 1]`. If the value is `None` the standard deviation of the `image` will be used.

  
`sigma_spatialfloat` 

Standard deviation for range distance. A larger value results in averaging of pixels with larger spatial differences.

  
`binsint` 

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`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)") for detail.

  
`cvalstring` 

Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  
`multichannelbool` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

    Returns 
 
`denoisedndarray` 

Denoised image.

     #### Notes

 This is an edge-preserving, denoising filter. It averages pixels based on their spatial closeness and radiometric similarity [[1]](#rb832e60bc162-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`).

 #### 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](https://doi.org/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]
>>> noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape)
>>> noisy = np.clip(noisy, 0, 1)
>>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15,
...                              multichannel=True)

```
 
 ### Examples using `skimage.restoration.denoise_bilateral`

 
 ![Rank filters]

   denoise\_nl\_means
------------------

  
`skimage.restoration.denoise_nl_means(image, patch_size=7, patch_distance=11, h=0.1, multichannel=False, fast_mode=True, sigma=0.0, *, preserve_range=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/non_local_means.py#L11-L164)
 
Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images.

  Parameters 
 
`image2D or 3D ndarray` 

Input image to be denoised, which can be 2D or 3D, and grayscale or RGB (for 2D images only, see `multichannel` parameter).

  
`patch_sizeint, optional` 

Size of patches used for denoising.

  
`patch_distanceint, optional` 

Maximal distance in pixels where to search patches used for denoising.

  
`hfloat, 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.

  
`multichannelbool, optional` 

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.

  
`fast_modebool, 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.

  
`sigmafloat, 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_rangebool, 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 
 
`resultndarray` 

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 neighbourhood, 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]](#rc9b3919da938-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]](#rc9b3919da938-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]](#rc9b3919da938-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]](#rc9b3919da938-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`](skimage.util#skimage.util.pad "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]](#rc9b3919da938-4). It was also mentioned as an option for the fast variant of the algorithm in [[3]](#rc9b3919da938-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(1,2)`  
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](https://doi.org/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](https://doi.org/10.1109/ISBI.2008.4541250)

  
`3(1,2)`  
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](https://doi.org/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](https://doi.org/10.5201/ipol.2011.bcm_nlm)

   #### Examples

 
```
>>> a = np.zeros((40, 40))
>>> a[10:-10, 10:-10] = 1.
>>> a += 0.3 * np.random.randn(*a.shape)
>>> denoised_a = denoise_nl_means(a, 7, 5, 0.1)

```
 
 denoise\_tv\_bregman
--------------------

  
`skimage.restoration.denoise_tv_bregman(image, weight, max_iter=100, eps=0.001, isotropic=True, *, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L235-L312)
 
Perform total-variation denoising using split-Bregman optimization.

 Total-variation denoising (also know as total-variation regularization) tries to find an image with less total-variation under the constraint of being similar to the input image, which is controlled by the regularization parameter ([[1]](#rc0e3588f2bc3-1), [[2]](#rc0e3588f2bc3-2), [[3]](#rc0e3588f2bc3-3), [[4]](#rc0e3588f2bc3-4)).

  Parameters 
 
`imagendarray` 

Input data to be denoised (converted using img\_as\_float`).

  
`weightfloat` 

Denoising weight. The smaller the `weight`, the more denoising (at the expense of less similarity to the `input`). The regularization parameter `lambda` is chosen as `2 * weight`.

  
`epsfloat, optional` 

Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:

 
```
SUM((u(n) - u(n-1))**2) < eps

```
  
`max_iterint, optional` 

Maximal number of iterations used for the optimization.

  
`isotropicboolean, optional` 

Switch between isotropic and anisotropic TV denoising.

  
`multichannelbool, optional` 

Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.

    Returns 
 
`undarray` 

Denoised image.

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/Total_variation_denoising>

  
`2`  
Tom Goldstein and Stanley Osher, “The Split Bregman Method For L1 Regularized Problems”, <ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf>

  
`3`  
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>

  
`4`  
<https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf>

   
 denoise\_tv\_chambolle
----------------------

  
`skimage.restoration.denoise_tv_chambolle(image, weight=0.1, eps=0.0002, n_iter_max=200, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L396-L479)
 
Perform total-variation denoising on n-dimensional images.

  Parameters 
 
`imagendarray 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.

  
`weightfloat, optional` 

Denoising weight. The greater `weight`, the more denoising (at the expense of fidelity to `input`).

  
`epsfloat, optional` 

Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when:

 (E\_(n-1) - E\_n) < eps \* E\_0

  
`n_iter_maxint, optional` 

Maximal number of iterations used for the optimization.

  
`multichannelbool, optional` 

Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension.

    Returns 
 
`outndarray` 

Denoised image.

     #### Notes

 Make sure to set the multichannel parameter appropriately for color images.

 The principle of total variation denoising is explained in <https://en.wikipedia.org/wiki/Total_variation_denoising>

 The principle of total variation denoising is to minimize the total variation of the 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.

 This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [[1]](#r3f46bb237e10-1).

 #### References

  
`1`  
A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97.

   #### Examples

 2D example on astronaut image:

 
```
>>> from skimage import color, data
>>> img = color.rgb2gray(data.astronaut())[:50, :50]
>>> img += 0.5 * img.std() * np.random.randn(*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)
>>> mask += 0.2*np.random.randn(*mask.shape)
>>> res = denoise_tv_chambolle(mask, weight=100)

```
 
 denoise\_wavelet
----------------

  
`skimage.restoration.denoise_wavelet(image, sigma=None, wavelet='db1', mode='soft', wavelet_levels=None, multichannel=False, convert2ycbcr=False, method='BayesShrink', rescale_sigma=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L694-L863)
 
Perform wavelet denoising on an image.

  Parameters 
 
`imagendarray ([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.

  
`sigmafloat 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]](#r3b8ec6d23a4e-2).

  
`waveletstring, 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_levelsint or None, optional` 

The number of wavelet decomposition levels to use. The default is three less than the maximum number of possible decomposition levels.

  
`multichannelbool, optional` 

Apply wavelet denoising separately for each channel (where channels correspond to the final axis of the array).

  
`convert2ycbcrbool, optional` 

If True and multichannel True, 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]](#r3b8ec6d23a4e-1) and “VisuShrink” [[2]](#r3b8ec6d23a4e-2). Defaults to “BayesShrink”.

  
`rescale_sigmabool, 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.

  New in version 0.16: `rescale_sigma` was introduced in 0.16

     Returns 
 
`outndarray` 

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.

  Changed in version 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]](#r3b8ec6d23a4e-1).

 If `method == "VisuShrink"`, a single “universal threshold” is applied to all wavelet detail coefficients as described in [[2]](#r3b8ec6d23a4e-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(1,2)`  
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](https://doi.org/10.1109/83.862633)

  
`2(1,2,3)`  
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](https://doi.org/10.1093/biomet/81.3.425)

   #### Examples

 
```
>>> from skimage import color, data
>>> img = img_as_float(data.astronaut())
>>> img = color.rgb2gray(img)
>>> img += 0.1 * np.random.randn(*img.shape)
>>> img = np.clip(img, 0, 1)
>>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True)

```
 
 ellipsoid\_kernel
-----------------

  
`skimage.restoration.ellipsoid_kernel(shape, intensity)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L155-L192)
 
Create an ellipoid kernel for restoration.rolling\_ball.

  Parameters 
 
`shapearraylike` 

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.

  
`intensityint` 

Length of the intensity axis of the ellipsoid.

    Returns 
 
`kernelndarray` 

The kernel containing the surface intensity of the top half of the ellipsoid.

      See also

  
[`rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball")

  
 ### Examples using `skimage.restoration.ellipsoid_kernel`

 
 ![Use rolling-ball algorithm for estimating background intensity]

   estimate\_sigma
---------------

  
`skimage.restoration.estimate_sigma(image, average_sigmas=False, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L866-L923)
 
Robust wavelet-based estimator of the (Gaussian) noise standard deviation.

  Parameters 
 
`imagendarray` 

Image for which to estimate the noise standard deviation.

  
`average_sigmasbool, optional` 

If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel.

  
`multichannelbool` 

Estimate sigma separately for each channel.

    Returns 
 
`sigmafloat 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]](#rbc448ac95825-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](https://doi.org/10.1093/biomet/81.3.425)

   #### Examples

 
```
>>> import skimage.data
>>> from skimage import img_as_float
>>> img = img_as_float(skimage.data.camera())
>>> sigma = 0.1
>>> img = img + sigma * np.random.standard_normal(img.shape)
>>> sigma_hat = estimate_sigma(img, multichannel=False)

```
 
 inpaint\_biharmonic
-------------------

  
`skimage.restoration.inpaint_biharmonic(image, mask, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/inpaint.py#L76-L152)
 
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.

  
`multichannelboolean, optional` 

If True, the last `image` dimension is considered as a color channel, otherwise as spatial.

    Returns 
 
`out(M[, N[, …, P]][, C]) ndarray` 

Input image with masked pixels inpainted.

     #### References

  
`1`  
N.S.Hoang, S.B.Damelin, “On surface completion and image inpainting by biharmonic functions: numerical aspects”, [arXiv:1707.06567](https://arxiv.org/abs/1707.06567)

  
`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](https://doi.org/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
----------------

  
`skimage.restoration.richardson_lucy(image, psf, iterations=50, clip=True, filter_epsilon=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L329-L385)
 
Richardson-Lucy deconvolution.

  Parameters 
 
`imagendarray` 

Input degraded image (can be N dimensional).

  
`psfndarray` 

The point spread function.

  
`iterationsint, optional` 

Number of iterations. This parameter plays the role of regularisation.

  
`clipboolean, 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_deconvndarray` 

The deconvolved image.

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution>

   #### 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')
>>> camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape)
>>> deconvolved = restoration.richardson_lucy(camera, psf, 5)

```
 
 rolling\_ball
-------------

  
`skimage.restoration.rolling_ball(image, *, radius=100, kernel=None, nansafe=False, num_threads=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L6-L114)
 
Estimate background intensity by rolling/translating a kernel.

 This rolling ball algorithm estimates background intensity for a ndimage in case of uneven exposure. It is a generalization of the frequently used rolling ball algorithm [[1]](#r62497d9283b1-1).

  Parameters 
 
`imagendarray` 

The image to be filtered.

  
`radiusint, optional` 

Radius of a ball shaped kernel to be rolled/translated in the image. Used if `kernel = None`.

  
`kernelndarray, optional` 

The kernel to be rolled/translated in the image. It must have the same number of dimensions as `image`. Kernel is filled with the intensity of the kernel at that position.

  **nansafe: bool, optional**

If `False` (default) 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` use the OpenMP default value; typically equal to the maximum number of virtual cores. Note: This is an upper limit to the number of threads. The exact number is determined by the system’s OpenMP library.

    Returns 
 
`backgroundndarray` 

The estimated background of the image.

     #### Notes

 For the pixel that has its background intensity estimated (without loss of generality at `center`) the rolling ball method centers `kernel` under it and raises the kernel until the surface touches the image umbra at some `pos=(y,x)`. The background intensity is then estimated using the image intensity at that position (`image[pos]`) plus the difference of `kernel[center] - kernel[pos]`.

 This algorithm assumes that dark pixels correspond to the background. If you have a bright background, invert the image before passing it to the function, e.g., using `utils.invert`. See the gallery example for details.

 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.

 #### References

  
`1`  
Sternberg, Stanley R. “Biomedical image processing.” Computer 1 (1983): 22-34. [DOI:10.1109/MC.1983.1654163](https://doi.org/10.1109/MC.1983.1654163)

   #### Examples

 
```
>>> import numpy as np
>>> from skimage import data
>>> from skimage.restoration import rolling_ball
>>> image = data.coins()
>>> background = rolling_ball(data.coins())
>>> filtered_image = image - background

```
 
```
>>> import numpy as np
>>> from skimage import data
>>> from skimage.restoration import rolling_ball, ellipsoid_kernel
>>> image = data.coins()
>>> kernel = ellipsoid_kernel((101, 101), 75)
>>> background = rolling_ball(data.coins(), kernel=kernel)
>>> filtered_image = image - background

```
 
 ### Examples using `skimage.restoration.rolling_ball`

 
 ![Use rolling-ball algorithm for estimating background intensity]

   unsupervised\_wiener
--------------------

  
`skimage.restoration.unsupervised_wiener(image, psf, reg=None, user_params=None, is_real=True, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L140-L326)
 
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.

  
`psfndarray` 

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)`).

  
`regndarray, optional` 

The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf.

  
`user_paramsdict, optional` 

Dictionary of parameters for the Gibbs sampler. See below.

  
`clipboolean, optional` 

True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.

    Returns 
 
`x_postmean(M, N) ndarray` 

The deconvolved image (the posterior mean).

  
`chainsdict` 

The keys `noise` and `prior` contain the chain list of noise and prior precision respectively.

    Other Parameters 
 **The keys of ``user\_params`` are:**

`thresholdfloat` 

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.

  
`burninint` 

The number of sample to ignore to start computation of the mean. 15 by default.

  
`min_iterint` 

The minimum number of iterations. 30 by default.

  
`max_iterint` 

The maximum number of iterations if `threshold` is not satisfied. 200 by default.

  
`callbackcallable (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.

     #### 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>

 <http://research.orieux.fr/files/papers/OGR-JOSA10.pdf>

   #### 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')
>>> img += 0.1 * img.std() * np.random.standard_normal(img.shape)
>>> deconvolved_img = restoration.unsupervised_wiener(img, psf)

```
 
 unwrap\_phase
-------------

  
`skimage.restoration.unwrap_phase(image, wrap_around=False, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/unwrap.py#L10-L113)
 
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 
 
`image1D, 2D or 3D ndarray of floats, optionally a masked array` 

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_aroundbool 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.

  
`seedint, optional` 

Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior.

    Returns 
 
`image_unwrappedarray_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`.

     #### 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.

   #### 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

```
 
 ### Examples using `skimage.restoration.unwrap_phase`

 
 ![Phase Unwrapping]

   wiener
------

  
`skimage.restoration.wiener(image, psf, balance, reg=None, is_real=True, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L13-L137)
 
Wiener-Hunt deconvolution

 Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation).

  Parameters 
 
`image(M, N) ndarray` 

Input degraded image

  
`psfndarray` 

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 `(M, N)` if `is_real is True`, `(M, N // 2 + 1)` otherwise (see `np.fft.rfftn`).

  
`balancefloat` 

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).

  
`regndarray, 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_realboolean, 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`.

  
`clipboolean, 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.

     #### Notes

 This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is

  \[y = Hx + n\] where \(n\) is noise, \(H\) the PSF and \(x\) the unknown original image, the Wiener filter is

  \[\hat x = F^\dagger (|\Lambda\_H|^2 + \lambda |\Lambda\_D|^2) \Lambda\_H^\dagger F y\] where \(F\) and \(F^\dagger\) are the Fourier and inverse Fourier transforms respectively, \(\Lambda\_H\) the transfer function (or the Fourier transform of the PSF, see [Hunt] below) and \(\Lambda\_D\) the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter \(\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 corresponds 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 \(H\), see [Hunt].

 #### 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>

 <http://research.orieux.fr/files/papers/OGR-JOSA10.pdf>

  
`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

   #### 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')
>>> img += 0.1 * img.std() * np.random.standard_normal(img.shape)
>>> deconvolved_img = restoration.wiener(img, psf, 1100)

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.restoration.html>

Module: util
============

 

|  |  |
| --- | --- |
| [`skimage.util.apply_parallel`](#skimage.util.apply_parallel "skimage.util.apply_parallel")(function, array) | Map a function in parallel across an array. |
| [`skimage.util.compare_images`](#skimage.util.compare_images "skimage.util.compare_images")(image1, image2) | Return an image showing the differences between two images. |
| [`skimage.util.crop`](#skimage.util.crop "skimage.util.crop")(ar, crop\_width[, copy, order]) | Crop array `ar` by `crop_width` along each dimension. |
| [`skimage.util.dtype_limits`](#skimage.util.dtype_limits "skimage.util.dtype_limits")(image[, clip\_negative]) | Return intensity limits, i.e. |
| [`skimage.util.img_as_bool`](#skimage.util.img_as_bool "skimage.util.img_as_bool")(image[, force\_copy]) | Convert an image to boolean format. |
| [`skimage.util.img_as_float`](#skimage.util.img_as_float "skimage.util.img_as_float")(image[, force\_copy]) | Convert an image to floating point format. |
| [`skimage.util.img_as_float32`](#skimage.util.img_as_float32 "skimage.util.img_as_float32")(image[, force\_copy]) | Convert an image to single-precision (32-bit) floating point format. |
| [`skimage.util.img_as_float64`](#skimage.util.img_as_float64 "skimage.util.img_as_float64")(image[, force\_copy]) | Convert an image to double-precision (64-bit) floating point format. |
| [`skimage.util.img_as_int`](#skimage.util.img_as_int "skimage.util.img_as_int")(image[, force\_copy]) | Convert an image to 16-bit signed integer format. |
| [`skimage.util.img_as_ubyte`](#skimage.util.img_as_ubyte "skimage.util.img_as_ubyte")(image[, force\_copy]) | Convert an image to 8-bit unsigned integer format. |
| [`skimage.util.img_as_uint`](#skimage.util.img_as_uint "skimage.util.img_as_uint")(image[, force\_copy]) | Convert an image to 16-bit unsigned integer format. |
| [`skimage.util.invert`](#skimage.util.invert "skimage.util.invert")(image[, signed\_float]) | Invert an image. |
| [`skimage.util.map_array`](#skimage.util.map_array "skimage.util.map_array")(input\_arr, …[, out]) | Map values from input array from input\_vals to output\_vals. |
| [`skimage.util.montage`](#skimage.util.montage "skimage.util.montage")(arr\_in[, fill, …]) | Create a montage of several single- or multichannel images. |
| [`skimage.util.pad`](#skimage.util.pad "skimage.util.pad")(array, pad\_width[, mode]) | Pad an array. |
| [`skimage.util.random_noise`](#skimage.util.random_noise "skimage.util.random_noise")(image[, mode, …]) | Function to add random noise of various types to a floating-point image. |
| [`skimage.util.regular_grid`](#skimage.util.regular_grid "skimage.util.regular_grid")(ar\_shape, n\_points) | Find `n_points` regularly spaced along `ar_shape`. |
| [`skimage.util.regular_seeds`](#skimage.util.regular_seeds "skimage.util.regular_seeds")(ar\_shape, n\_points) | Return an image with ~`n\_points` regularly-spaced nonzero pixels. |
| [`skimage.util.unique_rows`](#skimage.util.unique_rows "skimage.util.unique_rows")(ar) | Remove repeated rows from a 2D array. |
| [`skimage.util.view_as_blocks`](#skimage.util.view_as_blocks "skimage.util.view_as_blocks")(arr\_in, block\_shape) | Block view of the input n-dimensional array (using re-striding). |
| [`skimage.util.view_as_windows`](#skimage.util.view_as_windows "skimage.util.view_as_windows")(arr\_in, …[, step]) | Rolling window view of the input n-dimensional array. |

 apply\_parallel
---------------

  
`skimage.util.apply_parallel(function, array, chunks=None, depth=0, mode=None, extra_arguments=(), extra_keywords={}, *, dtype=None, multichannel=False, compute=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/apply_parallel.py#L58-L177)
 
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 
 
`functionfunction` 

Function to be mapped which takes an array as an argument.

  
`arraynumpy array or dask array` 

Array which the function will be applied to.

  
`chunksint, 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).

  
`depthint, optional` 

Integer equal to the depth of the added boundary cells. Defaults to zero.

  
`mode{‘reflect’, ‘symmetric’, ‘periodic’, ‘wrap’, ‘nearest’, ‘edge’}, optional` 

type of external boundary padding.

  
`extra_argumentstuple, optional` 

Tuple of arguments to be passed to the function.

  
`extra_keywordsdictionary, optional` 

Dictionary of keyword arguments to be passed to the function.

  
`dtypedata-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.

  New in version 0.18: `dtype` was added in 0.18.

   
`multichannelbool, optional` 

If `chunks` is None and `multichannel` is True, this function will keep only a single chunk along the channels axis. When `depth` is specified as a scalar value, that depth will be applied only to the non-channels axes (a depth of 0 will be used along the channels axis). If the user manually specified both `chunks` and a `depth` tuple, then this argument will have no effect.

  New in version 0.18: `multichannel` was added in 0.18.

   
`computebool, 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).

    Returns 
 
`outndarray 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
---------------

  
`skimage.util.compare_images(image1, image2, method='diff', *, n_tiles=(8, 8))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/compare.py#L6-L60)
 
Return an image showing the differences between two images.

  New in version 0.16.

   Parameters 
 
`image1, image22-D array` 

Images to process, must be of the same shape.

  
`methodstring, optional` 

Method used for the comparison. Valid values are {‘diff’, ‘blend’, ‘checkerboard’}. Details are provided in the note section.

  
`n_tilestuple, optional` 

Used only for the `checkerboard` method. Specifies the number of tiles (row, column) to divide the image.

    Returns 
 
`comparison2-D array` 

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.

 
 crop
----

  
`skimage.util.crop(ar, crop_width, copy=False, order='K')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/arraycrop.py#L11-L72)
 
Crop array `ar` by `crop_width` along each dimension.

  Parameters 
 
`ararray-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.

  
`copybool, 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 
 
`croppedarray` 

The cropped array. If `copy=False` (default), this is a sliced view of the input array.

     
 dtype\_limits
-------------

  
`skimage.util.dtype_limits(image, clip_negative=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L38-L57)
 
Return intensity limits, i.e. (min, max) tuple, of the image’s dtype.

  Parameters 
 
`imagendarray` 

Input image.

  
`clip_negativebool, optional` 

If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values.

    Returns 
 
`imin, imaxtuple` 

Lower and upper intensity limits.

     
 img\_as\_bool
-------------

  
`skimage.util.img_as_bool(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L534-L555)
 
Convert an image to boolean format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
--------------

  
`skimage.util.img_as_float(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L432-L458)
 
Convert an image to floating point format.

 This function is similar to [`img_as_float64`](#skimage.util.img_as_float64 "skimage.util.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
----------------

  
`skimage.util.img_as_float32(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L380-L403)
 
Convert an image to single-precision (32-bit) floating point format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
----------------

  
`skimage.util.img_as_float64(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L406-L429)
 
Convert an image to double-precision (64-bit) floating point format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
------------

  
`skimage.util.img_as_int(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L485-L507)
 
Convert an image to 16-bit signed integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray 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
--------------

  
`skimage.util.img_as_ubyte(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L510-L531)
 
Convert an image to 8-bit unsigned integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray of ubyte (uint8)` 

Output image.

     #### Notes

 Negative input values will be clipped. Positive values are scaled between 0 and 255.

 
 img\_as\_uint
-------------

  
`skimage.util.img_as_uint(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L461-L482)
 
Convert an image to 16-bit unsigned integer format.

  Parameters 
 
`imagendarray` 

Input image.

  
`force_copybool, optional` 

Force a copy of the data, irrespective of its current dtype.

    Returns 
 
`outndarray of uint16` 

Output image.

     #### Notes

 Negative input values will be clipped. Positive values are scaled between 0 and 65535.

 
 invert
------

  
`skimage.util.invert(image, signed_float=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_invert.py#L5-L74)
 
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 
 
`imagendarray` 

Input image.

  
`signed_floatbool, 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 
 
`invertedndarray` 

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]])

```
 
 ### Examples using `skimage.util.invert`

 
 ![Use rolling-ball algorithm for estimating background intensity]

   map\_array
----------

  
`skimage.util.map_array(input_arr, input_vals, output_vals, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_map_array.py#L5-L58)
 
Map values from input array from input\_vals to output\_vals.

  Parameters 
 
`input_arrarray of int, shape (M[, N][, P][, …])` 

The input label image.

  
`input_valsarray of int, shape (N,)` 

The values to map from.

  
`output_valsarray, shape (N,)` 

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 
 
`outarray, same shape as input_arr` 

The array of mapped values.

     
 montage
-------

  
`skimage.util.montage(arr_in, fill='mean', rescale_intensity=False, grid_shape=None, padding_width=0, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_montage.py#L7-L142)
 
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(K, M, N[, C]) ndarray` 

An array representing an ensemble of `K` images of equal shape.

  
`fillfloat 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_intensitybool, optional` 

Whether to rescale the intensity of each image to [0, 1].

  
`grid_shapetuple, optional` 

The desired grid shape for the montage `(ntiles_row, ntiles_column)`. The default aspect ratio is square.

  
`padding_widthint, 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.

  
`multichannelboolean, optional` 

If True, the last `arr_in` dimension is threated as a color channel, otherwise as spatial.

    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  
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)

```
 
 pad
---

  
`skimage.util.pad(array, pad_width, mode='constant', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/../numpy/lib/arraypad.py#L529-L876)
 
Pad an array.

  Parameters 
 
`arrayarray_like of rank N` 

The array to pad.

  
`pad_width{sequence, array_like, int}` 

Number of values padded to the edges of each axis. ((before\_1, after\_1), … (before\_N, after\_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

  
`modestr or function, optional` 

One of the following string values or a user supplied function.

  ‘constant’ (default)

Pads with a constant value.

  ‘edge’

Pads with the edge values of array.

  ‘linear\_ramp’

Pads with the linear ramp between end\_value and the array edge value.

  ‘maximum’

Pads with the maximum value of all or part of the vector along each axis.

  ‘mean’

Pads with the mean value of all or part of the vector along each axis.

  ‘median’

Pads with the median value of all or part of the vector along each axis.

  ‘minimum’

Pads with the minimum value of all or part of the vector along each axis.

  ‘reflect’

Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

  ‘symmetric’

Pads with the reflection of the vector mirrored along the edge of the array.

  ‘wrap’

Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.

  ‘empty’

Pads with undefined values.

  New in version 1.17.

   <function>

Padding function, see Notes.

    
`stat_lengthsequence or int, optional` 

Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value.

 ((before\_1, after\_1), … (before\_N, after\_N)) unique statistic lengths for each axis.

 ((before, after),) yields same before and after statistic lengths for each axis.

 (stat\_length,) or int is a shortcut for before = after = statistic length for all axes.

 Default is `None`, to use the entire axis.

  
`constant_valuessequence or scalar, optional` 

Used in ‘constant’. The values to set the padded values for each axis.

 `((before_1, after_1), ... (before_N, after_N))` unique pad constants for each axis.

 `((before, after),)` yields same before and after constants for each axis.

 `(constant,)` or `constant` is a shortcut for `before = after = constant` for all axes.

 Default is 0.

  
`end_valuessequence or scalar, optional` 

Used in ‘linear\_ramp’. The values used for the ending value of the linear\_ramp and that will form the edge of the padded array.

 `((before_1, after_1), ... (before_N, after_N))` unique end values for each axis.

 `((before, after),)` yields same before and after end values for each axis.

 `(constant,)` or `constant` is a shortcut for `before = after = constant` for all axes.

 Default is 0.

  
`reflect_type{‘even’, ‘odd’}, optional` 

Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.

    Returns 
 
`padndarray` 

Padded array of rank equal to [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") with shape increased according to `pad_width`.

     #### Notes

  New in version 1.7.0.

  For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis.

 The padding function, if used, should modify a rank 1 array in-place. It has the following signature:

 
```
padding_func(vector, iaxis_pad_width, iaxis, kwargs)

```
 where

  
`vectorndarray` 

A rank 1 array already padded with zeros. Padded values are vector[:iaxis\_pad\_width[0]] and vector[-iaxis\_pad\_width[1]:].

  
`iaxis_pad_widthtuple` 

A 2-tuple of ints, iaxis\_pad\_width[0] represents the number of values padded at the beginning of vector where iaxis\_pad\_width[1] represents the number of values padded at the end of vector.

  
`iaxisint` 

The axis currently being calculated.

  
`kwargsdict` 

Any keyword arguments the function requires.

   #### Examples

 
```
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
array([4, 4, 1, ..., 6, 6, 6])

```
 
```
>>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, ..., 5, 5, 5])

```
 
```
>>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])

```
 
```
>>> np.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])

```
 
```
>>> np.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

```
 
```
>>> np.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

```
 
```
>>> a = [[1, 2], [3, 4]]
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])

```
 
```
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])

```
 
```
>>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])

```
 
```
>>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])

```
 
```
>>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])

```
 
```
>>> np.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])

```
 
```
>>> def pad_with(vector, pad_width, iaxis, kwargs):
...     pad_value = kwargs.get('padder', 10)
...     vector[:pad_width[0]] = pad_value
...     vector[-pad_width[1]:] = pad_value
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, 2, pad_with)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])
>>> np.pad(a, 2, pad_with, padder=100)
array([[100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100,   0,   1,   2, 100, 100],
       [100, 100,   3,   4,   5, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100]])

```
 
 random\_noise
-------------

  
`skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/noise.py#L8-L192)
 
Function to add random noise of various types to a floating-point image.

  Parameters 
 
`imagendarray` 

Input image data. Will be converted to float.

  
`modestr, optional` 

One of the following strings, selecting the type of noise to add:

 * ‘gaussian’ 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.

  
`seedint, optional` 

If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons.

  
`clipbool, 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].

  
`meanfloat, optional` 

Mean of random distribution. Used in ‘gaussian’ and ‘speckle’. Default : 0.

  
`varfloat, optional` 

Variance of random distribution. Used in ‘gaussian’ and ‘speckle’. Note: variance = (standard deviation) \*\* 2. Default : 0.01

  
`local_varsndarray, optional` 

Array of positive floats, same shape as `image`, defining the local variance at every image point. Used in ‘localvar’.

  
`amountfloat, 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_pepperfloat, 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 
 
`outndarray` 

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
-------------

  
`skimage.util.regular_grid(ar_shape, n_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_regular_grid.py#L4-L83)
 
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_shapearray-like of ints` 

The shape of the space embedding the grid. `len(ar_shape)` is the number of dimensions.

  
`n_pointsint` 

The (approximate) number of points to embed in the space.

    Returns 
 
`slicestuple 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.

  Changed in version 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](https://github.com/numpy/numpy/blob/master/doc/release/1.15.0-notes.rst#deprecations) 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))

```
      #### 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
--------------

  
`skimage.util.regular_seeds(ar_shape, n_points, dtype=<class 'int'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_regular_grid.py#L86-L116)
 
Return an image with ~`n\_points` regularly-spaced nonzero pixels.

  Parameters 
 
`ar_shapetuple of int` 

The shape of the desired output image.

  
`n_pointsint` 

The desired number of nonzero points.

  
`dtypenumpy data type, optional` 

The desired data type of the output.

    Returns 
 
`seed_imgarray 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]])

```
 
 unique\_rows
------------

  
`skimage.util.unique_rows(ar)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/unique.py#L4-L50)
 
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 
 
`ar2-D ndarray` 

The input array.

    Returns 
 
`ar_out2-D ndarray` 

A copy of the input array with repeated rows removed.

    Raises 
 
`ValueErrorif 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
----------------

  
`skimage.util.view_as_blocks(arr_in, block_shape)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/shape.py#L8-L94)
 
Block view of the input n-dimensional array (using re-striding).

 Blocks are non-overlapping views of the input array.

  Parameters 
 
`arr_inndarray` 

N-d input array.

  
`block_shapetuple` 

The shape of the block. Each dimension must divide evenly into the corresponding dimensions of `arr_in`.

    Returns 
 
`arr_outndarray` 

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  
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]  
array([[[[52, 53],
         [58, 59]]],
       [[[76, 77],
         [82, 83]]]])

```
 
 view\_as\_windows
-----------------

  
`skimage.util.view_as_windows(arr_in, window_shape, step=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/shape.py#L97-L247)
 
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_inndarray` 

N-d input array.

  
`window_shapeinteger or tuple of length arr_in.ndim` 

Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [[1]](#redb8d40dc8d4-1)) of the rolling window view. If an integer is given, the shape will be a hypercube of sidelength given by its value.

  
`stepinteger 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_outndarray` 

(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  
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]]]])

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.util.html>

Module: viewer
==============

 

|  |  |
| --- | --- |
| [`skimage.viewer.CollectionViewer`](#skimage.viewer.CollectionViewer "skimage.viewer.CollectionViewer")(image\_collection) | Viewer for displaying image collections. |
| [`skimage.viewer.ImageViewer`](#skimage.viewer.ImageViewer "skimage.viewer.ImageViewer")(image[, useblit]) | Viewer for displaying images. |
| [`skimage.viewer.canvastools`](skimage.viewer.canvastools#module-skimage.viewer.canvastools "skimage.viewer.canvastools") |  |
| [`skimage.viewer.plugins`](skimage.viewer.plugins#module-skimage.viewer.plugins "skimage.viewer.plugins") |  |
| `skimage.viewer.qt` |  |
| [`skimage.viewer.utils`](skimage.viewer.utils#module-skimage.viewer.utils "skimage.viewer.utils") |  |
| [`skimage.viewer.viewers`](skimage.viewer.viewers#module-skimage.viewer.viewers "skimage.viewer.viewers") |  |
| [`skimage.viewer.widgets`](skimage.viewer.widgets#module-skimage.viewer.widgets "skimage.viewer.widgets") | Widgets for interacting with ImageViewer. |

 CollectionViewer
----------------

  
`class skimage.viewer.CollectionViewer(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L331-L407)
 
Bases: `skimage.viewer.viewers.core.ImageViewer`

 Viewer for displaying image collections.

 Select the displayed frame of the image collection using the slider or with the following keyboard shortcuts:

  left/right arrows

Previous/next image in collection.

  number keys, 0–9

0% to 90% of collection. For example, “5” goes to the image in the middle (i.e. 50%) of the collection.

  home/end keys

First/last image in collection.

    Parameters 
 
`image_collectionlist of images` 

List of images to be displayed.

  
`update_on{‘move’ | ‘release’}` 

Control whether image is updated on slide or release of the image slider. Using ‘on\_release’ will give smoother behavior when displaying large images or when writing a plugin/subclass that requires heavy computation.

      
`__init__(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L356-L379)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`keyPressEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L396-L407)

  
`update_index(name, index)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L381-L394)
 
Select image on display using index into image collection.

 
 
 ImageViewer
-----------

  
`class skimage.viewer.ImageViewer(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L49-L328)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Viewer for displaying images.

 This viewer is a simple container object that holds a Matplotlib axes for showing images. [`ImageViewer`](#skimage.viewer.ImageViewer "skimage.viewer.ImageViewer") doesn’t subclass the Matplotlib axes (or figure) because of the high probability of name collisions.

 Subclasses and plugins will likely extend the [`update_image`](#skimage.viewer.ImageViewer.update_image "skimage.viewer.ImageViewer.update_image") method to add custom overlays or filter the displayed image.

  Parameters 
 
`imagearray` 

Image being viewed.

     #### Examples

 
```
>>> from skimage import data
>>> image = data.coins()
>>> viewer = ImageViewer(image) 
>>> viewer.show()               

```
  Attributes 
 
`canvas, fig, axMatplotlib canvas, figure, and axes` 

Matplotlib canvas, figure, and axes used to display image.

  
`imagearray` 

Image being viewed. Setting this value will update the displayed frame.

  
`original_imagearray` 

Plugins typically operate on (but don’t change) the *original* image.

  
`pluginslist` 

List of attached plugins.

      
`__init__(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L92-L151)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L307-L311)

  
`closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L237-L238)

  
`connect_event(event, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L292-L295)
 
Connect callback function to matplotlib event and return id.

 
  
`disconnect_event(callback_id)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L297-L299)
 
Disconnect callback by its id (returned by [`connect_event`](#skimage.viewer.ImageViewer.connect_event "skimage.viewer.ImageViewer.connect_event")).

 
  
`dock_areas = {'bottom': None, 'left': None, 'right': None, 'top': None}` 
  
`property image` 
  
`open_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L186-L193)
 
Open image file and display in viewer.

 
  
`original_image_changed = None` 
  
`redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L258-L262)

  
`remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L313-L319)

  
`reset_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L289-L290)

  
`save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L208-L235)
 
Save current image to file.

 The current behavior is not ideal: It saves the image displayed on screen, so all images will be converted to RGB, and the image size is not preserved (resizing the viewer window will alter the size of the saved image).

 
  
`show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L248-L256)
 
Show ImageViewer and attached plugins.

 This behaves much like [`matplotlib.pyplot.show`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show "(in Matplotlib v3.3.3)") and `QWidget.show`.

 
  
`update_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L195-L201)
 
Update displayed image.

 This method can be overridden or extended in subclasses and plugins to react to image changes.

 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.html>

Module: filters.rank
====================

 

|  |  |
| --- | --- |
| [`skimage.filters.rank.autolevel`](#skimage.filters.rank.autolevel "skimage.filters.rank.autolevel")(image, selem) | Auto-level image using local histogram. |
| [`skimage.filters.rank.autolevel_percentile`](#skimage.filters.rank.autolevel_percentile "skimage.filters.rank.autolevel_percentile")(…) | Return greyscale local autolevel of an image. |
| [`skimage.filters.rank.bottomhat`](#skimage.filters.rank.bottomhat "skimage.filters.rank.bottomhat")(image, selem) | Local bottom-hat of an image. |
| [`skimage.filters.rank.enhance_contrast`](#skimage.filters.rank.enhance_contrast "skimage.filters.rank.enhance_contrast")(image, …) | Enhance contrast of an image. |
| [`skimage.filters.rank.enhance_contrast_percentile`](#skimage.filters.rank.enhance_contrast_percentile "skimage.filters.rank.enhance_contrast_percentile")(…) | Enhance contrast of an image. |
| [`skimage.filters.rank.entropy`](#skimage.filters.rank.entropy "skimage.filters.rank.entropy")(image, selem[, …]) | Local entropy. |
| [`skimage.filters.rank.equalize`](#skimage.filters.rank.equalize "skimage.filters.rank.equalize")(image, selem) | Equalize image using local histogram. |
| [`skimage.filters.rank.geometric_mean`](#skimage.filters.rank.geometric_mean "skimage.filters.rank.geometric_mean")(image, selem) | Return local geometric mean of an image. |
| [`skimage.filters.rank.gradient`](#skimage.filters.rank.gradient "skimage.filters.rank.gradient")(image, selem) | Return local gradient of an image (i.e. |
| [`skimage.filters.rank.gradient_percentile`](#skimage.filters.rank.gradient_percentile "skimage.filters.rank.gradient_percentile")(…) | Return local gradient of an image (i.e. |
| [`skimage.filters.rank.majority`](#skimage.filters.rank.majority "skimage.filters.rank.majority")(image, selem, \*) | Majority filter assign to each pixel the most occuring value within its neighborhood. |
| [`skimage.filters.rank.maximum`](#skimage.filters.rank.maximum "skimage.filters.rank.maximum")(image, selem[, …]) | Return local maximum of an image. |
| [`skimage.filters.rank.mean`](#skimage.filters.rank.mean "skimage.filters.rank.mean")(image, selem[, …]) | Return local mean of an image. |
| [`skimage.filters.rank.mean_bilateral`](#skimage.filters.rank.mean_bilateral "skimage.filters.rank.mean_bilateral")(image, selem) | Apply a flat kernel bilateral filter. |
| [`skimage.filters.rank.mean_percentile`](#skimage.filters.rank.mean_percentile "skimage.filters.rank.mean_percentile")(image, …) | Return local mean of an image. |
| [`skimage.filters.rank.median`](#skimage.filters.rank.median "skimage.filters.rank.median")(image[, selem, …]) | Return local median of an image. |
| [`skimage.filters.rank.minimum`](#skimage.filters.rank.minimum "skimage.filters.rank.minimum")(image, selem[, …]) | Return local minimum of an image. |
| [`skimage.filters.rank.modal`](#skimage.filters.rank.modal "skimage.filters.rank.modal")(image, selem[, …]) | Return local mode of an image. |
| [`skimage.filters.rank.noise_filter`](#skimage.filters.rank.noise_filter "skimage.filters.rank.noise_filter")(image, selem) | Noise feature. |
| [`skimage.filters.rank.otsu`](#skimage.filters.rank.otsu "skimage.filters.rank.otsu")(image, selem[, …]) | Local Otsu’s threshold value for each pixel. |
| [`skimage.filters.rank.percentile`](#skimage.filters.rank.percentile "skimage.filters.rank.percentile")(image, selem) | Return local percentile of an image. |
| [`skimage.filters.rank.pop`](#skimage.filters.rank.pop "skimage.filters.rank.pop")(image, selem[, …]) | Return the local number (population) of pixels. |
| [`skimage.filters.rank.pop_bilateral`](#skimage.filters.rank.pop_bilateral "skimage.filters.rank.pop_bilateral")(image, selem) | Return the local number (population) of pixels. |
| [`skimage.filters.rank.pop_percentile`](#skimage.filters.rank.pop_percentile "skimage.filters.rank.pop_percentile")(image, selem) | Return the local number (population) of pixels. |
| [`skimage.filters.rank.subtract_mean`](#skimage.filters.rank.subtract_mean "skimage.filters.rank.subtract_mean")(image, selem) | Return image subtracted from its local mean. |
| [`skimage.filters.rank.subtract_mean_percentile`](#skimage.filters.rank.subtract_mean_percentile "skimage.filters.rank.subtract_mean_percentile")(…) | Return image subtracted from its local mean. |
| [`skimage.filters.rank.sum`](#skimage.filters.rank.sum "skimage.filters.rank.sum")(image, selem[, …]) | Return the local sum of pixels. |
| [`skimage.filters.rank.sum_bilateral`](#skimage.filters.rank.sum_bilateral "skimage.filters.rank.sum_bilateral")(image, selem) | Apply a flat kernel bilateral filter. |
| [`skimage.filters.rank.sum_percentile`](#skimage.filters.rank.sum_percentile "skimage.filters.rank.sum_percentile")(image, selem) | Return the local sum of pixels. |
| [`skimage.filters.rank.threshold`](#skimage.filters.rank.threshold "skimage.filters.rank.threshold")(image, selem) | Local threshold of an image. |
| [`skimage.filters.rank.threshold_percentile`](#skimage.filters.rank.threshold_percentile "skimage.filters.rank.threshold_percentile")(…) | Local threshold of an image. |
| [`skimage.filters.rank.tophat`](#skimage.filters.rank.tophat "skimage.filters.rank.tophat")(image, selem[, …]) | Local top-hat of an image. |
| [`skimage.filters.rank.windowed_histogram`](#skimage.filters.rank.windowed_histogram "skimage.filters.rank.windowed_histogram")(…) | Normalized sliding window histogram |

 autolevel
---------

  
`skimage.filters.rank.autolevel(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L337-L387)
 
Auto-level image using local histogram.

 This filter locally stretches the histogram of gray values to cover the entire range of values from “white” to “black”.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import autolevel
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> auto = autolevel(img, disk(5))
>>> auto_vol = autolevel(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.autolevel`

 
 ![Rank filters]

   autolevel\_percentile
---------------------

  
`skimage.filters.rank.autolevel_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L48-L85)
 
Return greyscale local autolevel of an image.

 This filter locally stretches the histogram of greyvalues to cover the entire range of values from “white” to “black”.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 ### Examples using `skimage.filters.rank.autolevel_percentile`

 
 ![Rank filters]

   bottomhat
---------

  
`skimage.filters.rank.bottomhat(image, selem, out=None, mask=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L390-L443)
 
Local bottom-hat of an image.

 This filter computes the morphological closing of the image and then subtracts the result from the original image.

  Parameters 
 
`image2-D array (integer or float)` 

Input image.

  
`selem2-D array (integer or float)` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (integer or float), optional` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint, optional` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

    Warns 
 Deprecated:

 New in version 0.17.

  This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import bottomhat
>>> img = data.camera()
>>> out = bottomhat(img, disk(5))  

```
 
 enhance\_contrast
-----------------

  
`skimage.filters.rank.enhance_contrast(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L937-L988)
 
Enhance contrast of an image.

 This replaces each pixel by the local maximum if the pixel gray value is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import enhance_contrast
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = enhance_contrast(img, disk(5))
>>> out_vol = enhance_contrast(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.enhance_contrast`

 
 ![Rank filters]

   enhance\_contrast\_percentile
-----------------------------

  
`skimage.filters.rank.enhance_contrast_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L199-L237)
 
Enhance contrast of an image.

 This replaces each pixel by the local maximum if the pixel greyvalue is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 ### Examples using `skimage.filters.rank.enhance_contrast_percentile`

 
 ![Rank filters]

   entropy
-------

  
`skimage.filters.rank.entropy(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1290-L1346)
 
Local entropy.

 The entropy is computed using base 2 logarithm i.e. the filter returns the minimum number of bits needed to encode the local gray level distribution.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (float)` 

Output image.

     #### References

  
`1`  
<https://en.wikipedia.org/wiki/Entropy_(information_theory)>

   #### Examples

 
```
>>> from skimage import data
>>> from skimage.filters.rank import entropy
>>> from skimage.morphology import disk, ball
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> ent = entropy(img, disk(5))
>>> ent_vol = entropy(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.entropy`

 
 ![Tinting gray-scale images]

  

 ![Entropy]

  

 ![Rank filters]

   equalize
--------

  
`skimage.filters.rank.equalize(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L446-L493)
 
Equalize image using local histogram.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import equalize
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> equ = equalize(img, disk(5))
>>> equ_vol = equalize(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.equalize`

 
 ![Local Histogram Equalization]

  

 ![Rank filters]

   geometric\_mean
---------------

  
`skimage.filters.rank.geometric_mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L655-L707)
 
Return local geometric mean of an image.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### References

  
`1`  
Gonzalez, R. C. and Wood, R. E. “Digital Image Processing (3rd Edition).” Prentice-Hall Inc, 2006.

   #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import mean
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> avg = geometric_mean(img, disk(5))
>>> avg_vol = geometric_mean(volume, ball(5))

```
 
 gradient
--------

  
`skimage.filters.rank.gradient(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L496-L543)
 
Return local gradient of an image (i.e. local maximum - local minimum).

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import gradient
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = gradient(img, disk(5))
>>> out_vol = gradient(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.gradient`

 
 ![Markers for watershed transform]

  

 ![Rank filters]

   gradient\_percentile
--------------------

  
`skimage.filters.rank.gradient_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L88-L122)
 
Return local gradient of an image (i.e. local maximum - local minimum).

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 majority
--------

  
`skimage.filters.rank.majority(image, selem, *, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1460-L1508)
 
Majority filter assign to each pixel the most occuring value within its neighborhood.

  Parameters 
 
`imagendarray` 

Image array (uint8, uint16 array).

  
`selem2-D array (integer or float)` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`outndarray (integer or float), optional` 

If None, a new array will be allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint, optional` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.filters.rank import majority
>>> from skimage.morphology import disk, ball
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> maj_img = majority(img, disk(5))
>>> maj_img_vol = majority(volume, ball(5))

```
 
 maximum
-------

  
`skimage.filters.rank.maximum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L546-L602)
 
Return local maximum of an image.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

      See also

  
[`skimage.morphology.dilation`](skimage.morphology#skimage.morphology.dilation "skimage.morphology.dilation")

  #### Notes

 The lower algorithm complexity makes [`skimage.filters.rank.maximum`](#skimage.filters.rank.maximum "skimage.filters.rank.maximum") more efficient for larger images and structuring elements.

 #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import maximum
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = maximum(img, disk(5))
>>> out_vol = maximum(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.maximum`

 
 ![Rank filters]

   mean
----

  
`skimage.filters.rank.mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L605-L652)
 
Return local mean of an image.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import mean
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> avg = mean(img, disk(5))
>>> avg_vol = mean(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.mean`

 
 ![Segment human cells (in mitosis)]

  

 ![Rank filters]

   mean\_bilateral
---------------

  
`skimage.filters.rank.mean_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L47-L102)
 
Apply a flat kernel bilateral filter.

 This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity.

 Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element.

 Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel.

 Only pixels belonging to the structuring element and having a greylevel inside this interval are averaged.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`s0, s1int` 

Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

      See also

  
`denoise_bilateral` 
  #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import mean_bilateral
>>> img = data.camera().astype(np.uint16)
>>> bilat_img = mean_bilateral(img, disk(20), s0=10,s1=10)

```
 
 ### Examples using `skimage.filters.rank.mean_bilateral`

 
 ![Rank filters]

   mean\_percentile
----------------

  
`skimage.filters.rank.mean_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L125-L159)
 
Return local mean of an image.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 median
------

  
`skimage.filters.rank.median(image, selem=None, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L768-L823)
 
Return local median of an image.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s. If None, a full square of size 3 is used.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

      See also

  
[`skimage.filters.median`](skimage.filters#skimage.filters.median "skimage.filters.median")


Implementation of a median filtering which handles images with floating precision.

    #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import median
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> med = median(img, disk(5))
>>> med_vol = median(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.median`

 
 ![Markers for watershed transform]

  

 ![Rank filters]

   minimum
-------

  
`skimage.filters.rank.minimum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L826-L882)
 
Return local minimum of an image.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

      See also

  
[`skimage.morphology.erosion`](skimage.morphology#skimage.morphology.erosion "skimage.morphology.erosion")

  #### Notes

 The lower algorithm complexity makes [`skimage.filters.rank.minimum`](#skimage.filters.rank.minimum "skimage.filters.rank.minimum") more efficient for larger images and structuring elements.

 #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import minimum
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = minimum(img, disk(5))
>>> out_vol = minimum(volume, ball(5))

```
 
 ### Examples using `skimage.filters.rank.minimum`

 
 ![Rank filters]

   modal
-----

  
`skimage.filters.rank.modal(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L885-L934)
 
Return local mode of an image.

 The mode is the value that appears most often in the local histogram.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import modal
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = modal(img, disk(5))
>>> out_vol = modal(volume, ball(5))

```
 
 noise\_filter
-------------

  
`skimage.filters.rank.noise_filter(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1220-L1287)
 
Noise feature.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### References

  
`1`  
N. Hashimoto et al. Referenceless image quality evaluation for whole slide imaging. J Pathol Inform 2012;3:9.

   #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import noise_filter
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = noise_filter(img, disk(5))
>>> out_vol = noise_filter(volume, ball(5))

```
 
 otsu
----

  
`skimage.filters.rank.otsu(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1349-L1402)
 
Local Otsu’s threshold value for each pixel.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### References

  
`1`  
[https://en.wikipedia.org/wiki/Otsu’s\_method](https://en.wikipedia.org/wiki/Otsu's_method)

   #### Examples

 
```
>>> from skimage import data
>>> from skimage.filters.rank import otsu
>>> from skimage.morphology import disk, ball
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> local_otsu = otsu(img, disk(5))
>>> thresh_image = img >= local_otsu
>>> local_otsu_vol = otsu(volume, ball(5))
>>> thresh_image_vol = volume >= local_otsu_vol

```
 
 ### Examples using `skimage.filters.rank.otsu`

 
 ![Rank filters]

   percentile
----------

  
`skimage.filters.rank.percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L240-L276)
 
Return local percentile of an image.

 Returns the value of the p0 lower percentile of the local greyvalue distribution.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0float in [0, …, 1]` 

Set the percentile value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 pop
---

  
`skimage.filters.rank.pop(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L991-L1046)
 
Return the local number (population) of pixels.

 The number of pixels is defined as the number of pixels which are included in the structuring element and the mask.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage.morphology import square, cube # Need to add 3D example
>>> import skimage.filters.rank as rank
>>> img = 255 * 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)
>>> rank.pop(img, square(3))
array([[4, 6, 6, 6, 4],
       [6, 9, 9, 9, 6],
       [6, 9, 9, 9, 6],
       [6, 9, 9, 9, 6],
       [4, 6, 6, 6, 4]], dtype=uint8)

```
 
 pop\_bilateral
--------------

  
`skimage.filters.rank.pop_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L105-L158)
 
Return the local number (population) of pixels.

 The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Additionally pixels must have a greylevel inside the interval [g-s0, g+s1] where g is the greyvalue of the center pixel.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`s0, s1int` 

Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage.morphology import square
>>> import skimage.filters.rank as rank
>>> img = 255 * 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.uint16)
>>> rank.pop_bilateral(img, square(3), s0=10, s1=10)
array([[3, 4, 3, 4, 3],
       [4, 4, 6, 4, 4],
       [3, 6, 9, 6, 3],
       [4, 4, 6, 4, 4],
       [3, 4, 3, 4, 3]], dtype=uint16)

```
 
 pop\_percentile
---------------

  
`skimage.filters.rank.pop_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L279-L316)
 
Return the local number (population) of pixels.

 The number of pixels is defined as the number of pixels which are included in the structuring element and the mask.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 subtract\_mean
--------------

  
`skimage.filters.rank.subtract_mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L710-L765)
 
Return image subtracted from its local mean.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Notes

 Subtracting the mean value may introduce underflow. To compensate this potential underflow, the obtained difference is downscaled by a factor of 2 and shifted by `n_bins / 2 - 1`, the median value of the local histogram (`n_bins = max(3, image.max()) +1` for 16-bits images and 256 otherwise).

 #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import subtract_mean
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = subtract_mean(img, disk(5))
>>> out_vol = subtract_mean(volume, ball(5))

```
 
 subtract\_mean\_percentile
--------------------------

  
`skimage.filters.rank.subtract_mean_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L162-L196)
 
Return image subtracted from its local mean.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 sum
---

  
`skimage.filters.rank.sum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1049-L1104)
 
Return the local sum of pixels.

 Note that the sum may overflow depending on the data type of the input array.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage.morphology import square, cube # Need to add 3D example
>>> import skimage.filters.rank as rank         # Cube seems to fail but
>>> img = np.array([[0, 0, 0, 0, 0],            # Ball can pass
...                 [0, 1, 1, 1, 0],
...                 [0, 1, 1, 1, 0],
...                 [0, 1, 1, 1, 0],
...                 [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> rank.sum(img, square(3))
array([[1, 2, 3, 2, 1],
       [2, 4, 6, 4, 2],
       [3, 6, 9, 6, 3],
       [2, 4, 6, 4, 2],
       [1, 2, 3, 2, 1]], dtype=uint8)

```
 
 sum\_bilateral
--------------

  
`skimage.filters.rank.sum_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L161-L219)
 
Apply a flat kernel bilateral filter.

 This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity.

 Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element (selem).

 Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel.

 Only pixels belonging to the structuring element AND having a greylevel inside this interval are summed.

 Note that the sum may overflow depending on the data type of the input array.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`s0, s1int` 

Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

      See also

  
`denoise_bilateral` 
  #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import sum_bilateral
>>> img = data.camera().astype(np.uint16)
>>> bilat_img = sum_bilateral(img, disk(10), s0=10, s1=10)

```
 
 sum\_percentile
---------------

  
`skimage.filters.rank.sum_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L319-L356)
 
Return the local sum of pixels.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

 Note that the sum may overflow depending on the data type of the input array.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0, p1float in [0, …, 1]` 

Define the [p0, p1] percentile interval to be considered for computing the value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 threshold
---------

  
`skimage.filters.rank.threshold(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1107-L1162)
 
Local threshold of an image.

 The resulting binary mask is True if the gray value of the center pixel is greater than the local mean.

  Parameters 
 
`image([P,] M, N) ndarray (uint8, uint16)` 

Input image.

  
`selemndarray` 

The neighborhood expressed as an ndarray of 1’s and 0’s.

  
`out([P,] M, N) array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_y, shift_zint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out([P,] M, N) ndarray (same dtype as input image)` 

Output image.

     #### Examples

 
```
>>> from skimage.morphology import square, cube # Need to add 3D example
>>> from skimage.filters.rank import threshold
>>> img = 255 * 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)
>>> threshold(img, square(3))
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)

```
 
 threshold\_percentile
---------------------

  
`skimage.filters.rank.threshold_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L359-L395)
 
Local threshold of an image.

 The resulting binary mask is True if the greyvalue of the center pixel is greater than the local mean.

 Only greyvalues between percentiles [p0, p1] are considered in the filter.

  Parameters 
 
`image2-D array (uint8, uint16)` 

Input image.

  
`selem2-D array` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (same dtype as input)` 

If None, a new array is allocated.

  
`maskndarray` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`p0float in [0, …, 1]` 

Set the percentile value.

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

     
 tophat
------

  
`skimage.filters.rank.tophat(image, selem, out=None, mask=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1165-L1217)
 
Local top-hat of an image.

 This filter computes the morphological opening of the image and then subtracts the result from the original image.

  Parameters 
 
`image2-D array (integer or float)` 

Input image.

  
`selem2-D array (integer or float)` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (integer or float), optional` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint, optional` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

    Returns 
 
`out2-D array (same dtype as input image)` 

Output image.

    Warns 
 Deprecated:

 New in version 0.17.

  This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import tophat
>>> img = data.camera()
>>> out = tophat(img, disk(5))  

```
 
 windowed\_histogram
-------------------

  
`skimage.filters.rank.windowed_histogram(image, selem, out=None, mask=None, shift_x=False, shift_y=False, n_bins=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1405-L1457)
 
Normalized sliding window histogram

  Parameters 
 
`image2-D array (integer or float)` 

Input image.

  
`selem2-D array (integer or float)` 

The neighborhood expressed as a 2-D array of 1’s and 0’s.

  
`out2-D array (integer or float), optional` 

If None, a new array is allocated.

  
`maskndarray (integer or float), optional` 

Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default).

  
`shift_x, shift_yint, optional` 

Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element).

  
`n_binsint or None` 

The number of histogram bins. Will default to `image.max() + 1` if None is passed.

    Returns 
 
`out3-D array (float)` 

Array of dimensions (H,W,N), where (H,W) are the dimensions of the input image and N is n\_bins or `image.max() + 1` if no value is provided as a parameter. Effectively, each pixel is a N-D feature vector that is the histogram. The sum of the elements in the feature vector will be 1, unless no pixels in the window were covered by both selem and mask, in which case all elements will be 0.

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.filters.rank import windowed_histogram
>>> from skimage.morphology import disk, ball
>>> import numpy as np
>>> img = data.camera()
>>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8)
>>> hist_img = windowed_histogram(img, disk(5))

```
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.filters.rank.html>

Module: viewer.canvastools
==========================

 

|  |  |
| --- | --- |
| [`skimage.viewer.canvastools.LineTool`](#skimage.viewer.canvastools.LineTool "skimage.viewer.canvastools.LineTool")(manager) | Widget for line selection in a plot. |
| [`skimage.viewer.canvastools.PaintTool`](#skimage.viewer.canvastools.PaintTool "skimage.viewer.canvastools.PaintTool")(…[, …]) | Widget for painting on top of a plot. |
| [`skimage.viewer.canvastools.RectangleTool`](#skimage.viewer.canvastools.RectangleTool "skimage.viewer.canvastools.RectangleTool")(manager) | Widget for selecting a rectangular region in a plot. |
| [`skimage.viewer.canvastools.ThickLineTool`](#skimage.viewer.canvastools.ThickLineTool "skimage.viewer.canvastools.ThickLineTool")(manager) | Widget for line selection in a plot. |
| `skimage.viewer.canvastools.base` |  |
| `skimage.viewer.canvastools.linetool` |  |
| `skimage.viewer.canvastools.painttool` |  |
| `skimage.viewer.canvastools.recttool` |  |

 LineTool
--------

  
`class skimage.viewer.canvastools.LineTool(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, line_props=None, handle_props=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L9-L124)
 
Bases: `skimage.viewer.canvastools.base.CanvasToolBase`

 Widget for line selection in a plot.

  Parameters 
 
`managerViewer or PlotPlugin.` 

Skimage viewer or plot plugin object.

  
`on_movefunction` 

Function called whenever a control handle is moved. This function must accept the end points of line as the only argument.

  
`on_releasefunction` 

Function called whenever the control handle is released.

  
`on_enterfunction` 

Function called whenever the “enter” key is pressed.

  
`maxdistfloat` 

Maximum pixel distance allowed when selecting control handle.

  
`line_propsdict` 

Properties for [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)").

  
`handle_propsdict` 

Marker properties for the handles (also see [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)")).

    Attributes 
 
`end_points2D array` 

End points of line ((x1, y1), (x2, y2)).

      
`__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, line_props=None, handle_props=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L36-L67)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property end_points` 
  
`property geometry`  
Geometry information that gets passed to callback functions.

 
  
`hit_test(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L84-L93)

  
`on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L95-L100)

  
`on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L102-L107)

  
`on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L109-L115)

  
`update(x=None, y=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L117-L120)

 
 PaintTool
---------

  
`class skimage.viewer.canvastools.PaintTool(manager, overlay_shape, radius=5, alpha=0.3, on_move=None, on_release=None, on_enter=None, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L12-L186)
 
Bases: `skimage.viewer.canvastools.base.CanvasToolBase`

 Widget for painting on top of a plot.

  Parameters 
 
`managerViewer or PlotPlugin.` 

Skimage viewer or plot plugin object.

  
`overlay_shapeshape tuple` 

2D shape tuple used to initialize overlay image.

  
`radiusint` 

The size of the paint cursor.

  
`alphafloat (between [0, 1])` 

Opacity of overlay.

  
`on_movefunction` 

Function called whenever a control handle is moved. This function must accept the end points of line as the only argument.

  
`on_releasefunction` 

Function called whenever the control handle is released.

  
`on_enterfunction` 

Function called whenever the “enter” key is pressed.

  
`rect_propsdict` 

Properties for [`matplotlib.patches.Rectangle`](https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle "(in Matplotlib v3.3.3)"). This class redefines defaults in [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)").

     #### Examples

 
```
>>> from skimage.data import camera
>>> import matplotlib.pyplot as plt
>>> from skimage.viewer.canvastools import PaintTool
>>> import numpy as np

```
 
```
>>> img = camera() 

```
 
```
>>> ax = plt.subplot(111) 
>>> plt.imshow(img, cmap=plt.cm.gray) 
>>> p = PaintTool(ax,np.shape(img[:-1]),10,0.2) 
>>> plt.show() 

```
 
```
>>> mask = p.overlay 
>>> plt.imshow(mask,cmap=plt.cm.gray) 
>>> plt.show() 

```
  Attributes 
 
`overlayarray` 

Overlay of painted labels displayed on top of image.

  
`labelint` 

Current paint color.

      
`__init__(manager, overlay_shape, radius=5, alpha=0.3, on_move=None, on_release=None, on_enter=None, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L61-L86)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property geometry`  
Geometry information that gets passed to callback functions.

 
  
`property label` 
  
`on_key_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L143-L146)

  
`on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L148-L152)

  
`on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L154-L157)

  
`on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L159-L171)

  
`property overlay` 
  
`property radius` 
  
`property shape` 
  
`update_cursor(x, y)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L179-L182)

  
`update_overlay(x, y)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L173-L177)

 
 RectangleTool
-------------

  
`class skimage.viewer.canvastools.RectangleTool(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L9-L233)
 
Bases: `skimage.viewer.canvastools.base.CanvasToolBase`, [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)")

 Widget for selecting a rectangular region in a plot.

 After making the desired selection, press “Enter” to accept the selection and call the `on_enter` callback function.

  Parameters 
 
`managerViewer or PlotPlugin.` 

Skimage viewer or plot plugin object.

  
`on_movefunction` 

Function called whenever a control handle is moved. This function must accept the rectangle extents as the only argument.

  
`on_releasefunction` 

Function called whenever the control handle is released.

  
`on_enterfunction` 

Function called whenever the “enter” key is pressed.

  
`maxdistfloat` 

Maximum pixel distance allowed when selecting control handle.

  
`rect_propsdict` 

Properties for [`matplotlib.patches.Rectangle`](https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle "(in Matplotlib v3.3.3)"). This class redefines defaults in [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)").

     #### Examples

 
```
>>> from skimage import data
>>> from skimage.viewer import ImageViewer
>>> from skimage.viewer.canvastools import RectangleTool
>>> from skimage.draw import line
>>> from skimage.draw import set_color

```
 
```
>>> viewer = ImageViewer(data.coffee())  

```
 
```
>>> def print_the_rect(extents):
...     global viewer
...     im = viewer.image
...     coord = np.int64(extents)
...     [rr1, cc1] = line(coord[2],coord[0],coord[2],coord[1])
...     [rr2, cc2] = line(coord[2],coord[1],coord[3],coord[1])
...     [rr3, cc3] = line(coord[3],coord[1],coord[3],coord[0])
...     [rr4, cc4] = line(coord[3],coord[0],coord[2],coord[0])
...     set_color(im, (rr1, cc1), [255, 255, 0])
...     set_color(im, (rr2, cc2), [0, 255, 255])
...     set_color(im, (rr3, cc3), [255, 0, 255])
...     set_color(im, (rr4, cc4), [0, 0, 0])
...     viewer.image=im

```
 
```
>>> rect_tool = RectangleTool(viewer, on_enter=print_the_rect) 
>>> viewer.show() 

```
  Attributes 
 
`extentstuple` 

Return (xmin, xmax, ymin, ymax).

      
`__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L65-L110)
 
 Parameters 
 
`axAxes` 

The parent axes for the widget.

  
`onselectfunction` 

A callback function that is called after a selection is completed. It must have the signature:

 
```
def onselect(eclick: MouseEvent, erelease: MouseEvent)

```
 where *eclick* and *erelease* are the mouse click and release `MouseEvent`s that start and complete the selection.

  
`drawtype{“box”, “line”, “none”}, default: “box”` 

Whether to draw the full rectangle box, the diagonal line of the rectangle, or nothing at all.

  
`minspanxfloat, default: 0` 

Selections with an x-span less than *minspanx* are ignored.

  
`minspanyfloat, default: 0` 

Selections with an y-span less than *minspany* are ignored.

  
`useblitbool, default: False` 

Whether to use blitting for faster drawing (if supported by the backend).

  
`linepropsdict, optional` 

Properties with which the line is drawn, if `drawtype == "line"`. Default:

 
```
dict(color="black", linestyle="-", linewidth=2, alpha=0.5)

```
  
`rectpropsdict, optional` 

Properties with which the rectangle is drawn, if `drawtype ==
"box"`. Default:

 
```
dict(facecolor="red", edgecolor="black", alpha=0.2, fill=True)

```
  
`spancoords{“data”, “pixels”}, default: “data”` 

Whether to interpret *minspanx* and *minspany* in data or in pixel coordinates.

  
`buttonMouseButton, list of MouseButton, default: all buttons` 

Button(s) that trigger rectangle selection.

  
`maxdistfloat, default: 10` 

Distance in pixels within which the interactive tool handles can be activated.

  
`marker_propsdict` 

Properties with which the interactive handles are drawn. Currently not implemented and ignored.

  
`interactivebool, default: False` 

Whether to draw a set of handles that allow interaction with the widget after it is drawn.

  
`state_modifier_keysdict, optional` 

Keyboard modifiers which affect the widget’s behavior. Values amend the defaults.

 * “move”: Move the existing shape, default: no modifier.
* “clear”: Clear the current shape, default: “escape”.
* “square”: Makes the shape square, default: “shift”.
* “center”: Make the initial point the center of the shape, default: “ctrl”.

 “square” and “center” can be combined.

     
  
`property corners`  
Corners of rectangle from lower left, moving clockwise.

 
  
`property edge_centers`  
Midpoint of rectangle edges from left, moving clockwise.

 
  
`property extents`  
Return (xmin, xmax, ymin, ymax).

 
  
`property geometry`  
Geometry information that gets passed to callback functions.

 
  
`on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L178-L187)

  
`on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L165-L176)

  
`on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L213-L229)

 
 ThickLineTool
-------------

  
`class skimage.viewer.canvastools.ThickLineTool(manager, on_move=None, on_enter=None, on_release=None, on_change=None, maxdist=10, line_props=None, handle_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L127-L198)
 
Bases: `skimage.viewer.canvastools.linetool.LineTool`

 Widget for line selection in a plot.

 The thickness of the line can be varied using the mouse scroll wheel, or with the ‘+’ and ‘-‘ keys.

  Parameters 
 
`managerViewer or PlotPlugin.` 

Skimage viewer or plot plugin object.

  
`on_movefunction` 

Function called whenever a control handle is moved. This function must accept the end points of line as the only argument.

  
`on_releasefunction` 

Function called whenever the control handle is released.

  
`on_enterfunction` 

Function called whenever the “enter” key is pressed.

  
`on_changefunction` 

Function called whenever the line thickness is changed.

  
`maxdistfloat` 

Maximum pixel distance allowed when selecting control handle.

  
`line_propsdict` 

Properties for [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)").

  
`handle_propsdict` 

Marker properties for the handles (also see [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)")).

    Attributes 
 
`end_points2D array` 

End points of line ((x1, y1), (x2, y2)).

      
`__init__(manager, on_move=None, on_enter=None, on_release=None, on_change=None, maxdist=10, line_props=None, handle_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L160-L173)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`on_key_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L183-L187)

  
`on_scroll(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L175-L181)

 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.canvastools.html>

Module: viewer.plugins
======================

 

|  |  |
| --- | --- |
| [`skimage.viewer.plugins.CannyPlugin`](#skimage.viewer.plugins.CannyPlugin "skimage.viewer.plugins.CannyPlugin")(\*args, …) | Canny filter plugin to show edges of an image. |
| [`skimage.viewer.plugins.ColorHistogram`](#skimage.viewer.plugins.ColorHistogram "skimage.viewer.plugins.ColorHistogram")([max\_pct]) |  |
| [`skimage.viewer.plugins.Crop`](#skimage.viewer.plugins.Crop "skimage.viewer.plugins.Crop")([maxdist]) |  |
| [`skimage.viewer.plugins.LabelPainter`](#skimage.viewer.plugins.LabelPainter "skimage.viewer.plugins.LabelPainter")([max\_radius]) |  |
| [`skimage.viewer.plugins.LineProfile`](#skimage.viewer.plugins.LineProfile "skimage.viewer.plugins.LineProfile")([…]) | Plugin to compute interpolated intensity under a scan line on an image. |
| [`skimage.viewer.plugins.Measure`](#skimage.viewer.plugins.Measure "skimage.viewer.plugins.Measure")([maxdist]) |  |
| [`skimage.viewer.plugins.OverlayPlugin`](#skimage.viewer.plugins.OverlayPlugin "skimage.viewer.plugins.OverlayPlugin")(\*\*kwargs) | Plugin for ImageViewer that displays an overlay on top of main image. |
| [`skimage.viewer.plugins.PlotPlugin`](#skimage.viewer.plugins.PlotPlugin "skimage.viewer.plugins.PlotPlugin")([…]) | Plugin for ImageViewer that contains a plot canvas. |
| [`skimage.viewer.plugins.Plugin`](#skimage.viewer.plugins.Plugin "skimage.viewer.plugins.Plugin")([…]) | Base class for plugins that interact with an ImageViewer. |
| `skimage.viewer.plugins.base` | Base class for Plugins that interact with ImageViewer. |
| `skimage.viewer.plugins.canny` |  |
| `skimage.viewer.plugins.color_histogram` |  |
| `skimage.viewer.plugins.crop` |  |
| `skimage.viewer.plugins.labelplugin` |  |
| `skimage.viewer.plugins.lineprofile` |  |
| `skimage.viewer.plugins.measure` |  |
| `skimage.viewer.plugins.overlayplugin` |  |
| `skimage.viewer.plugins.plotplugin` |  |

 CannyPlugin
-----------

  
`class skimage.viewer.plugins.CannyPlugin(*args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L9-L30)
 
Bases: `skimage.viewer.plugins.overlayplugin.OverlayPlugin`

 Canny filter plugin to show edges of an image.

  
`__init__(*args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L14-L15)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L17-L30)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.CannyPlugin.attach "skimage.viewer.plugins.CannyPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`name = 'Canny Filter'` 
 
 ColorHistogram
--------------

  
`class skimage.viewer.plugins.ColorHistogram(max_pct=0.99, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L8-L83)
 
Bases: `skimage.viewer.plugins.plotplugin.PlotPlugin`

  
`__init__(max_pct=0.99, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L11-L15)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`ab_selected(extents)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L51-L61)

  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L17-L22)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.ColorHistogram.attach "skimage.viewer.plugins.ColorHistogram.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L46-L49)

  
`name = 'Color Histogram'` 
  
`output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L63-L83)
 
Return the image mask and the histogram data.

  Returns 
 
`maskarray of bool, same shape as image` 

The selected pixels.

  
`datadict` 

The data describing the histogram and the selected region. The dictionary contains:

 * ‘bins’ : array of float The bin boundaries for both `a` and `b` channels.
* ‘hist’ : 2D array of float The normalized histogram.
* ‘edges’ : tuple of array of float The bin edges along each dimension
* ‘extents’ : tuple of float The left and right and top and bottom of the selected region.

     
 
 Crop
----

  
`class skimage.viewer.plugins.Crop(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L9-L45)
 
Bases: `skimage.viewer.plugins.base.Plugin`

  
`__init__(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L12-L16)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L18-L27)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.Crop.attach "skimage.viewer.plugins.Crop.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`crop(extents)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L34-L40)

  
`help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L29-L32)

  
`name = 'Crop'` 
  
`reset()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L42-L45)

 
 LabelPainter
------------

  
`class skimage.viewer.plugins.LabelPainter(max_radius=20, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L14-L67)
 
Bases: `skimage.viewer.plugins.base.Plugin`

  
`__init__(max_radius=20, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L17-L29)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L36-L44)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.LabelPainter.attach "skimage.viewer.plugins.LabelPainter.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L31-L34)

  
`property label` 
  
`name = 'LabelPainter'` 
  
`on_enter(overlay)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L50-L51)

  
`property radius` 
 
 LineProfile
-----------

  
`class skimage.viewer.plugins.LineProfile(maxdist=10, epsilon='deprecated', limits='image', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L13-L167)
 
Bases: `skimage.viewer.plugins.plotplugin.PlotPlugin`

 Plugin to compute interpolated intensity under a scan line on an image.

 See PlotPlugin and Plugin classes for additional details.

  Parameters 
 
`maxdistfloat` 

Maximum pixel distance allowed when selecting end point of scan line.

  
`limitstuple or {None, ‘image’, ‘dtype’}` 

(minimum, maximum) intensity limits for plotted profile. The following special values are defined:

 None : rescale based on min/max intensity along selected scan line. ‘image’ : fixed scale based on min/max intensity in image. ‘dtype’ : fixed scale based on min/max intensity of image dtype.

      
`__init__(maxdist=10, epsilon='deprecated', limits='image', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L32-L37)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L39-L75)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.LineProfile.attach "skimage.viewer.plugins.LineProfile.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`get_profiles()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L83-L95)
 
Return intensity profile of the selected line.

  Returns 
 end\_points: (2, 2) array

The positions ((x1, y1), (x2, y2)) of the line ends.

  profile: list of 1d arrays

Profile of intensity values. Length 1 (grayscale) or 3 (rgb).

     
  
`help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L77-L81)

  
`line_changed(end_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L103-L110)

  
`name = 'Line Profile'` 
  
`output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L140-L167)
 
Return the drawn line and the resulting scan.

  Returns 
 
`line_image(M, N) uint8 array, same shape as image` 

An array of 0s with the scanned line set to 255. If the linewidth of the line tool is greater than 1, sets the values within the profiled polygon to 128.

  
`scan(P,) or (P, 3) array of int or float` 

The line scan values across the image.

     
  
`reset_axes(scan_data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L128-L138)

 
 Measure
-------

  
`class skimage.viewer.plugins.Measure(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L14-L49)
 
Bases: `skimage.viewer.plugins.base.Plugin`

  
`__init__(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L17-L27)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L29-L37)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.Measure.attach "skimage.viewer.plugins.Measure.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L39-L42)

  
`line_changed(end_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L44-L49)

  
`name = 'Measure'` 
 
 OverlayPlugin
-------------

  
`class skimage.viewer.plugins.OverlayPlugin(**kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L12-L114)
 
Bases: `skimage.viewer.plugins.base.Plugin`

 Plugin for ImageViewer that displays an overlay on top of main image.

 The base Plugin class displays the filtered image directly on the viewer. OverlayPlugin will instead overlay an image with a transparent colormap.

 See base Plugin class for additional details.

  Attributes 
 
`overlayarray` 

Overlay displayed on top of image. This overlay defaults to a color map with alpha values varying linearly from 0 to 1.

  
`colorint` 

Color of overlay.

      
`__init__(**kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L33-L38)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L40-L43)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.OverlayPlugin.attach "skimage.viewer.plugins.OverlayPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L100-L103)
 
On close disconnect all artists and events from ImageViewer.

 Note that artists must be appended to `self.artists`.

 
  
`property color` 
  
`colors = {'cyan': (0, 1, 1), 'green': (0, 1, 0), 'red': (1, 0, 0), 'yellow': (1, 1, 0)}` 
  
`display_filtered_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L96-L98)
 
Display filtered image as an overlay on top of image in viewer.

 
  
`property filtered_image`  
Return filtered image.

 This “filtered image” is used when saving from the plugin.

 
  
`output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L105-L114)
 
Return the overlaid image.

  Returns 
 
`overlayarray, same shape as image` 

The overlay currently displayed.

  
`dataNone` 
   
  
`property overlay` 
 
 PlotPlugin
----------

  
`class skimage.viewer.plugins.PlotPlugin(image_filter=None, height=150, width=400, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L12-L74)
 
Bases: `skimage.viewer.plugins.base.Plugin`

 Plugin for ImageViewer that contains a plot canvas.

 Base class for plugins that contain a Matplotlib plot canvas, which can, for example, display an image histogram.

 See base Plugin class for additional details.

  
`__init__(image_filter=None, height=150, width=400, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L21-L29)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`add_plot()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L43-L56)

  
`add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L62-L66)

  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L31-L37)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.PlotPlugin.attach "skimage.viewer.plugins.PlotPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L39-L41)
 
Redraw plot.

 
  
`remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L68-L74)

 
 Plugin
------

  
`class skimage.viewer.plugins.Plugin(image_filter=None, height=0, width=400, useblit=True, dock='bottom')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L11-L261)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Base class for plugins that interact with an ImageViewer.

 A plugin connects an image filter (or another function) to an image viewer. Note that a Plugin is initialized *without* an image viewer and attached in a later step. See example below for details.

  Parameters 
 
`image_viewerImageViewer` 

Window containing image used in measurement/manipulation.

  
`image_filterfunction` 

Function that gets called to update image in image viewer. This value can be `None` if, for example, you have a plugin that extracts information from an image and doesn’t manipulate it. Alternatively, this function can be defined as a method in a Plugin subclass.

  
`height, widthint` 

Size of plugin window in pixels. Note that Qt will automatically resize a window to fit components. So if you’re adding rows of components, you can leave `height = 0` and just let Qt determine the final height.

  
`useblitbool` 

If True, use blitting to speed up animation. Only available on some Matplotlib backends. If None, set to True when using Agg backend. This only has an effect if you draw on top of an image viewer.

     #### Examples

 
```
>>> from skimage.viewer import ImageViewer
>>> from skimage.viewer.widgets import Slider
>>> from skimage import data
>>>
>>> plugin = Plugin(image_filter=lambda img,
...                 threshold: img > threshold) 
>>> plugin += Slider('threshold', 0, 255)       
>>>
>>> image = data.coins()
>>> viewer = ImageViewer(image)       
>>> viewer += plugin                  
>>> thresholded = viewer.show()[0][0] 

```
 The plugin will automatically delegate parameters to `image_filter` based on its parameter type, i.e., `ptype` (widgets for required arguments must be added in the order they appear in the function). The image attached to the viewer is **automatically passed as the first argument** to the filter function.

 #TODO: Add flag so image is not passed to filter function by default.

 `ptype = ‘kwarg’` is the default for most widgets so it’s unnecessary here.

  Attributes 
 
`image_viewerImageViewer` 

Window containing image used in measurement.

  
`namestr` 

Name of plugin. This is displayed as the window title.

  
`artistlist` 

List of Matplotlib artists and canvastools. Any artists created by the plugin should be added to this list so that it gets cleaned up on close.

      
`__init__(image_filter=None, height=0, width=400, useblit=True, dock='bottom')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L80-L105)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`add_widget(widget)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L129-L150)
 
Add widget to plugin.

 Alternatively, Plugin’s `__add__` method is overloaded to add widgets:

 
```
plugin += Widget(...)

```
 Widgets can adjust required or optional arguments of filter function or parameters for the plugin. This is specified by the Widget’s `ptype`.

 
  
`attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L107-L127)
 
Attach the plugin to an ImageViewer.

 Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example:

 
```
viewer += Plugin(...)

```
 Also note that [`attach`](#skimage.viewer.plugins.Plugin.attach "skimage.viewer.plugins.Plugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets.

 
  
`clean_up()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L232-L237)

  
`closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L224-L230)
 
On close disconnect all artists and events from ImageViewer.

 Note that artists must be appended to `self.artists`.

 
  
`display_filtered_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L196-L203)
 
Display the filtered image on image viewer.

 If you don’t want to simply replace the displayed image with the filtered image (e.g., you want to display a transparent overlay), you can override this method.

 
  
`filter_image(*widget_arg)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L156-L172)
 
Call `image_filter` with widget args and kwargs

 Note: [`display_filtered_image`](#skimage.viewer.plugins.Plugin.display_filtered_image "skimage.viewer.plugins.Plugin.display_filtered_image") is automatically called.

 
  
`property filtered_image`  
Return filtered image.

 
  
`image_changed = None` 
  
`image_viewer = 'Plugin is not attached to ImageViewer'` 
  
`name = 'Plugin'` 
  
`output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L244-L261)
 
Return the plugin’s representation and data.

  Returns 
 
`imagearray, same shape as self.image_viewer.image, or None` 

The filtered image.

  
`dataNone` 

Any data associated with the plugin.

     #### Notes

 Derived classes should override this method to return a tuple containing an *overlay* of the same shape of the image, and a *data* object. Either of these is optional: return `None` if you don’t want to return a value.

 
  
`remove_image_artists()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L239-L242)
 
Remove artists that are connected to the image viewer.

 
  
`show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L213-L222)
 
Show plugin.

 
  
`update_plugin(name, value)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L205-L211)
 
Update keyword parameters of the plugin itself.

 These parameters will typically be implemented as class properties so that they update the image or some other component.

 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.plugins.html>

Module: viewer.utils
====================

 

|  |  |
| --- | --- |
| [`skimage.viewer.utils.figimage`](#skimage.viewer.utils.figimage "skimage.viewer.utils.figimage")(image[, …]) | Return figure and axes with figure tightly surrounding image. |
| [`skimage.viewer.utils.init_qtapp`](#skimage.viewer.utils.init_qtapp "skimage.viewer.utils.init_qtapp")() | Initialize QAppliction. |
| [`skimage.viewer.utils.new_plot`](#skimage.viewer.utils.new_plot "skimage.viewer.utils.new_plot")([parent, …]) | Return new figure and axes. |
| [`skimage.viewer.utils.start_qtapp`](#skimage.viewer.utils.start_qtapp "skimage.viewer.utils.start_qtapp")([app]) | Start Qt mainloop |
| [`skimage.viewer.utils.update_axes_image`](#skimage.viewer.utils.update_axes_image "skimage.viewer.utils.update_axes_image")(…) | Update the image displayed by an image plot. |
| [`skimage.viewer.utils.ClearColormap`](#skimage.viewer.utils.ClearColormap "skimage.viewer.utils.ClearColormap")(rgb[, …]) | Color map that varies linearly from alpha = 0 to 1 |
| [`skimage.viewer.utils.FigureCanvas`](#skimage.viewer.utils.FigureCanvas "skimage.viewer.utils.FigureCanvas")(figure, …) | Canvas for displaying images. |
| [`skimage.viewer.utils.LinearColormap`](#skimage.viewer.utils.LinearColormap "skimage.viewer.utils.LinearColormap")(name, …) | LinearSegmentedColormap in which color varies smoothly. |
| [`skimage.viewer.utils.RequiredAttr`](#skimage.viewer.utils.RequiredAttr "skimage.viewer.utils.RequiredAttr")([init\_val]) | A class attribute that must be set before use. |
| `skimage.viewer.utils.canvas` |  |
| `skimage.viewer.utils.core` |  |
| `skimage.viewer.utils.dialogs` |  |

 figimage
--------

  
`skimage.viewer.utils.figimage(image, scale=1, dpi=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L163-L193)
 
Return figure and axes with figure tightly surrounding image.

 Unlike pyplot.figimage, this actually plots onto an axes object, which fills the figure. Plotting the image onto an axes allows for subsequent overlays of axes artists.

  Parameters 
 
`imagearray` 

image to plot

  
`scalefloat` 

If scale is 1, the figure and axes have the same dimension as the image. Smaller values of `scale` will shrink the figure.

  
`dpiint` 

Dots per inch for figure. If None, use the default rcParam.

     
 init\_qtapp
-----------

  
`skimage.viewer.utils.init_qtapp()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L22-L31)
 
Initialize QAppliction.

 The QApplication needs to be initialized before creating any QWidgets

 
 new\_plot
---------

  
`skimage.viewer.utils.new_plot(parent=None, subplot_kw=None, **fig_kw)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L140-L160)
 
Return new figure and axes.

  Parameters 
 
`parentQtWidget` 

Qt widget that displays the plot objects. If None, you must manually call `canvas.setParent` and pass the parent widget.

  
`subplot_kwdict` 

Keyword arguments passed `matplotlib.figure.Figure.add_subplot`.

  
`fig_kwdict` 

Keyword arguments passed `matplotlib.figure.Figure`.

     
 start\_qtapp
------------

  
`skimage.viewer.utils.start_qtapp(app=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L44-L53)
 
Start Qt mainloop

 
 update\_axes\_image
-------------------

  
`skimage.viewer.utils.update_axes_image(image_axes, image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L196-L212)
 
Update the image displayed by an image plot.

 This sets the image plot’s array and updates its shape appropriately

  Parameters 
 
`image_axesmatplotlib.image.AxesImage` 

Image axes to update.

  
`imagearray` 

Image array.

     
 ClearColormap
-------------

  
`class skimage.viewer.utils.ClearColormap(rgb, max_alpha=1, name='clear_color')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L99-L108)
 
Bases: `skimage.viewer.utils.core.LinearColormap`

 Color map that varies linearly from alpha = 0 to 1

  
`__init__(rgb, max_alpha=1, name='clear_color')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L102-L108)
 
Create color map from linear mapping segments

 segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are optional.

 Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use:

 
```
cdict = {'red':   [(0.0,  0.0, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  1.0, 1.0)],

         'green': [(0.0,  0.0, 0.0),
                   (0.25, 0.0, 0.0),
                   (0.75, 1.0, 1.0),
                   (1.0,  1.0, 1.0)],

         'blue':  [(0.0,  0.0, 0.0),
                   (0.5,  0.0, 0.0),
                   (1.0,  1.0, 1.0)]}

```
 Each row in the table for a given color is a sequence of *x*, *y0*, *y1* tuples. In each sequence, *x* must increase monotonically from 0 to 1. For any input value *z* falling between *x[i]* and *x[i+1]*, the output value of a given color will be linearly interpolated between *y1[i]* and *y0[i+1]*:

 
```
row i:   x  y0  y1
               /
              /
row i+1: x  y0  y1

```
 Hence y0 in the first row and y1 in the last row are never used.

  See also

  
`LinearSegmentedColormap.from_list` 

Static method; factory function for generating a smoothly-varying LinearSegmentedColormap.

  
`makeMappingArray` 

For information about making a mapping array.

    
 
 FigureCanvas
------------

  
`class skimage.viewer.utils.FigureCanvas(figure, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L111-L125)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Canvas for displaying images.

  
`__init__(figure, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L113-L119)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`resizeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L121-L125)

 
 LinearColormap
--------------

  
`class skimage.viewer.utils.LinearColormap(name, segmented_data, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L74-L96)
 
Bases: [`matplotlib.colors.LinearSegmentedColormap`](https://matplotlib.org/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html#matplotlib.colors.LinearSegmentedColormap "(in Matplotlib v3.3.3)")

 LinearSegmentedColormap in which color varies smoothly.

 This class is a simplification of LinearSegmentedColormap, which doesn’t support jumps in color intensities.

  Parameters 
 
`namestr` 

Name of colormap.

  
`segmented_datadict` 

Dictionary of ‘red’, ‘green’, ‘blue’, and (optionally) ‘alpha’ values. Each color key contains a list of `x`, `y` tuples. `x` must increase monotonically from 0 to 1 and corresponds to input values for a mappable object (e.g. an image). `y` corresponds to the color intensity.

      
`__init__(name, segmented_data, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L93-L96)
 
Create color map from linear mapping segments

 segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are optional.

 Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use:

 
```
cdict = {'red':   [(0.0,  0.0, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  1.0, 1.0)],

         'green': [(0.0,  0.0, 0.0),
                   (0.25, 0.0, 0.0),
                   (0.75, 1.0, 1.0),
                   (1.0,  1.0, 1.0)],

         'blue':  [(0.0,  0.0, 0.0),
                   (0.5,  0.0, 0.0),
                   (1.0,  1.0, 1.0)]}

```
 Each row in the table for a given color is a sequence of *x*, *y0*, *y1* tuples. In each sequence, *x* must increase monotonically from 0 to 1. For any input value *z* falling between *x[i]* and *x[i+1]*, the output value of a given color will be linearly interpolated between *y1[i]* and *y0[i+1]*:

 
```
row i:   x  y0  y1
               /
              /
row i+1: x  y0  y1

```
 Hence y0 in the first row and y1 in the last row are never used.

  See also

  
`LinearSegmentedColormap.from_list` 

Static method; factory function for generating a smoothly-varying LinearSegmentedColormap.

  
`makeMappingArray` 

For information about making a mapping array.

    
 
 RequiredAttr
------------

  
`class skimage.viewer.utils.RequiredAttr(init_val=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L56-L71)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 A class attribute that must be set before use.

  
`__init__(init_val=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L61-L62)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`instances = {(<skimage.viewer.utils.core.RequiredAttr object>, None): 'Widget is not attached to a Plugin.', (<skimage.viewer.utils.core.RequiredAttr object>, None): 'Plugin is not attached to ImageViewer'}` 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.utils.html>

Module: viewer.viewers
======================

 

|  |  |
| --- | --- |
| [`skimage.viewer.viewers.CollectionViewer`](#skimage.viewer.viewers.CollectionViewer "skimage.viewer.viewers.CollectionViewer")(…) | Viewer for displaying image collections. |
| [`skimage.viewer.viewers.ImageViewer`](#skimage.viewer.viewers.ImageViewer "skimage.viewer.viewers.ImageViewer")(image[, …]) | Viewer for displaying images. |
| `skimage.viewer.viewers.core` | ImageViewer class for viewing and interacting with images. |

 CollectionViewer
----------------

  
`class skimage.viewer.viewers.CollectionViewer(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L331-L407)
 
Bases: `skimage.viewer.viewers.core.ImageViewer`

 Viewer for displaying image collections.

 Select the displayed frame of the image collection using the slider or with the following keyboard shortcuts:

  left/right arrows

Previous/next image in collection.

  number keys, 0–9

0% to 90% of collection. For example, “5” goes to the image in the middle (i.e. 50%) of the collection.

  home/end keys

First/last image in collection.

    Parameters 
 
`image_collectionlist of images` 

List of images to be displayed.

  
`update_on{‘move’ | ‘release’}` 

Control whether image is updated on slide or release of the image slider. Using ‘on\_release’ will give smoother behavior when displaying large images or when writing a plugin/subclass that requires heavy computation.

      
`__init__(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L356-L379)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`keyPressEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L396-L407)

  
`update_index(name, index)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L381-L394)
 
Select image on display using index into image collection.

 
 
 ImageViewer
-----------

  
`class skimage.viewer.viewers.ImageViewer(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L49-L328)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

 Viewer for displaying images.

 This viewer is a simple container object that holds a Matplotlib axes for showing images. [`ImageViewer`](#skimage.viewer.viewers.ImageViewer "skimage.viewer.viewers.ImageViewer") doesn’t subclass the Matplotlib axes (or figure) because of the high probability of name collisions.

 Subclasses and plugins will likely extend the [`update_image`](#skimage.viewer.viewers.ImageViewer.update_image "skimage.viewer.viewers.ImageViewer.update_image") method to add custom overlays or filter the displayed image.

  Parameters 
 
`imagearray` 

Image being viewed.

     #### Examples

 
```
>>> from skimage import data
>>> image = data.coins()
>>> viewer = ImageViewer(image) 
>>> viewer.show()               

```
  Attributes 
 
`canvas, fig, axMatplotlib canvas, figure, and axes` 

Matplotlib canvas, figure, and axes used to display image.

  
`imagearray` 

Image being viewed. Setting this value will update the displayed frame.

  
`original_imagearray` 

Plugins typically operate on (but don’t change) the *original* image.

  
`pluginslist` 

List of attached plugins.

      
`__init__(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L92-L151)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L307-L311)

  
`closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L237-L238)

  
`connect_event(event, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L292-L295)
 
Connect callback function to matplotlib event and return id.

 
  
`disconnect_event(callback_id)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L297-L299)
 
Disconnect callback by its id (returned by [`connect_event`](#skimage.viewer.viewers.ImageViewer.connect_event "skimage.viewer.viewers.ImageViewer.connect_event")).

 
  
`dock_areas = {'bottom': None, 'left': None, 'right': None, 'top': None}` 
  
`property image` 
  
`open_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L186-L193)
 
Open image file and display in viewer.

 
  
`original_image_changed = None` 
  
`redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L258-L262)

  
`remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L313-L319)

  
`reset_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L289-L290)

  
`save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L208-L235)
 
Save current image to file.

 The current behavior is not ideal: It saves the image displayed on screen, so all images will be converted to RGB, and the image size is not preserved (resizing the viewer window will alter the size of the saved image).

 
  
`show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L248-L256)
 
Show ImageViewer and attached plugins.

 This behaves much like [`matplotlib.pyplot.show`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show "(in Matplotlib v3.3.3)") and `QWidget.show`.

 
  
`update_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L195-L201)
 
Update displayed image.

 This method can be overridden or extended in subclasses and plugins to react to image changes.

 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.viewers.html>

Module: viewer.widgets
======================

 Widgets for interacting with ImageViewer.

 These widgets should be added to a Plugin subclass using its `add_widget` method or calling:

 
```
plugin += Widget(...)

```
 on a Plugin instance. The Plugin will delegate action based on the widget’s parameter type specified by its `ptype` attribute, which can be:

 
```
'arg' : positional argument passed to Plugin's `filter_image` method.
'kwarg' : keyword argument passed to Plugin's `filter_image` method.
'plugin' : attribute of Plugin. You'll probably need to add a class
    property of the same name that updates the display.

```
 

|  |  |
| --- | --- |
| [`skimage.viewer.widgets.BaseWidget`](#skimage.viewer.widgets.BaseWidget "skimage.viewer.widgets.BaseWidget")(name[, …]) |  |
| [`skimage.viewer.widgets.Button`](#skimage.viewer.widgets.Button "skimage.viewer.widgets.Button")(name, callback) | Button which calls callback upon click. |
| [`skimage.viewer.widgets.CheckBox`](#skimage.viewer.widgets.CheckBox "skimage.viewer.widgets.CheckBox")(name[, …]) | CheckBox widget |
| [`skimage.viewer.widgets.ComboBox`](#skimage.viewer.widgets.ComboBox "skimage.viewer.widgets.ComboBox")(name, items) | ComboBox widget for selecting among a list of choices. |
| [`skimage.viewer.widgets.OKCancelButtons`](#skimage.viewer.widgets.OKCancelButtons "skimage.viewer.widgets.OKCancelButtons")([…]) | Buttons that close the parent plugin. |
| [`skimage.viewer.widgets.SaveButtons`](#skimage.viewer.widgets.SaveButtons "skimage.viewer.widgets.SaveButtons")([name, …]) | Buttons to save image to io.stack or to a file. |
| [`skimage.viewer.widgets.Slider`](#skimage.viewer.widgets.Slider "skimage.viewer.widgets.Slider")(name[, low, …]) | Slider widget for adjusting numeric parameters. |
| [`skimage.viewer.widgets.Text`](#skimage.viewer.widgets.Text "skimage.viewer.widgets.Text")([name, text]) |  |
| `skimage.viewer.widgets.core` |  |
| `skimage.viewer.widgets.history` |  |

 BaseWidget
----------

  
`class skimage.viewer.widgets.BaseWidget(name, ptype=None, callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L8-L25)
 
Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)")

  
`__init__(name, ptype=None, callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L12-L17)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`plugin = 'Widget is not attached to a Plugin.'` 
  
`property val` 
 
 Button
------

  
`class skimage.viewer.widgets.Button(name, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L292-L309)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 Button which calls callback upon click.

  Parameters 
 
`namestr` 

Name of button.

  
`callbackcallable f()` 

Function to call when button is clicked.

      
`__init__(name, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L303-L309)
 
Initialize self. See help(type(self)) for accurate signature.

 
 
 CheckBox
--------

  
`class skimage.viewer.widgets.CheckBox(name, value=False, alignment='center', ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L239-L289)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 CheckBox widget

  Parameters 
 
`namestr` 

Name of CheckBox parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the CheckBox.

  **value: {False, True}, optional**

Initial state of the CheckBox.

  **alignment: {‘center’,’left’,’right’}, optional**

Checkbox alignment

  
`ptype{‘arg’ | ‘kwarg’ | ‘plugin’}, optional` 

Parameter type

  
`callbackcallable f(widget_name, value), optional` 

Callback function called in response to checkbox changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin.

      
`__init__(name, value=False, alignment='center', ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L261-L281)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property val` 
 
 ComboBox
--------

  
`class skimage.viewer.widgets.ComboBox(name, items, ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L190-L236)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 ComboBox widget for selecting among a list of choices.

  Parameters 
 
`namestr` 

Name of ComboBox parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the ComboBox.

  **items: list of str**

Allowed parameter values.

  
`ptype{‘arg’ | ‘kwarg’ | ‘plugin’}, optional` 

Parameter type.

  
`callbackcallable f(widget_name, value), optional` 

Callback function called in response to combobox changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin.

      
`__init__(name, items, ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L210-L224)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property index` 
  
`property val` 
 
 OKCancelButtons
---------------

  
`class skimage.viewer.widgets.OKCancelButtons(button_width=80)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L15-L47)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 Buttons that close the parent plugin.

 OK will replace the original image with the current (filtered) image. Cancel will just close the plugin.

  
`__init__(button_width=80)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L22-L38)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`close_plugin()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L45-L47)

  
`update_original_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L40-L43)

 
 SaveButtons
-----------

  
`class skimage.viewer.widgets.SaveButtons(name='Save to:', default_format='png')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L50-L92)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 Buttons to save image to io.stack or to a file.

  
`__init__(name='Save to:', default_format='png')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L53-L71)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L83-L92)

  
`save_to_stack()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L73-L81)

 
 Slider
------

  
`class skimage.viewer.widgets.Slider(name, low=0.0, high=1.0, value=None, value_type='float', ptype='kwarg', callback=None, max_edit_width=60, orientation='horizontal', update_on='release')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L50-L187)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

 Slider widget for adjusting numeric parameters.

  Parameters 
 
`namestr` 

Name of slider parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the slider.

  
`low, highfloat` 

Range of slider values.

  
`valuefloat` 

Default slider value. If None, use midpoint between `low` and `high`.

  
`value_type{‘float’ | ‘int’}, optional` 

Numeric type of slider value.

  
`ptype{‘kwarg’ | ‘arg’ | ‘plugin’}, optional` 

Parameter type.

  
`callbackcallable f(widget_name, value), optional` 

Callback function called in response to slider changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin.

  
`orientation{‘horizontal’ | ‘vertical’}, optional` 

Slider orientation.

  
`update_on{‘release’ | ‘move’}, optional` 

Control when callback function is called: on slider move or release.

      
`__init__(name, low=0.0, high=1.0, value=None, value_type='float', ptype='kwarg', callback=None, max_edit_width=60, orientation='horizontal', update_on='release')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L78-L147)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property val` 
 
 Text
----

  
`class skimage.viewer.widgets.Text(name=None, text='')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L28-L47)
 
Bases: `skimage.viewer.widgets.core.BaseWidget`

  
`__init__(name=None, text='')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L30-L39)
 
Initialize self. See help(type(self)) for accurate signature.

 
  
`property text` 
 


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/api/skimage.viewer.widgets.html>

Getting started
===============

 `scikit-image` is an image processing Python package that works with [`numpy`](https://numpy.org/doc/stable/reference/index.html#module-numpy "(in NumPy v1.19)") arrays. The package is imported as `skimage`:

 
```
>>> import skimage

```
 Most functions of `skimage` are found within submodules:

 
```
>>> from skimage import data
>>> camera = data.camera()

```
 A list of submodules and functions is found on the [API reference](https://scikit-image.org/docs/stable/api/api.html) webpage.

 Within scikit-image, images are represented as NumPy arrays, for example 2-D arrays for grayscale 2-D images

 
```
>>> type(camera)
<type 'numpy.ndarray'>
>>> # An image with 512 rows and 512 columns
>>> camera.shape
(512, 512)

```
 The [`skimage.data`](../api/skimage.data#module-skimage.data "skimage.data") submodule provides a set of functions returning example images, that can be used to get started quickly on using scikit-image’s functions:

 
```
>>> coins = data.coins()
>>> from skimage import filters
>>> threshold_value = filters.threshold_otsu(coins)
>>> threshold_value
107

```
 Of course, it is also possible to load your own images as NumPy arrays from image files, using [`skimage.io.imread()`](../api/skimage.io#skimage.io.imread "skimage.io.imread"):

 
```
>>> import os
>>> filename = os.path.join(skimage.data_dir, 'moon.png')
>>> from skimage import io
>>> moon = io.imread(filename)

```
 Use [natsort](https://pypi.org/project/natsort/) to load multiple images

 
```
>>> import os
>>> from natsort import natsorted, ns
>>> from skimage import io
>>> list_files = os.listdir('.')
>>> list_files
['01.png', '010.png', '0101.png', '0190.png', '02.png']
>>> list_files = natsorted(list_files)
>>> list_files
['01.png', '02.png', '010.png', '0101.png', '0190.png']
>>> image_list = []
>>> for filename in list_files:
...   image_list.append(io.imread(filename))

```


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/getting_started.html>

A crash course on NumPy for images
==================================

 Images in `scikit-image` are represented by NumPy ndarrays. Hence, many common operations can be achieved using standard NumPy methods for manipulating arrays:

 
```
>>> from skimage import data
>>> camera = data.camera()
>>> type(camera)
<type 'numpy.ndarray'>

```
 Retrieving the geometry of the image and the number of pixels:

 
```
>>> camera.shape
(512, 512)
>>> camera.size
262144

```
 Retrieving statistical information about image intensity values:

 
```
>>> camera.min(), camera.max()
(0, 255)
>>> camera.mean()
118.31400299072266

```
 NumPy arrays representing images can be of different integer or float numerical types. See [Image data types and what they mean](data_types#data-types) for more information about these types and how `scikit-image` treats them.

 NumPy indexing
--------------

 NumPy indexing can be used both for looking at the pixel values and to modify them:

 
```
>>> # Get the value of the pixel at the 10th row and 20th column
>>> camera[10, 20]
153
>>> # Set to black the pixel at the 3rd row and 10th column
>>> camera[3, 10] = 0

```
 Be careful! In NumPy indexing, the first dimension (`camera.shape[0]`) corresponds to rows, while the second (`camera.shape[1]`) corresponds to columns, with the origin (`camera[0, 0]`) at the top-left corner. This matches matrix/linear algebra notation, but is in contrast to Cartesian (x, y) coordinates. See [Coordinate conventions](#coordinate-conventions) below for more details.

 Beyond individual pixels, it is possible to access/modify values of whole sets of pixels using the different indexing capabilities of NumPy.

 Slicing:

 
```
>>> # Set the first ten lines to "black" (0)
>>> camera[:10] = 0

```
 Masking (indexing with masks of booleans):

 
```
>>> mask = camera < 87
>>> # Set to "white" (255) the pixels where mask is True
>>> camera[mask] = 255

```
 Fancy indexing (indexing with sets of indices):

 
```
>>> inds_r = np.arange(len(camera))
>>> inds_c = 4 * inds_r % len(camera)
>>> camera[inds_r, inds_c] = 0

```
 Masks are very useful when you need to select a set of pixels on which to perform the manipulations. The mask can be any boolean array of the same shape as the image (or a shape broadcastable to the image shape). This can be used to define a region of interest, for example, a disk:

 
```
>>> nrows, ncols = camera.shape
>>> row, col = np.ogrid[:nrows, :ncols]
>>> cnt_row, cnt_col = nrows / 2, ncols / 2
>>> outer_disk_mask = ((row - cnt_row)**2 + (col - cnt_col)**2 >
...                    (nrows / 2)**2)
>>> camera[outer_disk_mask] = 0

```
 [![../_images/sphx_glr_plot_camera_numpy_0011.png] Boolean operations from NumPy can be used to define even more complex masks:

 
```
>>> lower_half = row > cnt_row
>>> lower_half_disk = np.logical_and(lower_half, outer_disk_mask)
>>> camera = data.camera()
>>> camera[lower_half_disk] = 0

```
 Color images
------------

 All of the above remains true for color images. A color image is a NumPy array with an additional trailing dimension for the channels:

 
```
>>> cat = data.chelsea()
>>> type(cat)
<type 'numpy.ndarray'>
>>> cat.shape
(300, 451, 3)

```
 This shows that `cat` is a 300-by-451 pixel image with three channels (red, green, and blue). As before, we can get and set the pixel values:

 
```
>>> cat[10, 20]
array([151, 129, 115], dtype=uint8)
>>> # Set the pixel at (50th row, 60th column) to "black"
>>> cat[50, 60] = 0
>>> # set the pixel at (50th row, 61st column) to "green"
>>> cat[50, 61] = [0, 255, 0]  # [red, green, blue]

```
 We can also use 2D boolean masks for 2D multichannel images, as we did with the grayscale image above:

 Using a 2D mask on a 2D color image

 
```
>>> from skimage import data
>>> cat = data.chelsea()
>>> reddish = cat[:, :, 0] > 160
>>> cat[reddish] = [0, 255, 0]
>>> plt.imshow(cat)

```
 ([Source code](numpy_images-1.py), [png](numpy_images-1.png), [pdf](numpy_images-1.pdf))

  ![../_images/numpy_images-1.png]  Coordinate conventions
----------------------

 Because `scikit-image` represents images using NumPy arrays, the coordinate conventions must match. Two-dimensional (2D) grayscale images (such as `camera` above) are indexed by rows and columns (abbreviated to either `(row, col)` or `(r, c)`), with the lowest element `(0, 0)` at the top-left corner. In various parts of the library, you will also see `rr` and `cc` refer to lists of row and column coordinates. We distinguish this convention from `(x, y)`, which commonly denote standard Cartesian coordinates, where `x` is the horizontal coordinate, `y` - the vertical one, and the origin is at the bottom left (Matplotlib axes, for example, use this convention).

 In the case of multichannel images, the last dimension is used for color channels and is denoted by `channel` or `ch`.

 Finally, for volumetric (3D) images, such as videos, magnetic resonance imaging (MRI) scans, confocal microscopy, etc. we refer to the leading dimension as `plane`, abbreviated as `pln` or `p`.

 These conventions are summarized below:

 

Dimension name and order conventions in scikit-image| Image type | Coordinates |
| --- | --- |
| 2D grayscale | (row, col) |
| 2D multichannel (eg. RGB) | (row, col, ch) |
| 3D grayscale | (pln, row, col) |
| 3D multichannel | (pln, row, col, ch) |

 Many functions in `scikit-image` can operate on 3D images directly:

 
```
>>> im3d = np.random.rand(100, 1000, 1000)
>>> from skimage import morphology
>>> from scipy import ndimage as ndi
>>> seeds = ndi.label(im3d < 0.1)[0]
>>> ws = morphology.watershed(im3d, seeds)

```
 In many cases, however, the third spatial dimension has lower resolution than the other two. Some `scikit-image` functions provide a `spacing` keyword argument to help handle this kind of data:

 
```
>>> from skimage import segmentation
>>> slics = segmentation.slic(im3d, spacing=[5, 1, 1], multichannel=False)

```
 Other times, the processing must be done plane-wise. When planes are stacked along the leading dimension (in agreement with our convention), the following syntax can be used:

 
```
>>> from skimage import filters
>>> edges = np.empty_like(im3d)
>>> for pln, image in enumerate(im3d):
...     # Iterate over the leading dimension
...     edges[pln] = filters.sobel(image)

```
 Notes on the order of array dimensions
--------------------------------------

 Although the labeling of the axes might seem arbitrary, it can have a significant effect on the speed of operations. This is because modern processors never retrieve just one item from memory, but rather a whole chunk of adjacent items (an operation called prefetching). Therefore, processing of elements that are next to each other in memory is faster than processing them when they are scattered, even if the number of operations is the same:

 
```
>>> def in_order_multiply(arr, scalar):
...     for plane in list(range(arr.shape[0])):
...         arr[plane, :, :] *= scalar
...
>>> def out_of_order_multiply(arr, scalar):
...     for plane in list(range(arr.shape[2])):
...         arr[:, :, plane] *= scalar
...
>>> import time
>>> im3d = np.random.rand(100, 1024, 1024)
>>> t0 = time.time(); x = in_order_multiply(im3d, 5); t1 = time.time()
>>> print("%.2f seconds" % (t1 - t0))  
0.14 seconds
>>> s0 = time.time(); x = out_of_order_multiply(im3d, 5); s1 = time.time()
>>> print("%.2f seconds" % (s1 - s0))  
1.18 seconds
>>> print("Speedup: %.1fx" % ((s1 - s0) / (t1 - t0)))  
Speedup: 8.6x

```
 When the last/rightmost dimension becomes even larger the speedup is even more dramatic. It is worth thinking about *data locality* when developing algorithms. In particular, `scikit-image` uses C-contiguous arrays by default. When using nested loops, the last/rightmost dimension of the array should be in the innermost loop of the computation. In the example above, the `*=` numpy operator iterates over all remaining dimensions.

 A note on the time dimension
----------------------------

 Although `scikit-image` does not currently provide functions to work specifically with time-varying 3D data, its compatibility with NumPy arrays allows us to work quite naturally with a 5D array of the shape (t, pln, row, col, ch):

 
```
>>> for timepoint in image5d:  
...     # Each timepoint is a 3D multichannel image
...     do_something_with(timepoint)

```
 We can then supplement the above table as follows:

 

Addendum to dimension names and orders in scikit-image| Image type | coordinates |
| --- | --- |
| 2D color video | (t, row, col, ch) |
| 3D multichannel video | (t, pln, row, col, ch) |



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/numpy_images.html>

Image data types and what they mean
===================================

 In `skimage`, images are simply [numpy](https://docs.scipy.org/doc/numpy/user/) arrays, which support a variety of data types [1](#id2), *i.e.* “dtypes”. To avoid distorting image intensities (see [Rescaling intensity values](#rescaling-intensity-values)), we assume that images use the following dtype ranges:

 

| Data type | Range |
| --- | --- |
| uint8 | 0 to 255 |
| uint16 | 0 to 65535 |
| uint32 | 0 to 232 - 1 |
| float | -1 to 1 or 0 to 1 |
| int8 | -128 to 127 |
| int16 | -32768 to 32767 |
| int32 | -231 to 231 - 1 |

 Note that float images should be restricted to the range -1 to 1 even though the data type itself can exceed this range; all integer dtypes, on the other hand, have pixel intensities that can span the entire data type range. With a few exceptions, *64-bit (u)int images are not supported*.

 Functions in `skimage` are designed so that they accept any of these dtypes, but, for efficiency, *may return an image of a different dtype* (see [Output types](#output-types)). If you need a particular dtype, `skimage` provides utility functions that convert dtypes and properly rescale image intensities (see [Input types](#input-types)). You should **never use** `astype` on an image, because it violates these assumptions about the dtype range:

 
```
>>> from skimage.util import img_as_float
>>> image = np.arange(0, 50, 10, dtype=np.uint8)
>>> print(image.astype(float)) # These float values are out of range.
[  0.  10.  20.  30.  40.]
>>> print(img_as_float(image))
[ 0.          0.03921569  0.07843137  0.11764706  0.15686275]

```
 Input types
-----------

 Although we aim to preserve the data range and type of input images, functions may support only a subset of these data-types. In such a case, the input will be converted to the required type (if possible), and a warning message printed to the log if a memory copy is needed. Type requirements should be noted in the docstrings.

 The following utility functions in the main package are available to developers and users:

 

| Function name | Description |
| --- | --- |
| img\_as\_float | Convert to 64-bit floating point. |
| img\_as\_ubyte | Convert to 8-bit uint. |
| img\_as\_uint | Convert to 16-bit uint. |
| img\_as\_int | Convert to 16-bit int. |

 These functions convert images to the desired dtype and *properly rescale their values*:

 
```
>>> from skimage.util import img_as_ubyte
>>> image = np.array([0, 0.5, 1], dtype=float)
>>> img_as_ubyte(image)
array([  0, 128, 255], dtype=uint8)

```
 Be careful! These conversions can result in a loss of precision, since 8 bits cannot hold the same amount of information as 64 bits:

 
```
>>> image = np.array([0, 0.5, 0.503, 1], dtype=float)
>>> image_as_ubyte(image)
array([  0, 128, 128, 255], dtype=uint8)

```
 Additionally, some functions take a `preserve_range` argument where a range conversion is convenient but not necessary. For example, interpolation in `transform.warp` requires an image of type float, which should have a range in [0, 1]. So, by default, input images will be rescaled to this range. However, in some cases, the image values represent physical measurements, such as temperature or rainfall values, that the user does not want rescaled. With `preserve_range=True`, the original range of the data will be preserved, even though the output is a float image. Users must then ensure this non-standard image is properly processed by downstream functions, which may expect an image in [0, 1].

 
```
>>> from skimage import data
>>> from skimage.transform import rescale
>>> image = data.coins()
>>> image.dtype, image.min(), image.max(), image.shape
(dtype('uint8'), 1, 252, (303, 384))
>>> rescaled = rescale(image, 0.5)
>>> (rescaled.dtype, np.round(rescaled.min(), 4),
...  np.round(rescaled.max(), 4), rescaled.shape)
(dtype('float64'), 0.0147, 0.9456, (152, 192))
>>> rescaled = rescale(image, 0.5, preserve_range=True)
>>> (rescaled.dtype, np.round(rescaled.min()),
...  np.round(rescaled.max()), rescaled.shape
(dtype('float64'), 4.0, 241.0, (152, 192))

```
 Output types
------------

 The output type of a function is determined by the function author and is documented for the benefit of the user. While this requires the user to explicitly convert the output to whichever format is needed, it ensures that no unnecessary data copies take place.

 A user that requires a specific type of output (e.g., for display purposes), may write:

 
```
>>> from skimage.util import img_as_uint
>>> out = img_as_uint(sobel(image))
>>> plt.imshow(out)

```
 Working with OpenCV
-------------------

 It is possible that you may need to use an image created using `skimage` with [OpenCV](https://opencv.org/) or vice versa. OpenCV image data can be accessed (without copying) in NumPy (and, thus, in scikit-image). OpenCV uses BGR (instead of scikit-image’s RGB) for color images, and its dtype is uint8 by default (See [Image data types and what they mean](#image-data-types-and-what-they-mean)). BGR stands for Blue Green Red.

 ### Converting BGR to RGB or vice versa

 The color images in `skimage` and OpenCV have 3 dimensions: width, height and color. RGB and BGR use the same color space, except the order of colors is reversed.

 Note that in `scikit-image` we usually refer to `rows` and `columns` instead of width and height (see [Coordinate conventions](numpy_images#numpy-images-coordinate-conventions)).

 The following instruction effectively reverses the order of the colors, leaving the rows and columns unaffected.

 
```
>>> image = image[:, :, ::-1]

```
 ### Using an image from OpenCV with `skimage`

 If cv\_image is an array of unsigned bytes, `skimage` will understand it by default. If you prefer working with floating point images, `img_as_float()` can be used to convert the image:

 
```
>>> from skimage.util import img_as_float
>>> image = img_as_float(any_opencv_image)

```
 ### Using an image from `skimage` with OpenCV

 The reverse can be achieved with `img_as_ubyte()`:

 
```
>>> from skimage.util import img_as_ubyte
>>> cv_image = img_as_ubyte(any_skimage_image)

```
 Image processing pipeline
-------------------------

 This dtype behavior allows you to string together any `skimage` function without worrying about the image dtype. On the other hand, if you want to use a custom function that requires a particular dtype, you should call one of the dtype conversion functions (here, `func1` and `func2` are `skimage` functions):

 
```
>>> from skimage.util import img_as_float
>>> image = img_as_float(func1(func2(image)))
>>> processed_image = custom_func(image)

```
 Better yet, you can convert the image internally and use a simplified processing pipeline:

 
```
>>> def custom_func(image):
...     image = img_as_float(image)
...     # do something
...
>>> processed_image = custom_func(func1(func2(image)))

```
 Rescaling intensity values
--------------------------

 When possible, functions should avoid blindly stretching image intensities (e.g. rescaling a float image so that the min and max intensities are 0 and 1), since this can heavily distort an image. For example, if you’re looking for bright markers in dark images, there may be an image where no markers are present; stretching its input intensity to span the full range would make background noise look like markers.

 Sometimes, however, you have images that should span the entire intensity range but do not. For example, some cameras store images with 10-, 12-, or 14-bit depth per pixel. If these images are stored in an array with dtype uint16, then the image won’t extend over the full intensity range, and thus, would appear dimmer than it should. To correct for this, you can use the `rescale_intensity` function to rescale the image so that it uses the full dtype range:

 
```
>>> from skimage import exposure
>>> image = exposure.rescale_intensity(img10bit, in_range=(0, 2**10 - 1))

```
 Here, the `in_range` argument is set to the maximum range for a 10-bit image. By default, `rescale_intensity` stretches the values of `in_range` to match the range of the dtype. `rescale_intensity` also accepts strings as inputs to `in_range` and `out_range`, so the example above could also be written as:

 
```
>>> image = exposure.rescale_intensity(img10bit, in_range='uint10')

```
 Note about negative values
--------------------------

 People very often represent images in signed dtypes, even though they only manipulate the positive values of the image (e.g., using only 0-127 in an int8 image). For this reason, conversion functions *only spread the positive values* of a signed dtype over the entire range of an unsigned dtype. In other words, negative values are clipped to 0 when converting from signed to unsigned dtypes. (Negative values are preserved when converting between signed dtypes.) To prevent this clipping behavior, you should rescale your image beforehand:

 
```
>>> image = exposure.rescale_intensity(img_int32, out_range=(0, 2**31 - 1))
>>> img_uint8 = img_as_ubyte(image)

```
 This behavior is symmetric: The values in an unsigned dtype are spread over just the positive range of a signed dtype.

 References
----------

  
`1`  
<https://docs.scipy.org/doc/numpy/user/basics.types.html>

  

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/data_types.html>

I/O Plugin Infrastructure
=========================

 A plugin consists of two files, the source and the descriptor `.ini`. Let’s say we’d like to provide a plugin for `imshow` using `matplotlib`. We’ll call our plugin `mpl`:

 
```
skimage/io/_plugins/mpl.py
skimage/io/_plugins/mpl.ini

```
 The name of the `.py` and `.ini` files must correspond. Inside the `.ini` file, we give the plugin meta-data:

 
```
[mpl] <-- name of the plugin, may be anything
description = Matplotlib image I/O plugin
provides = imshow <-- a comma-separated list, one or more of
                      imshow, imsave, imread, _app_show

```
 The “provides”-line lists all the functions provided by the plugin. Since our plugin provides `imshow`, we have to define it inside `mpl.py`:

 
```
# This is mpl.py

import matplotlib.pyplot as plt

def imshow(img):
    plt.imshow(img)

```
 Note that, by default, `imshow` is non-blocking, so a special function `_app_show` must be provided to block the GUI. We can modify our plugin to provide it as follows:

 
```
[mpl]
provides = imshow, _app_show

```
 
```
# This is mpl.py

import matplotlib.pyplot as plt

def imshow(img):
    plt.imshow(img)

def _app_show():
    plt.show()

```
 Any plugin in the `_plugins` directory is automatically examined by `skimage.io` upon import. You may list all the plugins on your system:

 
```
>>> import skimage.io as io
>>> io.find_available_plugins()
{'gtk': ['imshow'],
 'matplotlib': ['imshow', 'imread', 'imread_collection'],
 'pil': ['imread', 'imsave', 'imread_collection'],
 'qt': ['imshow', 'imsave', 'imread', 'imread_collection'],
 'test': ['imsave', 'imshow', 'imread', 'imread_collection'],}

```
 or only those already loaded:

 
```
>>> io.find_available_plugins(loaded=True)
{'matplotlib': ['imshow', 'imread', 'imread_collection'],
 'pil': ['imread', 'imsave', 'imread_collection']}

```
 A plugin is loaded using the `use_plugin` command:

 
```
>>> import skimage.io as io
>>> io.use_plugin('pil') # Use all capabilities provided by PIL

```
 or

 
```
>>> io.use_plugin('pil', 'imread') # Use only the imread capability of PIL

```
 Note that, if more than one plugin provides certain functionality, the last plugin loaded is used.

 To query a plugin’s capabilities, use `plugin_info`:

 
```
>>> io.plugin_info('pil')
>>>
{'description': 'Image reading via the Python Imaging Library',
 'provides': 'imread, imsave'}

```


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/plugins.html>

Handling Video Files
====================

 Sometimes it is necessary to read a sequence of images from a standard video file, such as .avi and .mov files.

 In a scientific context, it is usually better to avoid these formats in favor of a simple directory of images or a multi-dimensional TIF. Video formats are more difficult to read piecemeal, typically do not support random frame access or research-minded meta data, and use lossy compression if not carefully configured. But video files are in widespread use, and they are easy to share, so it is convenient to be equipped to read and write them when necessary.

 Tools for reading video files vary in their ease of installation and use, their disk and memory usage, and their cross-platform compatibility. This is a practical guide.

 A Workaround: Convert the Video to an Image Sequence
----------------------------------------------------

 For a one-off solution, the simplest, surest route is to convert the video to a collection of sequentially-numbered image files, often called an image sequence. Then the images files can be read into an `ImageCollection` by [`skimage.io.imread_collection`](../api/skimage.io#skimage.io.imread_collection "skimage.io.imread_collection"). Converting the video to frames can be done easily in [ImageJ](https://imagej.nih.gov/ij/), a cross-platform, GUI-based program from the bio-imaging community, or [FFmpeg](https://www.ffmpeg.org/), a powerful command-line utility for manipulating video files.

 In FFmpeg, the following command generates an image file from each frame in a video. The files are numbered with five digits, padded on the left with zeros.

 
```
ffmpeg -i "video.mov" -f image2 "video-frame%05d.png"

```
 More information is available in an [FFmpeg tutorial on image sequences](https://en.wikibooks.org/wiki/FFMPEG_An_Intermediate_Guide/image_sequence#Making_an_Image_Sequence_from_a_video).

 Generating an image sequence has disadvantages: they can be large and unwieldy, and generating them can take some time. It is generally preferable to work directly with the original video file. For a more direct solution, we need to execute FFmpeg or LibAV from Python to read frames from the video. FFmpeg and LibAV are two large open-source projects that decode video from the sprawling variety of formats used in the wild. There are several ways to use them from Python. Each, unfortunately, has some disadvantages.

 PyAV
----

 [PyAV](http://docs.mikeboers.com/pyav/develop/) uses FFmpeg’s (or LibAV’s) libraries to read image data directly from the video file. It invokes them using Cython bindings, so it is very fast.

 
```
import av
v = av.open('path/to/video.mov')

```
 PyAV’s API reflects the way frames are stored in a video file.

 
```
for packet in container.demux():
    for frame in packet.decode():
        if frame.type == 'video':
            img = frame.to_image()  # PIL/Pillow image
            arr = np.asarray(img)  # numpy array
            # Do something!

```
 Adding Random Access to PyAV
----------------------------

 The `Video` class in [PIMS](https://github.com/soft-matter/pims) invokes PyAV and adds additional functionality to solve a common problem in scientific applications, accessing a video by frame number. Video file formats are designed to be searched in an approximate way, by time, and they do not support an efficient means of seeking a specific frame number. PIMS adds this missing functionality by decoding (but not reading) the entire video at and producing an internal table of contents that supports indexing by frame.

 
```
import pims
v = pims.Video('path/to/video.mov')
v[-1]  # a 2D numpy array representing the last frame

```
 MoviePy
-------

 [Moviepy](https://zulko.github.io/moviepy) invokes FFmpeg through a subprocess, pipes the decoded video from FFmpeg into RAM, and reads it out. This approach is straightforward, but it can be brittle, and it’s not workable for large videos that exceed available RAM. It works on all platforms if FFmpeg is installed.

 Since it does not link to FFmpeg’s underlying libraries, it is easier to install but about [half as fast](https://gist.github.com/mikeboers/6843684).

 
```
from moviepy.editor import VideoFileClip
myclip = VideoFileClip("some_video.avi")

```
 Imageio
-------

 [Imageio](http://imageio.github.io/) takes the same approach as MoviePy. It supports a wide range of other image file formats as well.

 
```
import imageio
filename = '/tmp/file.mp4'
vid = imageio.get_reader(filename,  'ffmpeg')

for num, image in vid.iter_data():
    print(image.mean())

metadata = vid.get_meta_data()

```
 OpenCV
------

 Finally, another solution is the [VideoReader](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-open) class in OpenCV, which has bindings to FFmpeg. If you need OpenCV for other reasons, then this may be the best approach.



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/video.html>

Data visualization
==================

 Data visualization takes an important place in image processing. Data can be a simple unique 2D image or a more complex with multidimensional aspects: 3D in space, timeslapse, multiple channels.

 Therefore, the visualization strategy will depend on the data complexity and a range of tools external to scikit-image can be used for this purpose. Historically, scikit-image provided viewer tools but powerful packages are now available and must be preferred.

 Matplotlib
----------

 [Matplotlib](https://matplotlib.org/) is a library able to generate static plots, which includes image visualization.

 Plotly
------

 [Plotly](https://dash.plotly.com/) is a plotting library relying on web technologies with interaction capabilities.

 Mayavi
------

 [Mayavi](https://docs.enthought.com/mayavi/mayavi/) can be used to visualize 3D images.

 Napari
------

 [Napari](https://napari.org/) is a multi-dimensional image viewer. It’s designed for browsing, annotating, and analyzing large multi-dimensional images.



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/visualization.html>

Image adjustment: transforming image content
============================================

 Color manipulation
------------------

 Most functions for manipulating color channels are found in the submodule [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color").

 ### Conversion between color models

 Color images can be represented using different [color spaces](https://en.wikipedia.org/wiki/Color_space). One of the most common color spaces is the [RGB space](https://en.wikipedia.org/wiki/RGB_color_model), where an image has red, green and blue channels. However, other color models are widely used, such as the [HSV color model](https://en.wikipedia.org/wiki/HSL_and_HSV), where hue, saturation and value are independent channels, or the [CMYK model](https://en.wikipedia.org/wiki/CMYK_color_model) used for printing.

 [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color") provides utility functions to convert images to and from different color spaces. Integer-type arrays can be transformed to floating-point type by the conversion operation:

 
```
>>> # bright saturated red
>>> red_pixel_rgb = np.array([[[255, 0, 0]]], dtype=np.uint8)
>>> color.rgb2hsv(red_pixel_rgb)
array([[[ 0.,  1.,  1.]]])
>>> # darker saturated blue
>>> dark_blue_pixel_rgb = np.array([[[0, 0, 100]]], dtype=np.uint8)
>>> color.rgb2hsv(dark_blue_pixel_rgb)
array([[[ 0.66666667,  1.        ,  0.39215686]]])
>>> # less saturated pink
>>> pink_pixel_rgb = np.array([[[255, 100, 255]]], dtype=np.uint8)
>>> color.rgb2hsv(pink_pixel_rgb)
array([[[ 0.83333333,  0.60784314,  1.        ]]])

```
 ### Conversion from RGBA to RGB - Removing alpha channel through alpha blending

 Converting an RGBA image to an RGB image by alpha blending it with a background is realized with [`rgba2rgb()`](../api/skimage.color#skimage.color.rgba2rgb "skimage.color.rgba2rgb")

 
```
>>> from skimage.color import rgba2rgb
>>> from skimage import data
>>> img_rgba = data.logo()
>>> img_rgb = rgba2rgb(img_rgba)

```
 ### Conversion between color and gray values

 Converting an RGB image to a grayscale image is realized with [`rgb2gray()`](../api/skimage.color#skimage.color.rgb2gray "skimage.color.rgb2gray")

 
```
>>> from skimage.color import rgb2gray
>>> from skimage import data
>>> img = data.astronaut()
>>> img_gray = rgb2gray(img)

```
 [`rgb2gray()`](../api/skimage.color#skimage.color.rgb2gray "skimage.color.rgb2gray") uses a non-uniform weighting of color channels, because of the different sensitivity of the human eye to different colors. Therefore, such a weighting ensures [luminance preservation](https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale) from RGB to grayscale:

 
```
>>> red_pixel = np.array([[[255, 0, 0]]], dtype=np.uint8)
>>> color.rgb2gray(red_pixel)
array([[ 0.2125]])
>>> green_pixel = np.array([[[0, 255, 0]]], dtype=np.uint8)
>>> color.rgb2gray(green_pixel)
array([[ 0.7154]])

```
 Converting a grayscale image to RGB with [`gray2rgb()`](../api/skimage.color#skimage.color.gray2rgb "skimage.color.gray2rgb") simply duplicates the gray values over the three color channels.

 ### Image inversion

 An inverted image is also called complementary image. For binary images, True values become False and conversely. For grayscale images, pixel values are replaced by the difference of the maximum value of the data type and the actual value. For RGB images, the same operation is done for each channel. This operation can be achieved with [`skimage.util.invert()`](../api/skimage.util#skimage.util.invert "skimage.util.invert"):

 
```
>>> from skimage import util
>>> img = data.camera()
>>> inverted_img = util.invert(img)

```
 ### Painting images with labels

 [`label2rgb()`](../api/skimage.color#skimage.color.label2rgb "skimage.color.label2rgb") can be used to superimpose colors on a grayscale image using an array of labels to encode the regions to be represented with the same color.

 [![../_images/sphx_glr_plot_join_segmentations_0011.png]  Examples:

 * [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py)
* [Find the intersection of two segmentations](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_join_segmentations.html#sphx-glr-auto-examples-segmentation-plot-join-segmentations-py)
* [RAG Thresholding](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rag_mean_color.html#sphx-glr-auto-examples-segmentation-plot-rag-mean-color-py)

  Contrast and exposure
---------------------

 Image pixels can take values determined by the `dtype` of the image (see [Image data types and what they mean](data_types#data-types)), such as 0 to 255 for `uint8` images or `[0,
1]` for floating-point images. However, most images either have a narrower range of values (because of poor contrast), or have most pixel values concentrated in a subrange of the accessible values. [`skimage.exposure`](../api/skimage.exposure#module-skimage.exposure "skimage.exposure") provides functions that spread the intensity values over a larger range.

 A first class of methods compute a nonlinear function of the intensity, that is independent of the pixel values of a specific image. Such methods are often used for correcting a known non-linearity of sensors, or receptors such as the human eye. A well-known example is [Gamma correction](https://en.wikipedia.org/wiki/Gamma_correction), implemented in [`adjust_gamma()`](../api/skimage.exposure#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma").

 Other methods re-distribute pixel values according to the *histogram* of the image. The histogram of pixel values is computed with [`skimage.exposure.histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram"):

 
```
>>> image = np.array([[1, 3], [1, 1]])
>>> exposure.histogram(image)
(array([3, 0, 1]), array([1, 2, 3]))

```
 [`histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram") returns the number of pixels for each value bin, and the centers of the bins. The behavior of [`histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram") is therefore slightly different from the one of [`numpy.histogram()`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.19)"), which returns the boundaries of the bins.

 The simplest contrast enhancement [`rescale_intensity()`](../api/skimage.exposure#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity") consists in stretching pixel values to the whole allowed range, using a linear transformation:

 
```
>>> from skimage import exposure
>>> text = data.text()
>>> text.min(), text.max()
(10, 197)
>>> better_contrast = exposure.rescale_intensity(text)
>>> better_contrast.min(), better_contrast.max()
(0, 255)

```
 Even if an image uses the whole value range, sometimes there is very little weight at the ends of the value range. In such a case, clipping pixel values using percentiles of the image improves the contrast (at the expense of some loss of information, because some pixels are saturated by this operation):

 
```
>>> moon = data.moon()
>>> v_min, v_max = np.percentile(moon, (0.2, 99.8))
>>> v_min, v_max
(10.0, 186.0)
>>> better_contrast = exposure.rescale_intensity(
...                                     moon, in_range=(v_min, v_max))

```
 The function [`equalize_hist()`](../api/skimage.exposure#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist") maps the cumulative distribution function (cdf) of pixel values onto a linear cdf, ensuring that all parts of the value range are equally represented in the image. As a result, details are enhanced in large regions with poor contrast. As a further refinement, histogram equalization can be performed in subregions of the image with [`equalize_adapthist()`](../api/skimage.exposure#skimage.exposure.equalize_adapthist "skimage.exposure.equalize_adapthist"), in order to correct for exposure gradients across the image. See the example [Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_equalize.html#sphx-glr-auto-examples-color-exposure-plot-equalize-py).

 [![../_images/sphx_glr_plot_equalize_0011.png]  Examples:

 * [Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_equalize.html#sphx-glr-auto-examples-color-exposure-plot-equalize-py)

 

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/transforming_image_data.html>

Geometrical transformations of images
=====================================

 Cropping, resizing and rescaling images
---------------------------------------

 Images being NumPy arrays (as described in the [A crash course on NumPy for images](numpy_images#numpy) section), cropping an image can be done with simple slicing operations. Below we crop a 100x100 square corresponding to the top-left corner of the astronaut image. Note that this operation is done for all color channels (the color dimension is the last, third dimension):

 
```
>>> from skimage import data
>>> img = data.astronaut()
>>> top_left = img[:100, :100]

```
 In order to change the shape of the image, [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color") provides several functions described in [Rescale, resize, and downscale](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_rescale.html#sphx-glr-auto-examples-transform-plot-rescale-py) .

 
```

from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean

image = color.rgb2gray(data.astronaut())

image_rescaled = rescale(image, 0.25, anti_aliasing=False)
image_resized = resize(image, (image.shape[0] // 4, image.shape[1] // 4),
                       anti_aliasing=True)
image_downscaled = downscale_local_mean(image, (4, 3))


```
 [![../_images/sphx_glr_plot_rescale_0011.png]
------------------------------------

 [Homographies](https://en.wikipedia.org/wiki/Homography) are transformations of a Euclidean space that preserve the alignment of points. Specific cases of homographies correspond to the conservation of more properties, such as parallelism (affine transformation), shape (similar transformation) or distances (Euclidean transformation). The different types of homographies available in scikit-image are presented in [Types of homographies](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_transform_types.html#sphx-glr-auto-examples-transform-plot-transform-types-py).

 Projective transformations can either be created using the explicit parameters (e.g. scale, shear, rotation and translation):

 
```
from skimage import data
from skimage import transform
from skimage import img_as_float

tform = transform.EuclideanTransform(
   rotation=np.pi / 12.,
   translation = (100, -20)
   )

```
 or the full transformation matrix:

 
```
from skimage import data
from skimage import transform
from skimage import img_as_float

matrix = np.array([[np.cos(np.pi/12), -np.sin(np.pi/12), 100],
                   [np.sin(np.pi/12), np.cos(np.pi/12), -20],
                   [0, 0, 1]])
tform = transform.EuclideanTransform(matrix)

```
 The transformation matrix of a transform is available as its `tform.params` attribute. Transformations can be composed by multiplying matrices with the `@` matrix multiplication operator.

 Transformation matrices use [Homogeneous coordinates](https://en.wikipedia.org/wiki/Homogeneous_coordinates), which are the extension of Cartesian coordinates used in Euclidean geometry to the more general projective geometry. In particular, points at infinity can be represented with finite coordinates.

 Transformations can be applied to images using [`skimage.transform.warp()`](../api/skimage.transform#skimage.transform.warp "skimage.transform.warp"):

 
```
img = img_as_float(data.chelsea())
tf_img = transform.warp(img, tform.inverse)

```
 [![../_images/sphx_glr_plot_transform_types_0011.png] tutorial:

 
```
text = data.text()

src = np.array([[0, 0], [0, 50], [300, 50], [300, 0]])
dst = np.array([[155, 15], [65, 40], [260, 130], [360, 95]])

tform3 = transform.ProjectiveTransform()
tform3.estimate(src, dst)
warped = transform.warp(text, tform3, output_shape=(50, 300))

```
 [![../_images/sphx_glr_plot_geometric_0021.png], such as

 * [Corner detection](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_corner.html#sphx-glr-auto-examples-features-detection-plot-corner-py),
* [ORB feature detector and binary descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_orb.html#sphx-glr-auto-examples-features-detection-plot-orb-py),
* [BRIEF binary descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_brief.html#sphx-glr-auto-examples-features-detection-plot-brief-py),
* etc.

 and matching points using [`skimage.feature.match_descriptors()`](../api/skimage.feature#skimage.feature.match_descriptors "skimage.feature.match_descriptors") before estimating transformation parameters. However, spurious matches are often made, and it is advisable to use the RANSAC algorithm (instead of simple least-squares optimization) to improve the robustness to outliers, as explained in [Robust matching using RANSAC](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_matching.html#sphx-glr-auto-examples-transform-plot-matching-py).

 [![../_images/sphx_glr_plot_matching_0011.png] Examples showing applications of transformation estimation are

 * stereo matching [Fundamental matrix estimation](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_fundamental_matrix.html#sphx-glr-auto-examples-transform-plot-fundamental-matrix-py) and
* image rectification [Using geometric transformations](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_geometric.html#sphx-glr-auto-examples-transform-plot-geometric-py)

 The `estimate` method is point-based, that is, it uses only a set of points from the source and destination images. For estimating translations (shifts), it is also possible to use a *full-field* method using all pixels, based on Fourier-space cross-correlation. This method is implemented by `skimage.registration.register_translation()` and explained in the [Image Registration](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_register_translation.html#sphx-glr-auto-examples-registration-plot-register-translation-py) tutorial.

 [![../_images/sphx_glr_plot_register_translation_0011.png] tutorial explains a variant of this full-field method for estimating a rotation, by using first a log-polar transformation.



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/geometrical_transform.html>

Tutorials
=========

 * [Image Segmentation](tutorial_segmentation)
* [How to parallelize loops](tutorial_parallelization)



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/tutorials.html>

Image Segmentation
==================

 Image segmentation is the task of labeling the pixels of objects of interest in an image.

 In this tutorial, we will see how to segment objects from a background. We use the `coins` image from `skimage.data`. This image shows several coins outlined against a darker background. The segmentation of the coins cannot be done directly from the histogram of grey values, because the background shares enough grey levels with the coins that a thresholding segmentation is not sufficient.

 [![../_images/sphx_glr_plot_coins_segmentation_0011.png] 
```
>>> from skimage import data
>>> from skimage.exposure import histogram
>>> coins = data.coins()
>>> hist, hist_centers = histogram(coins)

```
 Simply thresholding the image leads either to missing significant parts of the coins, or to merging parts of the background with the coins. This is due to the inhomogeneous lighting of the image.

 [![../_images/sphx_glr_plot_coins_segmentation_0021.png] A first idea is to take advantage of the local contrast, that is, to use the gradients rather than the grey values.

 Edge-based segmentation
-----------------------

 Let us first try to detect edges that enclose the coins. For edge detection, we use the [Canny detector](https://en.wikipedia.org/wiki/Canny_edge_detector) of `skimage.feature.canny`

 
```
>>> from skimage.feature import canny
>>> edges = canny(coins/255.)

```
 As the background is very smooth, almost all edges are found at the boundary of the coins, or inside the coins.

 
```
>>> from scipy import ndimage as ndi
>>> fill_coins = ndi.binary_fill_holes(edges)

```
 [![../_images/sphx_glr_plot_coins_segmentation_0031.png] Now that we have contours that delineate the outer boundary of the coins, we fill the inner part of the coins using the `ndi.binary_fill_holes` function, which uses mathematical morphology to fill the holes.

 [![../_images/sphx_glr_plot_coins_segmentation_0041.png] Most coins are well segmented out of the background. Small objects from the background can be easily removed using the `ndi.label` function to remove objects smaller than a small threshold.

 
```
>>> label_objects, nb_labels = ndi.label(fill_coins)
>>> sizes = np.bincount(label_objects.ravel())
>>> mask_sizes = sizes > 20
>>> mask_sizes[0] = 0
>>> coins_cleaned = mask_sizes[label_objects]

```
 However, the segmentation is not very satisfying, since one of the coins has not been segmented correctly at all. The reason is that the contour that we got from the Canny detector was not completely closed, therefore the filling function did not fill the inner part of the coin.

 [![../_images/sphx_glr_plot_coins_segmentation_0051.png] Therefore, this segmentation method is not very robust: if we miss a single pixel of the contour of the object, we will not be able to fill it. Of course, we could try to dilate the contours in order to close them. However, it is preferable to try a more robust method.

 Region-based segmentation
-------------------------

 Let us first determine markers of the coins and the background. These markers are pixels that we can label unambiguously as either object or background. Here, the markers are found at the two extreme parts of the histogram of grey values:

 
```
>>> markers = np.zeros_like(coins)
>>> markers[coins < 30] = 1
>>> markers[coins > 150] = 2

```
 We will use these markers in a watershed segmentation. The name watershed comes from an analogy with hydrology. The [watershed transform](https://en.wikipedia.org/wiki/Watershed_%28image_processing%29) floods an image of elevation starting from markers, in order to determine the catchment basins of these markers. Watershed lines separate these catchment basins, and correspond to the desired segmentation.

 The choice of the elevation map is critical for good segmentation. Here, the amplitude of the gradient provides a good elevation map. We use the Sobel operator for computing the amplitude of the gradient:

 
```
>>> from skimage.filters import sobel
>>> elevation_map = sobel(coins)

```
 From the 3-D surface plot shown below, we see that high barriers effectively separate the coins from the background.

 ![../_images/elevation_map.jpg] and here is the corresponding 2-D plot:

 [![../_images/sphx_glr_plot_coins_segmentation_0061.png] The next step is to find markers of the background and the coins based on the extreme parts of the histogram of grey values:

 
```
>>> markers = np.zeros_like(coins)
>>> markers[coins < 30] = 1
>>> markers[coins > 150] = 2

```
 [![../_images/sphx_glr_plot_coins_segmentation_0071.png] Let us now compute the watershed transform:

 
```
>>> from skimage.segmentation import watershed
>>> segmentation = watershed(elevation_map, markers)

```
 [![../_images/sphx_glr_plot_coins_segmentation_0081.png] With this method, the result is satisfying for all coins. Even if the markers for the background were not well distributed, the barriers in the elevation map were high enough for these markers to flood the entire background.

 We remove a few small holes with mathematical morphology:

 
```
>>> segmentation = ndi.binary_fill_holes(segmentation - 1)

```
 We can now label all the coins one by one using `ndi.label`:

 
```
>>> labeled_coins, _ = ndi.label(segmentation)

```
 [![../_images/sphx_glr_plot_coins_segmentation_0091.png]

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/tutorial_segmentation.html>

How to parallelize loops
========================

 In image processing, we frequently apply the same algorithm on a large batch of images. In this paragraph, we propose to use [joblib](https://joblib.readthedocs.io) to parallelize loops. Here is an example of such repetitive tasks:

 
```
from skimage import data, color, util
from skimage.restoration import denoise_tv_chambolle
from skimage.feature import hog

def task(image):
    """
    Apply some functions and return an image.
    """
    image = denoise_tv_chambolle(image[0][0], weight=0.1, multichannel=True)
    fd, hog_image = hog(color.rgb2gray(image), orientations=8,
                        pixels_per_cell=(16, 16), cells_per_block=(1, 1),
                        visualize=True)
    return hog_image


# Prepare images
hubble = data.hubble_deep_field()
width = 10
pics = util.view_as_windows(hubble, (width, hubble.shape[1], hubble.shape[2]), step=width)

```
 To call the function `task` on each element of the list `pics`, it is usual to write a for loop. To measure the execution time of this loop, you can use ipython and measure the execution time with `%timeit`.

 
```
def classic_loop():
    for image in pics:
        task(image)


%timeit classic_loop()

```
 Another equivalent way to code this loop is to use a comprehension list which has the same efficiency.

 
```
def comprehension_loop():
    [task(image) for image in pics]

%timeit comprehension_loop()

```
 `joblib` is a library providing an easy way to parallelize for loops once we have a comprehension list. The number of jobs can be specified.

 
```
from joblib import Parallel, delayed
def joblib_loop():
    Parallel(n_jobs=4)(delayed(task)(i) for i in pics)

%timeit joblib_loop()

```


 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/tutorial_parallelization.html>

Getting help on using skimage
=============================

 Besides the user guide, there exist other opportunities to get help on using `skimage`.

 Examples gallery
----------------

 The [General examples](https://scikit-image.org/docs/0.18.x/auto_examples/index.html#examples-gallery) gallery provides graphical examples of typical image processing tasks. By a quick glance at the different thumbnails, the user may find an example close to a typical use case of interest. Each graphical example page displays an introductory paragraph, a figure, and the source code that generated the figure. Downloading the Python source code enables one to modify quickly the example into a case closer to one’s image processing applications.

 Users are warmly encouraged to report on their use of `skimage` on the [Mailing-list](#mailing-list), in order to propose more examples in the future. Contributing examples to the gallery can be done on github (see [How to contribute to scikit-image](https://scikit-image.org/docs/0.18.x/contribute.html)).

 Search field
------------

 The `quick search` field located in the navigation bar of the html documentation can be used to search for specific keywords (segmentation, rescaling, denoising, etc.).

 API Discovery
-------------

 NumPy provides a `lookfor` function to search API functions. By default `lookfor` will search the NumPy API. NumPy lookfor example: ``np.lookfor('eigenvector') ``

 But it can be used to search in modules, by passing in the module name as a string:

 `` np.lookfor('boundaries', 'skimage') ``

 or the module itself. ``
> import skimage
> np.lookfor('boundaries', skimage)
``

 Docstrings
----------

 Docstrings of `skimage` functions are formatted using [Numpy’s documentation standard](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt), starting with a `Parameters` section for the arguments and a `Returns` section for the objects returned by the function. Also, most functions include one or more examples.

 Mailing-list
------------

 The scikit-image mailing-list is [scikit-image@python.org](mailto:scikit-image%40python.org) (users should [join](https://mail.python.org/mailman3/lists/scikit-image.python.org/) before posting). This mailing-list is shared by users and developers, and it is the right place to ask any question about `skimage`, or in general, image processing using Python. Posting snippets of code with minimal examples ensures to get more relevant and focused answers.

 We would love to hear from how you use `skimage` for your work on the mailing-list!



 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/getting_help.html>

Image Viewer
============

  Warning

 The scikit-image viewer is deprecated since 0.18 and will be removed in 0.20. Please, refer to the [visualization](https://scikit-image.org/docs/stable/user_guide/visualization.html) software page for alternatives.

  Quick Start
-----------

 `skimage.viewer` provides a [matplotlib](https://matplotlib.org/)-based canvas for displaying images and a Qt-based GUI-toolkit, with the goal of making it easy to create interactive image editors. You can simply use it to display an image:

 
```
from skimage import data
from skimage.viewer import ImageViewer

image = data.coins()
viewer = ImageViewer(image)
viewer.show()

```
 Of course, you could just as easily use `imshow` from [matplotlib](https://matplotlib.org/) (or alternatively, `skimage.io.imshow` which adds support for multiple io-plugins) to display images. The advantage of `ImageViewer` is that you can easily add plugins for manipulating images. Currently, only a few plugins are implemented, but it is easy to write your own. Before going into the details, let’s see an example of how a pre-defined plugin is added to the viewer:

 
```
from skimage.viewer.plugins.lineprofile import LineProfile

viewer = ImageViewer(image)
viewer += LineProfile(viewer)
overlay, data = viewer.show()[0]

```
 The viewer’s `show()` method returns a list of tuples, one for each attached plugin. Each tuple contains two elements: an overlay of the same shape as the input image, and a data field (which may be `None`). A plugin class documents its return value in its `output` method.

 In this example, only one plugin is attached, so the list returned by `show` will have length 1. We extract the single tuple and bind its `overlay` and `data` elements to individual variables. Here, `overlay` contains an image of the line drawn on the viewer, and `data` contains the 1-dimensional intensity profile along that line.

 At the moment, there are not many plugins pre-defined, but there is a really simple interface for creating your own plugin. First, let us create a plugin to call the total-variation denoising function, `denoise_tv_bregman`:

 
```
from skimage.filters import denoise_tv_bregman
from skimage.viewer.plugins.base import Plugin

denoise_plugin = Plugin(image_filter=denoise_tv_bregman)

```
  Note

 The `Plugin` assumes the first argument given to the image filter is the image from the image viewer. In the future, this should be changed so you can pass the image to a different argument of the filter function.

  To actually interact with the filter, you have to add widgets that adjust the parameters of the function. Typically, that means adding a slider widget and connecting it to the filter parameter and the minimum and maximum values of the slider:

 
```
from skimage.viewer.widgets import Slider
from skimage.viewer.widgets.history import SaveButtons

denoise_plugin += Slider('weight', 0.01, 0.5, update_on='release')
denoise_plugin += SaveButtons()

```
 Here, we connect a slider widget to the filter’s ‘weight’ argument. We also added some buttons for saving the image to file or to the `scikit-image` image stack (see `skimage.io.push` and `skimage.io.pop`).

 All that’s left is to create an image viewer and add the plugin to that viewer.

 
```
viewer = ImageViewer(image)
viewer += denoise_plugin
denoised = viewer.show()[0][0]

```
 Here, we access only the overlay returned by the plugin, which contains the filtered image for the last used setting of `weight`.

 ![../_images/denoise_viewer_window.png]

 © 2019 the scikit-image team  
Licensed under the BSD 3-clause License.  

<https://scikit-image.org/docs/0.18.x/user_guide/viewer.html>

scikit\_image