cuCIM API Reference¶
CuImage Submodules¶
CuImage¶

cucim.CuImage.
associated_images
¶ Returns a set of associated image names.
Digital Pathology image usually has a label/thumbnail or a macro image(lowpower snapshot of the entire glass slide). Names of those images (such as ‘macro’ and ‘label’) are in associated_images.

cucim.CuImage.
channel_names
¶ A channel name list.

cucim.CuImage.
coord_sys
¶ Coordinate frame in which the direction cosines are measured.
Available Coordinate frame names are not finalized yet.

cucim.CuImage.
device
¶ A device type.
By default t is cpu (It will be changed since v0.19.0).

cucim.CuImage.
dims
¶ A string containing a list of dimensions being requested.
 The default is to return the six standard dims (‘STCZYX’) unless it is a DP multiresolution image.
[sites, time, channel(or wavelength), z, y, x]. S  Sites or multiposition locations.
NOTE: in OMETIFF’s metadata, dimension order would be specified as ‘XYZCTS’ (first one is fastiterating dimension).

cucim.CuImage.
direction
¶ Direction cosines (size is always 3x3).

cucim.CuImage.
dtype
¶ The data type of the image.

cucim.CuImage.
is_loaded
¶ True if image data is loaded & available.

cucim.CuImage.
metadata
¶ A metadata object as dict.
It would be a dictionary(keyvalue pair) in general but can be a complex object (e.g., OMETIFF metadata).

cucim.CuImage.
ndim
¶ The number of dimensions.

cucim.CuImage.
origin
¶ Physical location of (0, 0, 0) (size is always 3).

cucim.CuImage.
path
¶ Underlying file path for this object.

cucim.CuImage.
raw_metadata
¶ A raw metadata string.

cucim.CuImage.
resolutions
¶ Returns a dict that includes resolution information.
level_count: The number of levels
level_dimensions: A tuple of dimension tuples (width, height)
level_downsamples: A tuple of downsample factors

cucim.CuImage.
shape
¶ A tuple of dimension sizes (in the order of dims)
skimage Submodules¶
color¶

cucim.skimage.color.
combine_stains
(stains, conv_matrix)¶ 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].
 Returns
 out(…, 3) ndarray
The image in RGB format. Same dimensions as input.
 Raises
 ValueError
If stains is not at least 2D with shape (…, 3).
Notes
Stain combination matrices available in the
color
module and their respective colorspace:rgb_from_hed
: Hematoxylin + Eosin + DABrgb_from_hdx
: Hematoxylin + DABrgb_from_fgx
: Feulgen + Light Greenrgb_from_bex
: Giemsa stain : Methyl Blue + Eosinrgb_from_rbd
: FastRed + FastBlue + DABrgb_from_gdx
: Methyl Green + DABrgb_from_hax
: Hematoxylin + AECrgb_from_bro
: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix OrangeGrgb_from_bpx
: Methyl Blue + Ponceau Fuchsinrgb_from_ahx
: Alcian Blue + Hematoxylinrgb_from_hpx
: Hematoxylin + PAS
References
 1
 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
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import (separate_stains, combine_stains, ... hdx_from_rgb, rgb_from_hdx) >>> ihc = cp.array(data.immunohistochemistry()) >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb) >>> ihc_rgb = combine_stains(ihc_hdx, rgb_from_hdx)

cucim.skimage.color.
convert_colorspace
(arr, fromspace, tospace)¶ 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
>>> import cupy as cp >>> from cucim.skimage import data >>> img = cp.array(data.astronaut()) >>> img_hsv = convert_colorspace(img, 'RGB', 'HSV')

cucim.skimage.color.
deltaE_cie76
(lab1, lab2)¶ 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
 2
A. R. Robertson, “The CIE 1976 colordifference formulae,” Color Res. Appl. 2, 711 (1977).

cucim.skimage.color.
deltaE_ciede2000
(lab1, lab2, kL=1, kC=1, kH=1)¶ Color difference as given by the CIEDE 2000 standard.
CIEDE 2000 is a major revision of CIDE94. The perceptual calibration is largely based on experience with automotive paint on smooth surfaces.
 Parameters
 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
 2
http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf DOI:10.1364/AO.33.008069
 3
M. Melgosa, J. Quesada, and E. Hita, “Uniformity of some recent color metrics tested with an accurate colordifference tolerance dataset,” Appl. Opt. 33, 80698077 (1994).

cucim.skimage.color.
deltaE_ciede94
(lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015)¶ Color difference according to CIEDE 94 standard
Accommodates perceptual nonuniformities 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

cucim.skimage.color.
deltaE_cmc
(lab1, lab2, kL=1, kC=1)¶ Color difference from the CMC l:c standard.
This color difference was developed by the Colour Measurement Committee (CMC) of the Society of Dyers and Colourists (United Kingdom). It is intended for use in the textile industry.
The scale factors kL, kC set the weight given to differences in lightness and chroma relative to differences in hue. The usual values are
kL=2
,kC=1
for “acceptability” andkL=1
,kC=1
for “imperceptibility”. Colors withdE > 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
 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 colourdifference formula,” J. Soc. Dyers Colour. 100, 128132 (1984).

cucim.skimage.color.
gray2rgb
(image, alpha=None)¶ Create an RGB representation of a graylevel 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 1dimensional image of shape
(M, )
, the output will be shape(M, 3)
.

cucim.skimage.color.
gray2rgba
(image, alpha=None)¶ Create a RGBA representation of a graylevel 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 theimage
dtype.
 Returns
 rgbandarray
RGBA image. A new dimension of length 4 is added to input image shape.

cucim.skimage.color.
grey2rgb
(image, alpha=None)¶ Create an RGB representation of a graylevel 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 1dimensional image of shape
(M, )
, the output will be shape(M, 3)
.

cucim.skimage.color.
hed2rgb
(hed)¶ HaematoxylinEosinDAB (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 2D 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. 2919, Aug. 2001.
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import rgb2hed, hed2rgb >>> ihc = cp.array(data.immunohistochemistry()) >>> ihc_hed = rgb2hed(ihc) >>> ihc_rgb = hed2rgb(ihc_hed)

cucim.skimage.color.
hsv2rgb
(hsv)¶ 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 2D with shape (…, 3).
Notes
Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [1].
References
Examples
>>> import cupy as cp >>> from skimage import data >>> img = cp.array(data.astronaut()) >>> img_hsv = rgb2hsv(img) >>> img_rgb = hsv2rgb(img_hsv)

cucim.skimage.color.
lab2lch
(lab)¶ CIELAB to CIELCH color space conversion.
LCH is the cylindrical representation of the LAB (Cartesian) colorspace
 Parameters
 lab(…, 3) array_like
The ND image in CIELAB format. The last (
N+1
th) dimension must have at least 3 elements, corresponding to theL
,a
, andb
color channels. Subsequent elements are copied.
 Returns
 out(…, 3) ndarray
The image in LCH format, in a ND 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 cucim.skimage.color import rgb2lab, lab2lch >>> img = cp.array(data.astronaut()) >>> img_lab = rgb2lab(img) >>> img_lch = lab2lch(img_lab)

cucim.skimage.color.
lab2rgb
(lab, illuminant='D65', observer='2')¶ 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 2D 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

cucim.skimage.color.
lab2xyz
(lab, illuminant='D65', observer='2')¶ CIELAB 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 2D 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

cucim.skimage.color.
label2rgb
(label, image=None, colors=None, alpha=0.3, bg_label= 1, bg_color=(0, 0, 0), image_alpha=1, kind='overlay')¶ Return an RGB image where colorcoded 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 stainedclass 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.

cucim.skimage.color.
lch2lab
(lch)¶ CIELCH to CIELAB color space conversion.
LCH is the cylindrical representation of the LAB (Cartesian) colorspace
 Parameters
 lch(…, 3) array_like
The ND image in CIELCH format. The last (
N+1
th) dimension must have at least 3 elements, corresponding to theL
,a
, andb
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 cucim.skimage.color import rgb2lab, lch2lab >>> img = cp.array(data.astronaut()) >>> img_lab = rgb2lab(img) >>> img_lch = lab2lch(img_lab) >>> img_lab2 = lch2lab(img_lch)

cucim.skimage.color.
luv2rgb
(luv)¶ Luv to RGB color space conversion.
 Parameters
 luv(…, 3) array_like
The image in CIE Luv format. Final dimension denotes channels.
 Returns
 out(…, 3) ndarray
The image in RGB format. Same dimensions as input.
 Raises
 ValueError
If luv is not at least 2D with shape (…, 3).
Notes
This function uses luv2xyz and xyz2rgb.

cucim.skimage.color.
luv2xyz
(luv, illuminant='D65', observer='2')¶ CIELuv to XYZ color space conversion.
 Parameters
 luv(…, 3) array_like
The image in CIELuv 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 luv is not at least 2D with shape (…, 3).
 ValueError
If either the illuminant or the observer angle are not supported or unknown.
Notes
XYZ conversion weights use observer=2A. Reference whitepoint for D65 Illuminant, with XYZ tristimulus values of
(95.047, 100., 108.883)
. See function ‘get_xyz_coords’ for a list of supported illuminants.References

cucim.skimage.color.
rgb2gray
(rgb)¶ 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 2D 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
Examples
>>> import cupy as cp >>> from cucim.skimage.color import rgb2gray >>> from skimage import data >>> img = cp.array(data.astronaut()) >>> img_gray = rgb2gray(img)

cucim.skimage.color.
rgb2grey
(rgb)¶ 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 2D 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
Examples
>>> import cupy as cp >>> from cucim.skimage.color import rgb2gray >>> from skimage import data >>> img = cp.array(data.astronaut()) >>> img_gray = rgb2gray(img)

cucim.skimage.color.
rgb2hed
(rgb)¶ RGB to HaematoxylinEosinDAB (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 2D 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. 2919, Aug. 2001.
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import rgb2hed >>> ihc = cp.array(data.immunohistochemistry()) >>> ihc_hed = rgb2hed(ihc)

cucim.skimage.color.
rgb2hsv
(rgb)¶ 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 2D with shape (…, 3).
Notes
Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [1].
References
Examples
>>> import cupy as cp >>> from cucim.skimage import color >>> from skimage import data >>> img = cp.array(data.astronaut()) >>> img_hsv = color.rgb2hsv(img)

cucim.skimage.color.
rgb2lab
(rgb, illuminant='D65', observer='2')¶ Conversion from the sRGB color space (IEC 6196621: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 2D with shape (…, 3).
Notes
RGB is a devicedependent 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

cucim.skimage.color.
rgb2luv
(rgb)¶ RGB to CIELuv color space conversion.
 Parameters
 rgb(…, 3) array_like
The image in RGB format. Final dimension denotes channels.
 Returns
 out(…, 3) ndarray
The image in CIE Luv format. Same dimensions as input.
 Raises
 ValueError
If rgb is not at least 2D with shape (…, 3).
Notes
This function uses rgb2xyz and xyz2luv.
References

cucim.skimage.color.
rgb2rgbcie
(rgb)¶ 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 2D with shape (…, 3).
References
Examples
>>> from skimage import data >>> from cucim.skimage.color import rgb2rgbcie >>> img = cp.array(data.astronaut()) >>> img_rgbcie = rgb2rgbcie(img)

cucim.skimage.color.
rgb2xyz
(rgb)¶ 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 2D 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
Examples
>>> import cupy as cp >>> from skimage import data >>> img = cp.array(data.astronaut()) >>> img_xyz = rgb2xyz(img)

cucim.skimage.color.
rgb2ycbcr
(rgb)¶ 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 2D 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

cucim.skimage.color.
rgb2ydbdr
(rgb)¶ 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 2D with shape (…, 3).
Notes
This is the color space commonly used by video codecs. It is also the reversible color transform in JPEG2000.
References

cucim.skimage.color.
rgb2yiq
(rgb)¶ 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 2D with shape (…, 3).

cucim.skimage.color.
rgb2ypbpr
(rgb)¶ 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 2D with shape (…, 3).
References

cucim.skimage.color.
rgb2yuv
(rgb)¶ 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 2D 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

cucim.skimage.color.
rgba2rgb
(rgba, background=(1, 1, 1))¶ RGBA to RGB conversion using alpha blending [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 2D with shape (…, 4).
References
Examples
>>> import cupy as cp >>> from cucim.skimage import color >>> from skimage import data >>> img_rgba = cp.array(data.logo()) >>> img_rgb = color.rgba2rgb(img_rgba)

cucim.skimage.color.
rgbcie2rgb
(rgbcie)¶ 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 2D with shape (…, 3).
References
Examples
>>> from skimage import data >>> from cucim.skimage.color import rgb2rgbcie, rgbcie2rgb >>> img = cp.array(data.astronaut()) >>> img_rgbcie = rgb2rgbcie(img) >>> img_rgb = rgbcie2rgb(img_rgbcie)

cucim.skimage.color.
separate_stains
(rgb, conv_matrix)¶ 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].
 Returns
 out(…, 3) ndarray
The image in stain color space. Same dimensions as input.
 Raises
 ValueError
If rgb is not at least 2D with shape (…, 3).
Notes
Stain separation matrices available in the
color
module and their respective colorspace:hed_from_rgb
: Hematoxylin + Eosin + DABhdx_from_rgb
: Hematoxylin + DABfgx_from_rgb
: Feulgen + Light Greenbex_from_rgb
: Giemsa stain : Methyl Blue + Eosinrbd_from_rgb
: FastRed + FastBlue + DABgdx_from_rgb
: Methyl Green + DABhax_from_rgb
: Hematoxylin + AECbro_from_rgb
: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix OrangeGbpx_from_rgb
: Methyl Blue + Ponceau Fuchsinahx_from_rgb
: Alcian Blue + Hematoxylinhpx_from_rgb
: Hematoxylin + PAS
This implementation borrows some ideas from DIPlib [2], e.g. the compensation using a small value to avoid log artifacts when calculating the BeerLambert law.
References
 1
 2
 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
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import separate_stains, hdx_from_rgb >>> ihc = cp.array(data.immunohistochemistry()) >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb)

cucim.skimage.color.
xyz2lab
(xyz, illuminant='D65', observer='2')¶ XYZ to CIELAB 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 CIELAB format. Same dimensions as input.
 Raises
 ValueError
If xyz is not at least 2D 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
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import rgb2xyz, xyz2lab >>> img = cp.array(data.astronaut()) >>> img_xyz = rgb2xyz(img) >>> img_lab = xyz2lab(img_xyz)

cucim.skimage.color.
xyz2luv
(xyz, illuminant='D65', observer='2')¶ XYZ to CIELuv 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 CIELuv format. Same dimensions as input.
 Raises
 ValueError
If xyz is not at least 2D with shape (…, 3).
 ValueError
If either the illuminant or the observer angle are not supported or unknown.
Notes
By default XYZ conversion weights use observer=2A. Reference whitepoint for D65 Illuminant, with XYZ tristimulus values of
(95.047, 100., 108.883)
. See function ‘get_xyz_coords’ for a list of supported illuminants.References
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.color import rgb2xyz, xyz2luv >>> img = cp.array(data.astronaut()) >>> img_xyz = rgb2xyz(img) >>> img_luv = xyz2luv(img_xyz)

cucim.skimage.color.
xyz2rgb
(xyz)¶ 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 2D 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
Examples
>>> from skimage import data >>> from cucim.skimage.color import rgb2xyz, xyz2rgb >>> img = cp.array(data.astronaut()) >>> img_xyz = rgb2xyz(img) >>> img_rgb = xyz2rgb(img_xyz)

cucim.skimage.color.
ycbcr2rgb
(ycbcr)¶ 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 2D 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

cucim.skimage.color.
ydbdr2rgb
(ydbdr)¶ 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 2D with shape (…, 3).
Notes
This is the color space commonly used by video codecs, also called the reversible color transform in JPEG2000.
References

cucim.skimage.color.
yiq2rgb
(yiq)¶ 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 2D with shape (…, 3).

cucim.skimage.color.
ypbpr2rgb
(ypbpr)¶ 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 2D with shape (…, 3).
References

cucim.skimage.color.
yuv2rgb
(yuv)¶ 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 2D with shape (…, 3).
References
data¶

cucim.skimage.data.
binary_blobs
(length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, seed=None)¶ Generate synthetic binary image with several rounded bloblike 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
Notes
Warning: CuPy does not give identical randomly generated numbers as NumPy, so using a specific seed here will not give an identical pattern to the scikitimage implementation.
The behavior for a given random seed may also change across CuPy major versions. See: https://docs.cupy.dev/en/stable/reference/random.html
Examples
>>> from cucim.skimage import data >>> # tiny size (5, 5) >>> blobs = data.binary_blobs(length=5, blob_size_fraction=0.2, seed=1) >>> # larger size >>> 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)
exposure¶

cucim.skimage.exposure.
adjust_gamma
(image, gamma=1, gain=1)¶ Performs Gamma Correction on the input image.
Also known as Power Law Transform. This function transforms the input image pixelwise according to the equation
O = I**gamma
after scaling each pixel to the range 0 to 1. Parameters
 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
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
Examples
>>> from skimage import data >>> from cucim.skimage import exposure, img_as_float >>> image = img_as_float(cp.array(data.moon())) >>> gamma_corrected = exposure.adjust_gamma(image, 2) >>> # Output is darker for gamma > 1 >>> image.mean() > gamma_corrected.mean() True

cucim.skimage.exposure.
adjust_log
(image, gain=1, inv=False)¶ Performs Logarithmic correction on the input image.
This function transforms the input image pixelwise according to the equation
O = gain*log(1 + I)
after scaling each pixel to the range 0 to 1.For inverse logarithmic correction, the equation is
O = gain*(2**I  1)
. Parameters
 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
References

cucim.skimage.exposure.
adjust_sigmoid
(image, cutoff=0.5, gain=10, inv=False)¶ Performs Sigmoid Correction on the input image.
Also known as Contrast Adjustment. This function transforms the input image pixelwise according to the equation
O = 1/(1 + exp*(gain*(cutoff  I)))
after scaling each pixel to the range 0 to 1. Parameters
 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
References
 1
Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”, http://www.cis.rit.edu/fairchild/PDFs/PAP07.pdf

cucim.skimage.exposure.
cumulative_distribution
(image, nbins=256)¶ 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
References
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage import exposure, img_as_float >>> image = img_as_float(cp.array(data.camera())) >>> hi = exposure.histogram(image) >>> cdf = exposure.cumulative_distribution(image) >>> cp.alltrue(cdf[0] == cp.cumsum(hi[0])/float(image.size)) True

cucim.skimage.exposure.
equalize_adapthist
(image, kernel_size=None, clip_limit=0.01, nbins=256)¶ Contrast Limited Adaptive Histogram Equalization (CLAHE).
An algorithm for local contrast enhancement, that uses histograms computed over different tile regions of the image. Local details can therefore be enhanced even in regions that are darker or lighter than most of the image.
 Parameters
 image(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 ofimage
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
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

cucim.skimage.exposure.
equalize_hist
(image, nbins=256, mask=None)¶ 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] with the author’s permission.
References

cucim.skimage.exposure.
histogram
(image, nbins=256, source_range='image', normalize=False)¶ Return histogram of image.
Unlike numpy.histogram, this function returns the centers of bins and does not rebin integer arrays. For integer arrays, each integer value has its own bin, which improves speed and intensityresolution.
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
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage import exposure, img_as_float >>> image = img_as_float(cp.array(data.camera())) >>> cp.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]))

cucim.skimage.exposure.
is_low_contrast
(image, fraction_threshold=0.05, lower_percentile=1, upper_percentile=99, method='linear')¶ Determine if an image is low contrast.
 Parameters
 imagearraylike
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]
 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
Examples
>>> import cupy as cp >>> image = cp.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

cucim.skimage.exposure.
match_histograms
(image, reference, *, multichannel=False)¶ 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 grayscale 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

cucim.skimage.exposure.
rescale_intensity
(image, in_range='image', out_range='dtype')¶ Return image after stretching or shrinking its intensity levels.
The desired intensity range of the input and output, in_range and out_range respectively, are used to stretch or shrink the intensity range of the input image. See examples below.
 Parameters
 imagearray
Image array.
 in_range, out_rangestr or 2tuple, 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.
 dtypename
Use intensity range based on desired dtype. Must be valid key in DTYPE_RANGE.
 2tuple
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
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 = cp.array([51, 102, 153], dtype=np.uint8) >>> rescale_intensity(image) array([ 0, 127, 255], dtype=uint8)
It’s easy to accidentally convert an image dtype from uint8 to float:
>>> 1.0 * image array([ 51., 102., 153.])
Use rescale_intensity to rescale to the proper range for float dtypes:
>>> image_float = 1.0 * image >>> rescale_intensity(image_float) array([0. , 0.5, 1. ])
To maintain the low contrast of the original, use the in_range parameter:
>>> rescale_intensity(image_float, in_range=(0, 255)) array([0.2, 0.4, 0.6])
If the min/max value of in_range is more/less than the min/max image intensity, then the intensity levels are clipped:
>>> rescale_intensity(image_float, in_range=(0, 102)) array([0.5, 1. , 1. ])
If you have an image with signed integers but want to rescale the image to just the positive range, use the out_range parameter. In that case, the output dtype will be float:
>>> image = cp.asarray([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 = cp.asarray([130, 130, 130], dtype=np.int32) >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32) array([127, 127, 127], dtype=int32)
feature¶

cucim.skimage.feature.
canny
(image, sigma=1.0, low_threshold=None, high_threshold=None, mask=None, use_quantiles=False)¶ 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 1pixel 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 XSobel and YSobel 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 8connected 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:679714, 1986 DOI:10.1109/TPAMI.1986.4767851
 2
William Green’s Canny tutorial https://en.wikipedia.org/wiki/Canny_edge_detector
Examples
>>> import cupy as cp >>> from cucim.skimage import feature >>> # Generate noisy image of a square >>> im = cp.zeros((256, 256)) >>> im[64:64, 64:64] = 1 >>> im += 0.2 * cp.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)

cucim.skimage.feature.
corner_foerstner
(image, sigma=1)¶ Compute Foerstner corner measure response image.
This corner detector uses information from the autocorrelation 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 autocorrelation 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. 281305). https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf
 2
Examples
>>> from cucim.skimage.feature import corner_foerstner, corner_peaks >>> square = cp.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]])

cucim.skimage.feature.
corner_harris
(image, method='k', k=0.05, eps=1e06, sigma=1)¶ Compute Harris corner measure response image.
This corner detector uses information from the autocorrelation 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 autocorrelation 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 autocorrelation matrix.
 Returns
 responsendarray
Harris response image.
References
Examples
>>> from cucim.skimage.feature import corner_harris, corner_peaks >>> square = cp.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]])

cucim.skimage.feature.
corner_kitchen_rosenfeld
(image, mode='constant', cval=0)¶ Compute Kitchen and Rosenfeld corner measure response image.
The corner measure is calculated as follows:
(imxx * imy**2 + imyy * imx**2  2 * imxy * imx * imy) / (imx**2 + imy**2)
Where imx and imy are the first and imxx, imxy, imyy the second derivatives.
 Parameters
 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). Graylevel corner detection. Pattern recognition letters, 1(2), 95102. DOI:10.1016/01678655(82)900204

cucim.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)¶ Find peaks in corner measure response image.
This differs from skimage.feature.peak_local_max in that it suppresses multiple connected peaks with the same accumulator value.
 Parameters
 imagendarray
Input image.
 min_distanceint, optional
The minimal allowed distance separating peaks.
 **
See
skimage.feature.peak_local_max()
. p_normfloat
Which Minkowski pnorm 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
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 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 postprocess the output of this function.
Examples
>>> from cucim.skimage.feature import peak_local_max >>> response = cp.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]])

cucim.skimage.feature.
corner_shi_tomasi
(image, sigma=1)¶ Compute ShiTomasi (KanadeTomasi) corner measure response image.
This corner detector uses information from the autocorrelation 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 autocorrelation matrix.
 Returns
 responsendarray
ShiTomasi response image.
References
Examples
>>> from cucim.skimage.feature import corner_shi_tomasi, corner_peaks >>> square = cp.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]])

cucim.skimage.feature.
daisy
(image, step=4, radius=15, rings=3, histograms=8, orientations=8, normalization='l1', sigmas=None, ring_radii=None, visualize=False)¶ Extract DAISY feature descriptors densely for the given image.
DAISY is a feature descriptor similar to SIFT formulated in a way that allows for fast dense extraction. Typically, this is practical for bagoffeatures image representations.
The implementation follows Tola et al. [1] but deviate on the following points:
Histogram bin contribution are smoothed with a circular Gaussian window over the tonal range (the angular range).
The sigma values of the spatial Gaussian smoothing in this code do not match the sigma values in the original code by Tola et al. [2]. In their code, spatial smoothing is applied to both the input image and the center histogram. However, this smoothing is not documented in [1] and, therefore, it is omitted.
 Parameters
 image(M, N) array
Input image (grayscale).
 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’: L1normalization of each descriptor.
‘l2’: L2normalization of each descriptor.
‘daisy’: L2normalization 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

cucim.skimage.feature.
hessian_matrix
(image, sigma=1, mode='constant', cval=0, order='rc')¶ 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 cdirections.
 Parameters
 imagendarray
Input image.
 sigmafloat
Standard deviation used for the Gaussian kernel, which is used as weighting function for the autocorrelation 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
>>> import cupy as cp >>> from cucim.skimage.feature import hessian_matrix >>> square = cp.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.]])

cucim.skimage.feature.
hessian_matrix_det
(image, sigma=1, approximate=True)¶ Compute the approximate Hessian Determinant over an image.
The 2D approximate method uses box filters over integral images to compute the approximate Hessian Determinant, as described in [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

cucim.skimage.feature.
hessian_matrix_eigvals
(H_elems)¶ Compute eigenvalues of Hessian matrix.
 Parameters
 H_elemslist of ndarray
The upperdiagonal elements of the Hessian matrix, as returned by 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 ithlargest eigenvalue at position (j, k).
Examples
>>> import cupy as cp >>> from cucim.skimage.feature import (hessian_matrix, ... hessian_matrix_eigvals) >>> square = cp.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.]])

cucim.skimage.feature.
masked_register_translation
(src_image, target_image, src_mask, target_mask=None, overlap_ratio=0.3)¶ Deprecated function. Use
cucim.skimage.registration.phase_cross_correlation
instead.

cucim.skimage.feature.
match_template
(image, template, pad_input=False, mode='constant', constant_values=0)¶ Match a template to a 2D or 3D 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 topleft 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
2D or 3D 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 (topleft 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 crosscorrelation are presented in [1]. This implementation uses FFT convolutions of the image and the template. Reference [2] presents similar derivations but the approximation presented in this reference is not used in our implementation.
This CuPy implementation does not force the image to float64 internally, but will use float32 for singleprecision inputs.
References
 1
J. P. Lewis, “Fast Normalized CrossCorrelation”, Industrial Light and Magic.
 2
Briechle and Hanebeck, “Template Matching using Fast Normalized Cross Correlation”, Proceedings of the SPIE (2001). DOI:10.1117/12.421129
Examples
>>> import cupy as cp >>> template = cp.zeros((3, 3)) >>> template[1, 1] = 1 >>> template array([[ 0., 0., 0.], [ 0., 1., 0.], [ 0., 0., 0.]]) >>> image = cp.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) >>> cp.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) >>> cp.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]])

cucim.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)¶ Local features for a single or multichannel 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
 featurescp.ndarray
Array of shape
image.shape + (n_features,)

cucim.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)¶ 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 gh2592.
 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_borderpixels of the border of the image. If tuple of nonnegative ints, the length of the tuple must match the input array’s dimensionality. Each element of the tuple will exclude peaks from within exclude_borderpixels 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 pnorm 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
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
>>> import cupy as cp >>> img1 = cp.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 = cp.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 = cp.zeros_like(img2, dtype=bool) >>> peak_mask[tuple(peak_idx.T)] = True >>> np.argwhere(peak_mask) array([[10, 10, 10], [15, 15, 15]])

cucim.skimage.feature.
register_translation
(src_image, target_image, upsample_factor=1, space='real', return_error=True)¶ Deprecated function. Use
cucim.skimage.registration.phase_cross_correlation
instead.

cucim.skimage.feature.
shape_index
(image, sigma=1, mode='constant', cval=0)¶ Compute the shape index.
The shape index, as defined by Koenderink & van Doorn [1], is a single valued measure of local curvature, assuming the image as a 3D plane with intensities representing heights.
It is derived from the 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:
¶ 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, 557564. DOI:10.1016/02628856(92)90076F
Examples
>>> from cucim.skimage.feature import shape_index >>> square = cp.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]])

cucim.skimage.feature.
structure_tensor
(image, sigma=1, mode='constant', cval=0, order=None)¶ Compute structure tensor using sum of squared differences.
The (2dimensional) structure tensor A is defined as:
A = [Arr Arc] [Arc Acc]
which is approximated by the weighted sum of squared differences in a local window around each pixel in the image. This formula can be extended to a larger number of dimensions (see [1]).
 Parameters
 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
Upperdiagonal elements of the structure tensor for each pixel in the input image.
See also
References
>>> import cupy as cp >>> from cucim.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.]])

cucim.skimage.feature.
structure_tensor_eigenvalues
(A_elems)¶ Compute eigenvalues of structure tensor.
 Parameters
 A_elemslist of ndarray
The upperdiagonal elements of the structure tensor, as returned by structure_tensor.
 Returns
 ndarray
The eigenvalues of the structure tensor, in decreasing order. The eigenvalues are the leading dimension. That is, the coordinate [i, j, k] corresponds to the ithlargest eigenvalue at position (j, k).
Examples
>>> import cupy as cp >>> from cucim.skimage.feature import structure_tensor >>> from cucim.skimage.feature import structure_tensor_eigenvalues >>> square = cp.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.]])

cucim.skimage.feature.
structure_tensor_eigvals
(Axx, Axy, Ayy)¶ 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
>>> import cupy as cp >>> from cucim.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.]])
filters¶

class
cucim.skimage.filters.
LPIFilter2D
(impulse_response, **filter_params)¶ Linear PositionInvariant Filter (2dimensional)
Methods
__call__
(data)Apply the filter to the given data.

cucim.skimage.filters.
apply_hysteresis_threshold
(image, low, high)¶ Apply hysteresis thresholding to
image
.This algorithm finds regions where
image
is greater thanhigh
ORimage
is greater thanlow
and that region is connected to a region greater thanhigh
. 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 whereimage
was above the hysteresis threshold.
 thresholdedarray of bool, same shape as
References
 1
J. Canny. A computational approach to edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence. 1986; vol. 8, pp.679698. DOI:10.1109/TPAMI.1986.4767851
Examples
>>> import cupy as cp >>> from cucim.skimage.filters import apply_hysteresis_threshold >>> image = cp.asarray([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])

cucim.skimage.filters.
correlate_sparse
(image, kernel, mode='reflect')¶ Compute valid crosscorrelation of padded_array and kernel.
This function is fast when kernel is large with many zeros.
See
scipy.ndimage.correlate
for a description of crosscorrelation. 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 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 crosscorrelating image with kernel. If mode ‘valid’ is used, the resulting shape is (MQ+1, NR+1,[ …,] PS+1).

cucim.skimage.filters.
difference_of_gaussians
(image, low_sigma, high_sigma=None, *, mode='nearest', cval=0, multichannel=False, truncate=4.0)¶ Find features between
low_sigma
andhigh_sigma
in size.This function uses the Difference of Gaussians method for applying bandpass filters to multidimensional arrays. The input array is blurred with two Gaussian kernels of differing sigmas to produce two intermediate, filtered images. The moreblurred image is then subtracted from the lessblurred image. The final output image will therefore have had highfrequency components attenuated by the smallersigma Gaussian, and low frequency components will have been removed due to their presence in the moreblurred 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, wherecval
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 bylow_sigma
. The values forhigh_sigma
must always be greater than or equal to the corresponding values inlow_sigma
, or aValueError
will be raised.When
high_sigma
is none, the values forhigh_sigma
will be calculated as 1.6x the corresponding values inlow_sigma
. This ratio was originally proposed by Marr and Hildreth (1980) [1] and is commonly used when approximating the inverted Laplacian of Gaussian, which is used in edge and blob detection.Input image is converted according to the conventions of
img_as_float
.Except for sigma values, all parameters are used for both filters.
References
 1
Marr, D. and Hildreth, E. Theory of Edge Detection. Proc. R. Soc. Lond. Series B 207, 187217 (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 cucim.skimage.filters import difference_of_gaussians >>> astro = cp.asarray(astronaut()) >>> filtered_image = difference_of_gaussians(astro, 2, 10, ... multichannel=True)
Apply a Laplacian of Gaussian filter as approximated by the Difference of Gaussians filter:
>>> filtered_image = difference_of_gaussians(astro, 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 >>> cam = cp.array(camera()) >>> filtered_image = difference_of_gaussians(cam, (2,5), (3,20))

cucim.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)¶ 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 2D and 3D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to vessels, according to the method described in [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_range2tuple 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 platelike structure.
 betafloat, optional
Frangi correction constant that adjusts the filter’s sensitivity to deviation from a bloblike 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).
Notes
Written by Marc Schrijver, November 2001 ReWritten by D. J. Kroon, University of Twente, May 2009, [2] Adoption of 3D version from D. G. Ellis, Januar 20017, [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 ComputerAssisted Intervention (pp. 130137). Springer Berlin Heidelberg. DOI:10.1007/BFb0056195
 2
Kroon, D. J.: Hessian based Frangi vesselness filter.
 3
Ellis, D. G.: https://github.com/ellisdg/frangi3d/tree/master/frangi

cucim.skimage.filters.
gabor
(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)¶ Return real and imaginary responses to Gabor filter.
The real and imaginary parts of the Gabor filter kernel are applied to the image and the response is returned as a pair of arrays.
Gabor filter is a linear filter with a Gaussian kernel which is modulated by a sinusoidal plane wave. Frequency and orientation representations of the Gabor filter are similar to those of the human visual system. Gabor filter banks are commonly used in computer vision and image processing. They are especially suitable for edge detection and texture classification.
 Parameters
 image2D 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 xdirection.
 bandwidthfloat, optional
The bandwidth captured by the filter. For fixed bandwidth,
sigma_x
andsigma_y
will decrease with increasing frequency. This value is ignored ifsigma_x
andsigma_y
are set by the user. sigma_x, sigma_yfloat, optional
Standard deviation in x and ydirections. 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
Examples
>>> import cupy as cp >>> from cucim.skimage.filters import gabor >>> from skimage import data, io >>> from matplotlib import pyplot as plt
>>> image = cp.array(data.coins()) >>> # detecting edges in a coin image >>> filt_real, filt_imag = gabor(image, frequency=0.6) >>> plt.figure() >>> io.imshow(cp.asnumpy(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(cp.asnumpy(filt_real) >>> io.show()

cucim.skimage.filters.
gabor_kernel
(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, *, float_dtype=<class 'numpy.float64'>)¶ 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 xdirection.
 bandwidthfloat, optional
The bandwidth captured by the filter. For fixed bandwidth,
sigma_x
andsigma_y
will decrease with increasing frequency. This value is ignored ifsigma_x
andsigma_y
are set by the user. sigma_x, sigma_yfloat, optional
Standard deviation in x and ydirections. 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
Examples
>>> import cupy as cp >>> from cucim.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(cp.asnumpy(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(cp.asnumpy(gk.real)) >>> io.show()

cucim.skimage.filters.
gaussian
(image, sigma=1, output=None, mode='nearest', cval=0, multichannel=None, preserve_range=False, truncate=4.0)¶ Multidimensional Gaussian filter.
 Parameters
 imagearraylike
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, wherecval
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://scikitimage.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 providedimage
. Ifoutput
is not provided, another array will be allocated and returned as the result.The multidimensional filter is implemented as a sequence of onedimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision.
Examples
>>> import cupy as cp >>> a = cp.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 = cp.array(astronaut()) >>> filtered_img = gaussian(image, sigma=1, multichannel=True)

cucim.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)¶ 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 2D and 3D images. Almost equal to Frangi filter, but uses alternative method of smoothing. Refer to [1] to find the differences between Frangi and Hessian filters.
 Parameters
 image(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_range2tuple 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 bloblike 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).
Notes
Written by Marc Schrijver (November 2001) ReWritten by D. J. Kroon University of Twente (May 2009) [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. 609622). Springer International Publishing. DOI:10.1007/9783319168111_40
 2
Kroon, D. J.: Hessian based Frangi vesselness filter.

cucim.skimage.filters.
inverse
(data, impulse_response=None, filter_params={}, max_gain=2, predefined_filter=None)¶ 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.

cucim.skimage.filters.
laplace
(image, ksize=3, mask=None)¶ 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().

cucim.skimage.filters.
median
(image, selem=None, out=None, mode='nearest', cval=0.0, behavior='ndimage')¶ Return local median of an image.
 Parameters
 imagearraylike
Input image.
 selemndarray, optional
If
behavior=='rank'
,selem
is a 2D array of 1’s and 0’s. Ifbehavior=='ndimage'
,selem
is a ND array of 1’s and 0’s with the same number of dimension thanimage
. If None,selem
will be a ND 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 whenbehavior='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 whenbehavior='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()
. The new behavior will call thescipy.ndimage.median_filter()
. Default is ‘ndimage’.New in version 0.15:
behavior
is introduced in 0.15Changed in version 0.16: Default
behavior
has been changed from ‘rank’ to ‘ndimage’
 Returns
 out2D array (same dtype as input image)
Output image.
See also
skimage.filters.rank.median
Rankbased implementation of the median filtering offering more flexibility with additional parameters but dedicated for unsigned integer images.
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage.morphology import disk >>> from cucim.skimage.filters import median >>> img = cp.array(data.camera()) >>> med = median(img, disk(5))

cucim.skimage.filters.
meijering
(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0)¶ Filter an image with the Meijering neuriteness filter.
This filter can be used to detect continuous ridges, e.g. neurites, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects.
Calculates the eigenvectors of the Hessian to compute the similarity of an image region to neurites, according to the method described in [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 platelike 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).
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), 167176. DOI:10.1002/cyto.a.20022

cucim.skimage.filters.
prewitt
(image, mask=None, *, axis=None, mode='reflect', cval=0.0)¶ 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 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.
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
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage import filters >>> camera = cp.array(data.camera()) >>> edges = filters.prewitt(camera)

cucim.skimage.filters.
prewitt_h
(image, mask=None)¶ Find the horizontal edges of an image using the Prewitt transform.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D 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

cucim.skimage.filters.
prewitt_v
(image, mask=None)¶ Find the vertical edges of an image using the Prewitt transform.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D 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

cucim.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 rankorder value. Parameters
 imagendarray
 Returns
 labelsndarray of type np.uint32, of shape image.shape
New array where each pixel has the rankorder value of the corresponding pixel in
image
. Pixel values are between 0 and n  1, where n is the number of distinct unique values inimage
. original_values1D ndarray
Unique original values of
image
Examples
>>> a = cp.asarray([[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 = cp.asarray([1., 2.5, 3.1, 2.5]) >>> rank_order(b) (array([0, 1, 2, 1], dtype=uint32), array([1. , 2.5, 3.1]))

cucim.skimage.filters.
roberts
(image, mask=None)¶ Find the edge magnitude using Roberts’ cross operator.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D array
The Roberts’ Cross edge map.
Examples
>>> import cupy as cp >>> from skimage import data >>> camera = cp.array(data.camera()) >>> from cucim.skimage import filters >>> edges = filters.roberts(camera)

cucim.skimage.filters.
roberts_neg_diag
(image, mask=None)¶ Find the cross edges of an image using the Roberts’ Cross operator.
The kernel is applied to the input image to produce separate measurements of the gradient component one orientation.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D array
The Robert’s edge map.
Notes
We use the following kernel:
0 1 1 0

cucim.skimage.filters.
roberts_pos_diag
(image, mask=None)¶ Find the cross edges of an image using Roberts’ cross operator.
The kernel is applied to the input image to produce separate measurements of the gradient component one orientation.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D array
The Robert’s edge map.
Notes
We use the following kernel:
1 0 0 1

cucim.skimage.filters.
sato
(image, sigmas=range(1, 10, 2), black_ridges=True, mode=None, cval=0)¶ Filter an image with the Sato tubeness filter.
This filter can be used to detect continuous ridges, e.g. tubes, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects.
Defined only for 2D and 3D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [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).
References
 1
Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., Koller, T., …, Kikinis, R. (1998). Threedimensional multiscale line filter for segmentation and visualization of curvilinear structures in medical images. Medical image analysis, 2(2), 143168. DOI:10.1016/S13618415(98)800091

cucim.skimage.filters.
scharr
(image, mask=None, *, axis=None, mode='reflect', cval=0.0)¶ 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 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.
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
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage import filters >>> camera = cp.array(data.camera()) >>> edges = filters.scharr(camera)

cucim.skimage.filters.
scharr_h
(image, mask=None)¶ Find the horizontal edges of an image using the Scharr transform.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D 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.

cucim.skimage.filters.
scharr_v
(image, mask=None)¶ Find the vertical edges of an image using the Scharr transform.
 Parameters
 image2D array
Image to process
 mask2D 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
 output2D 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.

cucim.skimage.filters.
sobel
(image, mask=None, *, axis=None, mode='reflect', cval=0.0)¶ 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 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.
References
 1
D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives.
 2
Examples
>>> import cupy as cp >>> from skimage import data >>> from cucim.skimage import filters >>> camera = cp.array(data.camera()) >>> edges = filters.sobel(camera)

cucim.skimage.filters.
sobel_h
(image, mask=None)¶ Find the horizontal edges of an image using the Sobel transform.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D array
The Sobel edge map.
Notes
We use the following kernel:
1 2 1 0 0 0 1 2 1

cucim.skimage.filters.
sobel_v
(image, mask=None)¶ Find the vertical edges of an image using the Sobel transform.
 Parameters
 image2D array
Image to process.
 mask2D 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
 output2D array
The Sobel edge map.
Notes
We use the following kernel:
1 0 1 2 0 2 1 0 1

cucim.skimage.filters.
threshold_isodata
(image=None, nbins=256, return_all=False, *, hist=None)¶ Return threshold value(s) based on ISODATA method.
Histogrambased threshold, known as RidlerCalvard method or intermeans. 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 binwidth.
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 2tuple 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: 630632, DOI:10.1109/TSMC.1978.4310039
 2
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146165, http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf DOI:10.1117/1.1631315
 3
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
>>> from skimage.data import coins >>> image = coins() >>> thresh = threshold_isodata(image) >>> binary = image > thresh

cucim.skimage.filters.
threshold_li
(image, *, tolerance=None, initial_guess=None, iter_callback=None)¶ 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 globallyoptimal 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 evenskimage.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): 617625 DOI:10.1016/00313203(93)90115D
 2
Li C.H. and Tam P.K.S. (1998) “An Iterative Algorithm for Minimum Cross Entropy Thresholding” Pattern Recognition Letters, 18(8): 771776 DOI:10.1016/S01678655(98)000579
 3
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146165 DOI:10.1117/1.1631315
 4
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_li(image) >>> binary = image > thresh

cucim.skimage.filters.
threshold_local
(image, block_size, method='gaussian', offset=0, mode='reflect', param=None, cval=0)¶ Compute a threshold mask image based on local pixel neighborhood.
Also known as adaptive or dynamic thresholding. The threshold value is the weighted mean for the local neighborhood of a pixel subtracted by a constant. Alternatively the threshold can be determined dynamically by a given function, using the ‘generic’ method.
 Parameters
 image(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
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)

cucim.skimage.filters.
threshold_mean
(image)¶ 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 histogrambased thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532537, 1993. DOI:10.1006/cgip.1993.1040
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_mean(image) >>> binary = image > thresh

cucim.skimage.filters.
threshold_minimum
(image=None, nbins=256, max_iter=10000, *, hist=None)¶ Return threshold value based on minimum method.
The histogram of the input
image
is computed if not provided and smoothed until there are only two maxima. Then the minimum in between is the threshold value.Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored.
 Parameters
 image(M, N) ndarray, optional
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 2tuple 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 histogrambased thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532537, 1993.
 2
Prewitt, JMS & Mendelsohn, ML (1966), “The analysis of cell images”, Annals of the New York Academy of Sciences 128: 10351053 DOI:10.1111/j.17496632.1965.tb11715.x
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_minimum(image) >>> binary = image > thresh

cucim.skimage.filters.
threshold_multiotsu
(image, classes=3, nbins=256)¶ Generate classes1 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] 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^{C1}}{(C1)!}\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, PS., Chen, TS. and Chung, PC., “A fast algorithm for multilevel thresholding”, Journal of Information Science and Engineering 17 (5): 713727, 2001. Available at: <https://ftp.iis.sinica.edu.tw/JISE/2001/200109_01.pdf> DOI:10.6688/JISE.2001.17.5.1
 2
Tosa, Y., “MultiOtsu Threshold”, a java plugin for ImageJ. Available at: <http://imagej.net/plugins/download/Multi_OtsuThreshold.java>
Examples
>>> import cupy as cp >>> from cucim.skimage.color import label2rgb >>> from skimage import data >>> image = cp.asarray(data.camera()) >>> thresholds = threshold_multiotsu(image) >>> regions = cp.digitize(image, bins=thresholds) >>> regions_colorized = label2rgb(regions)

cucim.skimage.filters.
threshold_niblack
(image, window_size=15, k=0.2)¶ Applies Niblack local threshold to an array.
A threshold T is calculated for every pixel in the image using the following formula:
T = m(x,y)  k * s(x,y)
where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation.
 Parameters
 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 useq=1
.References
 1
W. Niblack, An introduction to Digital Image Processing, PrenticeHall, 1986.
 2
D. Bradley and G. Roth, “Adaptive thresholding using Integral Image”, Journal of Graphics Tools 12(2), pp. 1321, 2007. DOI:10.1080/2151237X.2007.10129236
Examples
>>> from skimage import data >>> image = data.page() >>> threshold_image = threshold_niblack(image, window_size=7, k=0.1)

cucim.skimage.filters.
threshold_otsu
(image=None, nbins=256, *, hist=None)¶ Return threshold value based on Otsu’s method.
Either image or hist must be provided. If hist is provided, the actual histogram of the image is ignored.
 Parameters
 image(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 2tuple 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
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_otsu(image) >>> binary = image <= thresh

cucim.skimage.filters.
threshold_sauvola
(image, window_size=15, k=0.2, r=None)¶ Applies Sauvola local threshold to an array. Sauvola is a modification of Niblack technique.
In the original method a threshold T is calculated for every pixel in the image using the following formula:
T = m(x,y) * (1 + k * ((s(x,y) / R)  1))
where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation. R is the maximum standard deviation of a 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. 225236, 2000. DOI:10.1016/S00313203(99)000552
Examples
>>> from skimage import data >>> image = data.page() >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2) >>> binary_image = image > t_sauvola

cucim.skimage.filters.
threshold_triangle
(image, nbins=256)¶ 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. 741753 DOI:10.1177/25.7.70454
 2
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_triangle(image) >>> binary = image > thresh

cucim.skimage.filters.
threshold_yen
(image=None, nbins=256, *, hist=None)¶ Return threshold value based on Yen’s method. Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored.
 Parameters
 image(N, M) ndarray, optional
Input image.
 nbinsint, optional
Number of bins used to calculate histogram. This value is ignored for integer arrays.
 histarray, or 2tuple 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): 370378. DOI:10.1109/83.366472
 2
Sezgin M. and Sankur B. (2004) “Survey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146165, DOI:10.1117/1.1631315 http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
 3
ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
>>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_yen(image) >>> binary = image <= thresh

cucim.skimage.filters.
try_all_threshold
(image, figsize=(8, 5), verbose=True)¶ 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)

cucim.skimage.filters.
unsharp_mask
(image, radius=1.0, amount=1.0, multichannel=False, preserve_range=False)¶ 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://scikitimage.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 illposed 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].
References
 1
Maria Petrou, Costas Petrou “Image Processing: The Fundamentals”, (2010), ed ii., page 357, ISBN 13: 9781119994398 DOI:10.1002/9781119994398
 2
Wikipedia. Unsharp masking https://en.wikipedia.org/wiki/Unsharp_masking
Examples
>>> import cupy as cp >>> array = cp.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) >>> cp.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 = cp.ones(shape=(5,5), dtype=np.int8)*100 >>> array[2,2] = 127 >>> cp.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]])
>>> cp.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. ]])

cucim.skimage.filters.
wiener
(data, impulse_response=None, filter_params={}, K=0.25, predefined_filter=None)¶ 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.

cucim.skimage.filters.
window
(window_type, shape, warp_kwargs=None)¶ Return an ndimensional 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 (e.g.,
warp_kwargs={'order':3}
to change interpolation method).
 Returns
 nd_windowndarray
A window of the specified
shape
.dtype
isnp.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 theorder
keyword argument passed to skimage.transform.warp.Some coordinates in the output window will be outside of the original signal; these will be filled in with zeros.
Window types:  boxcar  triang  blackman  hamming  hann  bartlett  flattop  parzen  bohman  blackmanharris  nuttall  barthann  kaiser (needs beta)  gaussian (needs standard deviation)  general_gaussian (needs power, width)  slepian (needs width)  dpss (needs normalized halfbandwidth)  chebwin (needs attenuation)  exponential (needs decay scale)  tukey (needs taper fraction)
References
 1
Twodimensional window design, Wikipedia, https://en.wikipedia.org/wiki/Two_dimensional_window_design
Examples
Return a Hann window with shape (512, 512):
>>> from cucim.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))
measure¶

cucim.skimage.measure.
approximate_polygon
(coords, tolerance)¶ Approximate a polygonal chain with the specified tolerance.
It is based on the DouglasPeucker 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

cucim.skimage.measure.
block_reduce
(image, block_size, func=<function sum>, cval=0, func_kwargs=None)¶ Downsample image by applying function func to local blocks.
This function is useful for max and mean pooling, for example.
 Parameters
 imagendarray
Ndimensional input image.
 block_sizearray_like
Array containing downsampling 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 arenumpy.sum
,numpy.min
,numpy.max
,numpy.mean
andnumpy.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
Downsampled image with same number of dimensions as input image.
Examples
>>> import cupy as cp >>> from skimage.measure import block_reduce >>> image = cp.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=cp.mean) array([[[16., 17., 18., 19.]]]) >>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=cp.max) >>> image_max1 array([[[11]], [[23]], [[35]]]) >>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=cp.max) >>> image_max2 array([[[27], [31], [35]]])

cucim.skimage.measure.
centroid
(image)¶ Return the (weighted) centroid of an image.
 Parameters
 imagearray
The input image.
 Returns
 centertuple of float, length
image.ndim
The centroid of the (nonzero) pixels in
image
.
 centertuple of float, length
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import centroid >>> image = cp.zeros((20, 20), dtype=np.float64) >>> image[13:17, 13:17] = 0.5 >>> image[10:12, 10:12] = 1 >>> centroid(image) array([13.16666667, 13.16666667])

cucim.skimage.measure.
inertia_tensor
(image, mu=None, *, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ Compute the inertia tensor of the input image.
 Parameters
 imagearray
The input image.
 muarray, optional
The precomputed central moments of
image
. The inertia tensor computation requires the central moments of the image. If an application requires both the central moments and the inertia tensor (for example, skimage.measure.regionprops), then it is more efficient to precompute 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\).
 Tarray, shape
References
 1
https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor
 2
Bernd Jähne. SpatioTemporal Image Processing: Theory and Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993.

cucim.skimage.measure.
inertia_tensor_eigvals
(image, mu=None, T=None, *, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along the image axes. (See inertia_tensor.) The relative magnitude of the eigenvalues of the tensor is thus a measure of the elongation of a (bright) object in the image.
 Parameters
 imagearray
The input image.
 muarray, optional
The precomputed central moments of
image
. Tarray, shape
(image.ndim, image.ndim)
The precomputed inertia tensor. If
T
is given,mu
andimage
are ignored.
 Returns
 eigvalslist of float, length
image.ndim
The eigenvalues of the inertia tensor of
image
, in descending order.
 eigvalslist of float, length
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.

cucim.skimage.measure.
label
(input, background=None, return_num=False, connectivity=None)¶ Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1 or 2connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:
1connectivity 2connectivity diagonal connection closeup [ ] [ ] [ ] [ ] [ ]  \  /  < 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, 0valued 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 ofinput.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
Notes
Currently the cucim implementation of this function always uses 32bit integers for the label array. This is done for performance. In the future 64bit integer support may also be added for better skimage compatibility.
References
 1
Christophe Fiorio and Jens Gustedt, “Two linear time UnionFind strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165181.
 2
Kensheng Wu, Ekow Otoo and Arie Shoshani, “Optimizing connected component labeling algorithms”, Paper LBNL56864, 2005, Lawrence Berkeley National Laboratory (University of California), http://repositories.cdlib.org/lbnl/LBNL56864
Examples
>>> import cupy as cp >>> x = cp.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 = cp.asarray([[1, 0, 0], ... [1, 1, 5], ... [0, 0, 0]]) >>> print(label(x)) [[1 0 0] [1 1 2] [0 0 0]]

cucim.skimage.measure.
moments
(image, order=3)¶ Calculate all raw image moments up to a certain order.
 The following properties can be calculated from raw image moments:
Area as:
M[0, 0]
.Centroid as: {
M[1, 0] / M[0, 0]
,M[0, 1] / M[0, 0]
}.
Note that raw moments are neither translation, scale nor rotation invariant.
 Parameters
 imagenD floating point 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.
 m(
References
 1
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
 2
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 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
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import moments >>> image = cp.zeros((20, 20), dtype=cp.float64) >>> image[13:17, 13:17] = 1 >>> M = moments(image) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> centroid (14.5, 14.5)

cucim.skimage.measure.
moments_central
(image, center=None, order=3, **kwargs)¶ Calculate all central image moments up to a certain order.
The center coordinates (cr, cc) can be calculated from the raw moments as: {
M[1, 0] / M[0, 0]
,M[0, 1] / M[0, 0]
}.Note that central moments are translation invariant but not scale and rotation invariant.
 Parameters
 imagenD floating point 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.
 mu(
References
 1
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
 2
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 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
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import moments, moments_central >>> image = cp.zeros((20, 20), dtype=cp.float64) >>> image[13:17, 13:17] = 1 >>> M = moments(image) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> moments_central(image, centroid) array([[16., 0., 20., 0.], [ 0., 0., 0., 0.], [20., 0., 25., 0.], [ 0., 0., 0., 0.]])

cucim.skimage.measure.
moments_coords
(coords, order=3)¶ Calculate all raw image moments up to a certain order.
 The following properties can be calculated from raw image moments:
Area as:
M[0, 0]
.Centroid as: {
M[1, 0] / M[0, 0]
,M[0, 1] / M[0, 0]
}.
Note that raw moments are neither translation, scale nor rotation invariant.
 Parameters
 coords(N, D) floating point 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)
 M(
References
 1
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import moments_coords >>> coords = cp.array([[row, col] ... for row in range(13, 17) ... for col in range(14, 18)], dtype=cp.float64) >>> M = moments_coords(coords) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> centroid (14.5, 15.5)

cucim.skimage.measure.
moments_coords_central
(coords, center=None, order=3)¶ Calculate all central image moments up to a certain order.
 The following properties can be calculated from raw image moments:
Area as:
M[0, 0]
.Centroid as: {
M[1, 0] / M[0, 0]
,M[0, 1] / M[0, 0]
}.
Note that raw moments are neither translation, scale nor rotation invariant.
 Parameters
 coords(N, D) floating point or uint8 array
Array of N points that describe an image of D dimensionality in Cartesian space. A tuple of coordinates as returned by
cp.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)
 Mc(
References
 1
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import moments_coords_central >>> coords = cp.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, oddorder 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 = cp.concatenate((coords, [[17, 17]]), axis=0) >>> cp.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):
>>> cp.allclose(moments_coords(coords), ... moments_coords_central(coords, (0, 0))) True

cucim.skimage.measure.
moments_hu
(nu)¶ Calculate Hu’s set of image moments (2Donly).
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.
Notes
Due to the small array sizes, this function will be faster on the CPU. Consider transfering
nu
to the host and runningskimage.measure.moments_hu
if the moments are not needed on the device.References
 1
M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT8, pp. 179187, 1962
 2
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
 3
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 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
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import (moments_central, moments_hu, ... moments_normalized) >>> image = cp.zeros((20, 20), dtype=np.float64) >>> image[13:17, 13:17] = 0.5 >>> image[10:12, 10:12] = 1 >>> mu = moments_central(image) >>> nu = moments_normalized(mu) >>> moments_hu(nu) array([7.45370370e01, 3.51165981e01, 1.04049179e01, 4.06442107e02, 2.64312299e03, 2.40854582e02, 4.33680869e19])

cucim.skimage.measure.
moments_normalized
(mu, order=3)¶ 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.
 nu(
Notes
Due to the small array sizes, this function should be faster on the CPU. Consider transfering
mu
to the host and runningskimage.measure.moments_normalized
.References
 1
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
 2
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 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
Examples
>>> import cupy as cp >>> from cucim.skimage.measure import (moments, moments_central, ... moments_normalized) >>> image = cp.zeros((20, 20), dtype=cp.float64) >>> image[13:17, 13:17] = 1 >>> m = moments(image) >>> centroid = (m[0, 1] / m[0, 0], m[1, 0] / m[0, 0]) >>> mu = moments_central(image, centroid) >>> moments_normalized(mu) array([[ nan, nan, 0.078125 , 0. ], [ nan, 0. , 0. , 0. ], [0.078125 , 0. , 0.00610352, 0. ], [0. , 0. , 0. , 0. ]])

cucim.skimage.measure.
perimeter
(image, neighbourhood=4)¶ 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...

cucim.skimage.measure.
profile_line
(image, src, dst, linewidth=1, order=None, mode=None, cval=0.0, *, reduce_func=<function mean>)¶ 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 05. See 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
>>> import cupy as cp >>> x = cp.asarray([[1, 1, 1, 2, 2, 2]]) >>> img = cp.vstack([cp.zeros_like(x), x, x, x, cp.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=cp.mean) array([0.66666667, 0.66666667, 0.66666667, 1.33333333]) >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=cp.max) array([1, 1, 1, 2]) >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=cp.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=cp.sqrt) array([[1. , 1. , 0. ], [1. , 1. , 0. ], [1. , 1. , 0. ], [1.41421356, 1.41421356, 0. ]])

cucim.skimage.measure.
regionprops
(label_image, intensity_image=None, cache=True, coordinates=None, *, extra_properties=None)¶ 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 bynumpy.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, useregionprops(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 scikitimage.
See 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
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 halfopen 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 secondmoments 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 nonzero 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] 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 counterclockwise.
 perimeterfloat
Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4connectivity.
 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 (intensityweighted 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. SpringerVerlag, London, 2009.
 2
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 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
 5
W. Pabst, E. Gregorová. Characterization of particles and particle systems, pp. 2728. ICT Prague, 2007. https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf
Examples
>>> from skimage import data, util >>> from cucim.skimage.measure import label, regionprops >>> img = cp.asarray(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 cucim.skimage.measure import label, regionprops >>> import numpy as np >>> img = cp.asarray(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

cucim.skimage.measure.
regionprops_table
(label_image, intensity_image=None, properties=('label', 'bbox'), *, cache=True, separator='', extra_properties=None)¶ Compute image properties and return them as a pandascompatible 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()
. 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 nonscalar 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_tensor00
,inertia_tensor01
,inertia_tensor10
, andinertia_tensor11
(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
andcoords
. 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_tensor00': array([ 4.012...e+03, 8.51..., ...]), ... ..., 'inertia_tensor_eigvals1': 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_tensor00 ... inertia_tensor_eigvals1 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 builtin 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 quartiles0 quartiles1 quartiles2 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

cucim.skimage.measure.
shannon_entropy
(image, base=2)¶ Calculate the Shannon entropy of an image.
The Shannon entropy is defined as S = sum(pk * log(pk)), where pk are frequency/probability of pixels of value k.
 Parameters
 image(N, M) ndarray
Grayscale input image.
 basefloat, optional
The logarithmic base to use.
 Returns
 entropy0dimensional float cupy.ndarray
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

cucim.skimage.measure.
subdivide_polygon
(coords, degree=2, preserve_ends=False)¶ Subdivision of polygonal curves using BSplines.
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 BSpline. Default is 2.
 preserve_endsbool, optional
Preserve first and last coordinate of noncircular polygon. Default is False.
 Returns
 coords(M, 2) array
Subdivided coordinate array.
References
metrics¶

cucim.skimage.metrics.
mean_squared_error
(image0, image1)¶ Compute the meansquared error between two images.
 Parameters
 image0, image1ndarray
Images. Any dimensionality, must have same shape.
 Returns
 msefloat
The meansquared error (MSE) metric.
Notes
Changed in version 0.16: This function was renamed from
skimage.measure.compare_mse
toskimage.metrics.mean_squared_error
.

cucim.skimage.metrics.
normalized_root_mse
(image_true, image_test, *, normalization='euclidean')¶ Compute the normalized root meansquared error (NRMSE) between two images.
 Parameters
 image_truendarray
Groundtruth image, same shape as im_test.
 image_testndarray
Test image.
 normalization{‘euclidean’, ‘minmax’, ‘mean’}, optional
Controls the normalization method to use in the denominator of the NRMSE. There is no standard method of normalization across the literature [1]. The methods available here are as follows:
‘euclidean’ : normalize by the averaged Euclidean norm of
im_true
:NRMSE = RMSE * sqrt(N) /  im_true 
where  .  denotes the Frobenius norm and
N = im_true.size
. This result is equivalent to:NRMSE =  im_true  im_test  /  im_true .
‘minmax’ : 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
toskimage.metrics.normalized_root_mse
.References

cucim.skimage.metrics.
peak_signal_noise_ratio
(image_true, image_test, *, data_range=None)¶ Compute the peak signal to noise ratio (PSNR) for an image.
 Parameters
 image_truendarray
Groundtruth 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 datatype.
 Returns
 psnrfloat
The PSNR metric.
Notes
Changed in version 0.16: This function was renamed from
skimage.measure.compare_psnr
toskimage.metrics.peak_signal_noise_ratio
.References

cucim.skimage.metrics.
structural_similarity
(im1, im2, *, win_size=None, gradient=False, data_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs)¶ Compute the mean structural similarity index between two images.
 Parameters
 im1, im2ndarray
Images. Any dimensionality with same shape.
 win_sizeint or None, optional
The sidelength 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 datatype.
 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]. 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 N1 rather than, N where N is the number of pixels within the sliding window.
 K1float
Algorithm parameter, K1 (small constant, see [1]).
 K2float
Algorithm parameter, K2 (small constant, see [1]).
 sigmafloat
Standard deviation for the Gaussian when gaussian_weights is True.
Notes
To match the implementation of Wang et. al. [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
toskimage.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, 600612. https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf, DOI:10.1109/TIP.2003.819861
 2
Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613621. arXiv:0901.0065 DOI:10.1007/s100430090119z
morphology¶

cucim.skimage.morphology.
ball
(radius, dtype=<class 'numpy.uint8'>)¶ Generates a ballshaped 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 ballshaped structuring element.
 Returns
 selemndarray
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
 Other Parameters
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
binary_closing
(image, selem=None, out=None)¶ 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 2D array of 1’s and 0’s. If None, use a crossshaped 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.

cucim.skimage.morphology.
binary_dilation
(image, selem=None, out=None)¶ 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 2D array of 1’s and 0’s. If None, use a crossshaped 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]
.

cucim.skimage.morphology.
binary_erosion
(image, selem=None, out=None)¶ 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 2D array of 1’s and 0’s. If None, use a crossshaped 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]
.

cucim.skimage.morphology.
binary_opening
(image, selem=None, out=None)¶ 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 2D array of 1’s and 0’s. If None, use a crossshaped 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.

cucim.skimage.morphology.
black_tophat
(image, selem=None, out=None)¶ 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 2D array of 1’s and 0’s. If None, use crossshaped 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
References
Examples
>>> # Change dark peak to bright peak and subtract background >>> import cupy as cp >>> from cucim.skimage.morphology import square >>> dark_on_grey = cp.asarray([[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=cp.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)

cucim.skimage.morphology.
closing
(image, selem=None, out=None)¶ 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 crossshaped 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 cupy as cp >>> from cucim.skimage.morphology import square >>> broken_line = cp.asarray([[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=cp.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)

cucim.skimage.morphology.
cube
(width, dtype=<class 'numpy.uint8'>)¶ Generates a cubeshaped 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
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
diamond
(radius, dtype=<class 'numpy.uint8'>)¶ Generates a flat, diamondshaped 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 diamondshaped structuring element.
 Returns
 selemndarray
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
 Other Parameters
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
dilation
(image, selem=None, out=None, shift_x=False, shift_y=False)¶ 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 2D array of 1’s and 0’s. If None, use crossshaped 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 bitdepth) data, the lower algorithm complexity makes the skimage.filters.rank.maximum function more efficient for larger images and structuring elements.
Examples
>>> # Dilation enlarges bright regions >>> import cupy as cp >>> from cucim.skimage.morphology import square >>> bright_pixel = cp.asarray([[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=cp.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)

cucim.skimage.morphology.
disk
(radius, dtype=<class 'numpy.uint8'>)¶ Generates a flat, diskshaped 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 diskshaped structuring element.
 Returns
 selemndarray
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
 Other Parameters
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
erosion
(image, selem=None, out=None, shift_x=False, shift_y=False)¶ 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 crossshaped 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
(anduint16
up to a certain bitdepth) data, the lower algorithm complexity makes the skimage.filters.rank.minimum function more efficient for larger images and structuring elements.Examples
>>> # Erosion shrinks bright regions >>> import cupy as cp >>> from cucim.skimage.morphology import square >>> bright_square = cp.asarray([[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=cp.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)

cucim.skimage.morphology.
octagon
(m, n, dtype=<class 'numpy.uint8'>)¶ 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
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
octahedron
(radius, dtype=<class 'numpy.uint8'>)¶ Generates a octahedronshaped 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 octahedronshaped structuring element.
 Returns
 selemndarray
The structuring element where elements of the neighborhood are 1 and 0 otherwise.
 Other Parameters
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
opening
(image, selem=None, out=None)¶ 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 crossshaped 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 cupy as cp >>> from cucim.skimage.morphology import square >>> bad_connection = cp.asarray([[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=cp.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)

cucim.skimage.morphology.
reconstruction
(seed, mask, method='dilation', selem=None, offset=None)¶ Perform a morphological reconstruction of an image.
Morphological reconstruction by dilation is similar to basic morphological dilation: highintensity values will replace nearby lowintensity 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 highintensity values. Reconstruction by erosion is simply the inverse: lowintensity 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 lessthanorequalto 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 nD array of 1’s and 0’s. Default is the nD 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]. Applications for greyscale reconstruction are discussed in [2] and [3].
References
 1
Robinson, “Efficient morphological reconstruction: a downhill filter”, Pattern Recognition Letters 25 (2004) 17591767.
 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, minintensity 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 hdome of the image and leaves features of height h in the subtracted image.

cucim.skimage.morphology.
rectangle
(nrows, ncols, dtype=<class 'numpy.uint8'>)¶ Generates a flat, rectangularshaped 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
 dtypedatatype
The data type of the structuring element.
Notes
The use of
width
andheight
has been deprecated in scikitimage 0.18.0. Usenrows
andncols
instead.

cucim.skimage.morphology.
remove_small_holes
(ar, area_threshold=64, connectivity=1, in_place=False)¶ 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 alreadylabeled 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
>>> import cupy as cp >>> from cucim.skimage import morphology >>> a = cp.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

cucim.skimage.morphology.
remove_small_objects
(ar, min_size=64, connectivity=1, in_place=False)¶ 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 0and1 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 nonnegative.
 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
>>> import cupy as cp >>> from cucim.skimage import morphology >>> a = cp.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

cucim.skimage.morphology.
square
(width, dtype=<class 'numpy.uint8'>)¶ Generates a flat, squareshaped 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
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
star
(a, dtype=<class 'numpy.uint8'>)¶ 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
 dtypedatatype
The data type of the structuring element.

cucim.skimage.morphology.
white_tophat
(image, selem=None, out=None)¶ 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 crossshaped 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
References
Examples
>>> # Subtract grey background from bright peak >>> import cupy as cp >>> from cucim.skimage.morphology import square >>> bright_on_grey = cp.asarray([[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=cp.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)
registration¶

cucim.skimage.registration.
optical_flow_ilk
(reference_image, moving_image, *, radius=7, num_warp=10, gaussian=False, prefilter=False, dtype=<class 'numpy.float32'>)¶ Coarse to fine optical flow estimator.
The iterative LucasKanade (iLK) solver is applied at each level of the image pyramid. iLK [1] is a fast and robust alternative to TVL1 algorithm although less accurate for rendering flat surfaces and object boundaries (see [2]).
 Parameters
 reference_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].
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. I137). IEEE. DOI:10.1109/ICIP.2005.1529706
 2
Plyer, A., Le Besnerais, G., & Champagnat, F. (2016). Massively parallel Lucas Kanade optical flow for realtime video processing applications. Journal of RealTime Image Processing, 11(4), 713730. DOI:10.1007/s1155401404230

cucim.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'>)¶ Coarse to fine optical flow estimator.
The TVL1 solver is applied at each level of the image pyramid. TVL1 is a popular algorithm for optical flow estimation introduced by Zack et al. [1], improved in [2] and detailed in [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]). The smaller this parameter is, the smoother the returned result will be.
 tightnessfloat, optional
Tightness parameter (\(\tau\) in [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 TVL 1 optical flow. In Joint pattern recognition symposium (pp. 214223). Springer, Berlin, Heidelberg. DOI:10.1007/9783540749363_22
 2
Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, D. (2009). An improved algorithm for TVL 1 optical flow. In Statistical and geometrical approaches to visual motion analysis (pp. 2345). Springer, Berlin, Heidelberg. DOI:10.1007/9783642030611_2
 3
Pérez, J. S., MeinhardtLlopis, E., & Facciolo, G. (2013). TVL1 optical flow estimation. Image Processing On Line, 2013, 137150. DOI:10.5201/ipol.2013.26
Examples
>>> import cupy as cp >>> from cucim.skimage.color import rgb2gray >>> from skimage.data import stereo_motorcycle >>> from cucim.skimage.registration import optical_flow_tvl1 >>> image0, image1, disp = [cp.array(a) for a in stereo_motorcycle()] >>> #  Convert the images to gray level: color is not supported. >>> image0 = rgb2gray(image0) >>> image1 = rgb2gray(image1) >>> flow = optical_flow_tvl1(image1, image0)

cucim.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)¶ Efficient subpixel image translation registration by crosscorrelation.
This code gives the same precision as the FFT upsampled crosscorrelation in a fraction of the computation time and with reduced memory requirements. It obtains an initial estimate of the crosscorrelation 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 matrixmultiply 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 exampleupsample_factor == 20
means the images will be registered within 1/20th of a pixel. Default is 1 (no upsampling). Not used if any ofreference_mask
ormoving_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
ormoving_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
ormoving_mask
is not None. In this case only shifts is returned. reference_maskndarray
Boolean mask for
reference_image
. The mask should evaluate toTrue
(or 1) on valid pixels.reference_mask
should have the same shape asreference_image
. moving_maskndarray or None, optional
Boolean mask for
moving_image
. The mask should evaluate toTrue
(or 1) on valid pixels.moving_mask
should have the same shape asmoving_image
. IfNone
,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
ormoving_mask
is None.
 Returns
 shiftsndarray
Shift vector (in pixels) required to register
moving_image
withreference_image
. Axis ordering is consistent with numpy (e.g. Z, Y, X) errorfloat
Translation invariant normalized RMS error between
reference_image
andmoving_image
. phasedifffloat
Global phase difference between the two images (should be zero if images are nonnegative).
References
 1
Manuel GuizarSicairos, Samuel T. Thurman, and James R. Fienup, “Efficient subpixel image registration algorithms,” Optics Letters 33, 156158 (2008). DOI:10.1364/OL.33.000156
 2
James R. Fienup, “Invariant error metrics for image reconstruction” Optics Letters 36, 83528357 (1997). DOI:10.1364/AO.36.008352
 3
Dirk Padfield. Masked Object Registration in the Fourier Domain. IEEE Transactions on Image Processing, vol. 21(5), pp. 27062718 (2012). DOI:10.1109/TIP.2011.2181402
 4
D. Padfield. “Masked FFT registration”. In Proc. Computer Vision and Pattern Recognition, pp. 29182925 (2010). DOI:10.1109/CVPR.2010.5540032
restoration¶

cucim.skimage.restoration.
calibrate_denoiser
(image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True, extra_output=False)¶ Calibrate a denoising function and return optimal Jinvariant 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 Jinvariance.
 approximate_lossbool, optional
Whether to approximate the selfsupervised 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 Jinvariant 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 Selfsupervised loss for each set of parameters in parameters_tested.
Notes
The calibration procedure uses a selfsupervised meansquareerror loss to evaluate the performance of Jinvariant versions of denoise_function. The minimizer of the selfsupervised loss is also the minimizer of the groundtruth 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 SelfSupervision, International Conference on Machine Learning, p. 524533 (2019).
Examples
>>> import cupy as cp >>> from cucim.skimage import color >>> from skimage import data >>> from cucim.skimage.restoration import (denoise_tv_chambolle, ... calibrate_denoiser) >>> img = color.rgb2gray(cp.array(data.astronaut()[:50, :50])) >>> noisy = img + 0.5 * img.std() * cp.random.randn(*img.shape) >>> parameters = {'weight': cp.arange(0.01, 0.5, 0.05)} >>> denoising_function = calibrate_denoiser(noisy, denoise_tv_chambolle, ... denoise_parameters=parameters) >>> denoised_img = denoising_function(img)

cucim.skimage.restoration.
denoise_tv_chambolle
(image, weight=0.1, eps=0.0002, n_iter_max=200, multichannel=False)¶ Perform totalvariation denoising on ndimensional 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_(n1)  E_n) < eps * E_0
 n_iter_maxint, optional
Maximal number of iterations used for the optimization.
 multichannelbool, optional
Apply totalvariation 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 “cartoonlike” images, that is, piecewiseconstant images.
This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [1].
References
 1
A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 8997.
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(np.float) >>> mask += 0.2*np.random.randn(*mask.shape) >>> res = denoise_tv_chambolle(mask, weight=100)

cucim.skimage.restoration.
richardson_lucy
(image, psf, iterations=50, clip=True, filter_epsilon=None)¶ RichardsonLucy 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
Examples
>>> import cupy as cp >>> from cucim.skimage import img_as_float, restoration >>> from skimage import data >>> camera = cp.asarray(img_as_float(data.camera())) >>> from cupyx.scipy.signal import convolve2d >>> psf = cp.ones((5, 5)) / 25 >>> camera = convolve2d(camera, psf, 'same') >>> camera += 0.1 * camera.std() * cp.random.standard_normal(camera.shape) >>> deconvolved = restoration.richardson_lucy(camera, psf, 5)

cucim.skimage.restoration.
unsupervised_wiener
(image, psf, reg=None, user_params=None, is_real=True, clip=True)¶ Unsupervised WienerHunt deconvolution.
Return the deconvolution with a WienerHunt 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 (
cupy.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
andprior
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). 1e4 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, JeanFrançois Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for WienerHunt deconvolution”, J. Opt. Soc. Am. A 27, 15931607 (2010)
https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa2771593
Examples
>>> import cupy as cp >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = cp.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * cp.random.standard_normal(img.shape) >>> deconvolved_img = restoration.unsupervised_wiener(img, psf)

cucim.skimage.restoration.
wiener
(image, psf, balance, reg=None, is_real=True, clip=True)¶ WienerHunt deconvolution
Return the deconvolution with a WienerHunt 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 datatype is real, or the transfer function (Fourier space) if the datatype 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 cupy.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
andreg
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 ifpsf
and/orreg
are provided as transfer function. For the hermitian property seeuft
module orcupy.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 highfrequency 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, JeanFrançois Giovannelli, and Thomas Rodet, “Bayesian estimation of regularization and point spread function parameters for WienerHunt deconvolution”, J. Opt. Soc. Am. A 27, 15931607 (2010)
https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa2771593
 2
B. R. Hunt “A matrix theory proof of the discrete convolution theorem”, IEEE Trans. on Audio and Electroacoustics, vol. au19, no. 4, pp. 285288, dec. 1971
Examples
>>> import cupy as cp >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = cp.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * cp.random.standard_normal(img.shape) >>> deconvolved_img = restoration.wiener(img, psf, 1100)
segmentation¶

cucim.skimage.segmentation.
checkerboard_level_set
(image_shape, square_size=5)¶ 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

cucim.skimage.segmentation.
circle_level_set
(image_shape, center=None, radius=None)¶ 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 scikitimage 0.19. Please use the function named
disk_level_set
instead.
See also

cucim.skimage.segmentation.
disk_level_set
(image_shape, *, center=None, radius=None)¶ 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

cucim.skimage.segmentation.
find_boundaries
(label_img, connectivity=1, mode='thick', background=0)¶ 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 to2 * label_img.shape[i]  1
for alli
(a pixel is inserted in between all other pairs of pixels).
Examples
>>> labels = cp.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=cp.uint8) >>> find_boundaries(labels, mode='thick').astype(cp.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(cp.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(cp.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(cp.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 = cp.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=cp.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]])

cucim.skimage.segmentation.
inverse_gaussian_gradient
(image, alpha=100.0, sigma=5.0)¶ Inverse of gradient magnitude.
Compute the magnitude of the gradients in the image and then inverts the result in the range [0, 1]. Flat areas are assigned values close to 1, while areas close to borders are assigned values close to 0.
This function or a similar one defined by the user should be applied over the image as a preprocessing step before calling morphological_geodesic_active_contour.
 Parameters
 image(M, N) or (L, M, N) array
Grayscale image or volume.
 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.

cucim.skimage.segmentation.
join_segmentations
(s1, s2)¶ 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
>>> import cupy as cp >>> from cucim.skimage.segmentation import join_segmentations >>> s1 = cp.array([[0, 0, 1, 1], ... [0, 2, 1, 1], ... [2, 2, 2, 1]]) >>> s2 = cp.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]])

cucim.skimage.segmentation.
mark_boundaries
(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0, *, order=3)¶ 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.
 colorlength3 sequence, optional
RGB color of boundaries in the output image.
 outline_colorlength3 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
andouter
).
 Returns
 marked(M, N, 3) array of float
An image in which the boundaries between labels are superimposed on the original image.
See also

cucim.skimage.segmentation.
morphological_chan_vese
(image, iterations, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=<function <lambda>>)¶ 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 and 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 14. 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
Notes
This is a version of the ChanVese 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 ChanVese PDE (see [1]). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (it is not necessary to find the right time step for the evolution), and are computationally faster.
The algorithm and its theoretical derivation are described in [1].
References
 1(1,2)
A Morphological Approach to Curvaturebased Evolution of Curves and Surfaces, Pablo MárquezNeila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, DOI:10.1109/TPAMI.2013.106

cucim.skimage.segmentation.
morphological_geodesic_active_contour
(gimage, iterations, init_level_set='circle', smoothing=1, threshold='auto', balloon=0, iter_callback=<function <lambda>>)¶ 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 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 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 and 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 14. 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 noninformative 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)
Notes
This is a version of the Geodesic Active Contours (GAC) algorithm that uses morphological operators instead of solving partial differential equations (PDEs) for the evolution of the contour. The set of morphological operators used in this algorithm are proved to be infinitesimally equivalent to the GAC PDEs (see [1]). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (e.g., it is not necessary to find the right time step for the evolution), and are computationally faster.
The algorithm and its theoretical derivation are described in [1].
References
 1(1,2)
A Morphological Approach to Curvaturebased Evolution of Curves and Surfaces, Pablo MárquezNeila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, DOI:10.1109/TPAMI.2013.106

cucim.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)¶ Random walker algorithm for segmentation from markers.
Random walker algorithm is implemented for graylevel or multichannel images.
 Parameters
 dataarray_like
Image to be segmented in phases. Graylevel data can be two or threedimensional; 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. Zerolabeled 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 memoryintensive for large images (e.g., 3D volumes).
‘cg’ (conjugate gradient): the linear system is solved iteratively using the Conjugate Gradient method from scipy.sparse.linalg. This is less memoryconsuming 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
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].
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):176883. DOI:10.1109/TPAMI.2006.233.
Examples
>>> import cupy as cp >>> cp.random.seed(0) >>> a = cp.zeros((10, 10)) + 0.2 * cp.random.rand(10, 10) >>> a[5:8, 5:8] += 1 >>> b = cp.zeros_like(a, dtype=cp.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)

cucim.skimage.segmentation.
relabel_sequential
(label_field, offset=1)¶ Relabel arbitrary labels to {offset, … offset + number_of_labels}.
This function also returns the forward map (mapping the original labels to the reduced labels) and the inverse map (mapping the reduced labels back to the original ones).
 Parameters
 label_fieldnumpy array of int, arbitrary shape
An array of labels, which must be nonnegative 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 reapply 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 thanlabel_field.size
, and in these cases the forward map is guaranteed to be smaller than either the input or output images.Examples
>>> import cupy as cp >>> from cucim.skimage.segmentation import relabel_sequential >>> label_field = cp.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 >>> cp.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]) >>> cp.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])
transform¶

class
cucim.skimage.transform.
AffineTransform
(matrix=None, scale=None, rotation=None, shear=None, translation=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ 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
andsy
are scale factors in the x and y directions, and the homogeneous transformation matrix is:[[a0 a1 a2] [b0 b1 b2] [0 0 1]]
In 2D, the transformation parameters can be given as the homogeneous transformation matrix, above, or as the implicit parameters, scale, rotation, shear, and translation in x (a2) and y (b2). For 3D and higher, only the matrix form is allowed.
In narrower transforms, such as the Euclidean (only rotation and translation) or Similarity (rotation, translation, and a global scale factor) transforms, it is possible to specify 3D transforms using implicit parameters also.
 Parameters
 matrix(D+1, D+1) array, optional
Homogeneous transformation matrix. If this matrix is provided, it is an error to provide any of scale, rotation, shear, or translation.
 scale{s as float or (sx, sy) as array, list or tuple}, optional
Scale factor(s). If a single value, it will be assigned to both sx and sy. Only available for 2D.
New in version 0.17: Added support for supplying a single scalar value.
 rotationfloat, optional
Rotation angle in counterclockwise direction as radians. Only available for 2D.
 shearfloat, optional
Shear angle in counterclockwise direction as radians. Only available for 2D.
 translation(tx, ty) as array, list or tuple, optional
Translation parameters. Only available for 2D.
 dimensionalityint, optional
The dimensionality of the transform. This is not used if any other parameters are provided.
 Raises
 ValueError
If both
matrix
and any of the other parameters are provided.
 Attributes
 params(D+1, D+1) array
Homogeneous transformation matrix.

property
rotation
¶

property
scale
¶

property
shear
¶

property
translation
¶

class
cucim.skimage.transform.
EssentialMatrixTransform
(rotation=None, translation=None, matrix=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ 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 nonplanar scene. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images (ProjectiveTransform). If the intrinsic calibration of the images is unknown, the fundamental matrix describes the projective relation between the two images (FundamentalMatrixTransform).
 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.
Methods
estimate
(src, dst)Estimate essential matrix using 8point algorithm.

estimate
(src, dst)¶ Estimate essential matrix using 8point algorithm.
The 8point algorithm requires at least 8 corresponding point pairs for a wellconditioned solution, otherwise the overdetermined solution is estimated.
 Parameters
 src(N, 2) array
Source coordinates.
 dst(N, 2) array
Destination coordinates.
 Returns
 successbool
True, if model estimation succeeds.

class
cucim.skimage.transform.
EuclideanTransform
(matrix=None, rotation=None, translation=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ Euclidean transformation, also known as a rigid transform.
Has the following form:
X = a0 * x  b0 * y + a1 = = x * cos(rotation)  y * sin(rotation) + a1 Y = b0 * x + a0 * y + b1 = = x * sin(rotation) + y * cos(rotation) + b1
where the homogeneous transformation matrix is:
[[a0 b0 a1] [b0 a0 b1] [0 0 1]]
The Euclidean transformation is a rigid transformation with rotation and translation parameters. The similarity transformation extends the Euclidean transformation with a single scaling factor.
 Parameters
 matrix(D+1, D+1) array, optional
Homogeneous transformation matrix.
 rotationfloat or sequence of float, optional
Rotation angle in counterclockwise direction as radians. If given as a vector, it is interpreted as Euler rotation angles [1]. Only 2D (single rotation) and 3D (Euler rotations) values are supported. For higher dimensions, you must provide or estimate the transformation matrix.
 translationsequence of float, length D, optional
Translation parameters for each axis.
 dimensionalityint, optional
The dimensionality of the transform.
References
 Attributes
 params(D+1, D+1) array
Homogeneous transformation matrix.
Methods
estimate
(src, dst)Estimate the transformation from a set of corresponding points.

estimate
(src, dst)¶ Estimate the transformation from a set of corresponding points.
You can determine the over, well and underdetermined parameters with the total leastsquares method.
Number of source and destination coordinates must match.
 Parameters
 src(N, D) array
Source coordinates.
 dst(N, D) array
Destination coordinates.
 Returns
 successbool
True, if model estimation succeeds.

property
rotation
¶

property
translation
¶

class
cucim.skimage.transform.
FundamentalMatrixTransform
(matrix=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ Fundamental matrix transformation.
The fundamental matrix relates corresponding points between a pair of uncalibrated images. The matrix transforms homogeneous image points in one image to epipolar lines in the other image.
The fundamental matrix is only defined for a pair of moving images. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images (ProjectiveTransform). If the intrinsic calibration of the images is known, the essential matrix describes the metric relation between the two images (EssentialMatrixTransform).
 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.
Methods
__call__
(coords)Apply forward transformation.
estimate
(src, dst)Estimate fundamental matrix using 8point algorithm.
inverse
(coords)Apply inverse transformation.
residuals
(src, dst)Compute the Sampson distance.

estimate
(src, dst)¶ Estimate fundamental matrix using 8point algorithm.
The 8point algorithm requires at least 8 corresponding point pairs for a wellconditioned solution, otherwise the overdetermined 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)¶ Apply inverse transformation.
 Parameters
 coords(N, 2) array
Destination coordinates.
 Returns
 coords(N, 3) array
Epipolar lines in the source image.

residuals
(src, dst)¶ Compute the Sampson distance.
The Sampson distance is the first approximation to the geometric error.
 Parameters
 src(N, 2) array
Source coordinates.
 dst(N, 2) array
Destination coordinates.
 Returns
 residuals(N, ) array
Sampson distance.

class
cucim.skimage.transform.
PiecewiseAffineTransform
¶ 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.
Methods
__call__
(coords)Apply forward transformation.
estimate
(src, dst)Estimate the transformation from a set of corresponding points.
inverse
(coords)Apply inverse transformation.

estimate
(src, dst)¶ Estimate the transformation from a set of corresponding points.
Number of source and destination coordinates must match.
 Parameters
 src(N, D) array
Source coordinates.
 dst(N, D) array
Destination coordinates.
 Returns
 successbool
True, if model estimation succeeds.

inverse
(coords)¶ Apply inverse transformation.
Coordinates outside of the mesh will be set to  1.
 Parameters
 coords(N, D) array
Source coordinates.
 Returns
 coords(N, D) array
Transformed coordinates.

class
cucim.skimage.transform.
PolynomialTransform
(params=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ 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, :].
Methods
__call__
(coords)Apply forward transformation.
estimate
(src, dst[, order])Estimate the transformation from a set of corresponding points.
inverse
(coords)Apply inverse transformation.

estimate
(src, dst, order=2)¶ Estimate the transformation from a set of corresponding points.
You can determine the over, well and underdetermined parameters with the total leastsquares 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 leastsquares 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)¶ Apply inverse transformation.
 Parameters
 coords(N, 2) array
Destination coordinates.
 Returns
 coords(N, 2) array
Source coordinates.

class
cucim.skimage.transform.
ProjectiveTransform
(matrix=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ 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(D+1, D+1) array, optional
Homogeneous transformation matrix.
 dimensionalityint, optional
The number of dimensions of the transform. This is ignored if
matrix
is not None.
 Attributes
 params(D+1, D+1) array
Homogeneous transformation matrix.
Methods
__call__
(coords)Apply forward transformation.
estimate
(src, dst)Estimate the transformation from a set of corresponding points.
inverse
(coords)Apply inverse transformation.

property
dimensionality
¶ The dimensionality of the transformation.

estimate
(src, dst)¶ Estimate the transformation from a set of corresponding points.
You can determine the over, well and underdetermined parameters with the total leastsquares 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 leastsquares 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)¶ Apply inverse transformation.
 Parameters
 coords(N, D) array
Destination coordinates.
 Returns
 coords_out(N, D) array
Source coordinates.

class
cucim.skimage.transform.
SimilarityTransform
(matrix=None, scale=None, rotation=None, translation=None, *, dimensionality=2, xp=<module 'cupy' from '/opt/conda/envs/cucim/lib/python3.8/sitepackages/cupy/__init__.py'>)¶ 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(dim+1, dim+1) array, optional
Homogeneous transformation matrix.
 scalefloat, optional
Scale factor. Implemented only for 2D and 3D.
 rotationfloat, optional
Rotation angle in counterclockwise direction as radians. Implemented only for 2D and 3D. For 3D, this is given in XZX Euler angles.
 translation(dim,) arraylike, optional
x, y[, z] translation parameters. Implemented only for 2D and 3D.
 Attributes
 params(dim+1, dim+1) array
Homogeneous transformation matrix.
Methods
estimate
(src, dst)Estimate the transformation from a set of corresponding points.

estimate
(src, dst)¶ Estimate the transformation from a set of corresponding points.
You can determine the over, well and underdetermined parameters with the total leastsquares 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
¶

cucim.skimage.transform.
downscale_local_mean
(image, factors, cval=0, clip=True)¶ Downsample Ndimensional image by local averaging.
The image is padded with cval if it is not perfectly divisible by the integer factors.
In contrast to interpolation in skimage.transform.resize and skimage.transform.rescale this function calculates the local mean of elements in each block of size factors in the input image.
 Parameters
 imagendarray
Ndimensional input image.
 factorsarray_like
Array containing downsampling 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
Downsampled image with same number of dimensions as input image. For integer inputs, the output dtype will be
float64
. Seenumpy.mean()
for details.
Examples
>>> import cupy as cp >>> a = cp.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]])

cucim.skimage.transform.
estimate_transform
(ttype, src, dst, **kwargs)¶ Estimate 2D geometric transformation parameters.
You can determine the over, well and underdetermined parameters with the total leastsquares method.
Number of source and destination coordinates must match.
 Parameters
 ttype{‘euclidean’, similarity’, ‘affine’, ‘piecewiseaffine’, ‘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` 'piecewiseaffine' `src, `dst` 'projective' `src, `dst` 'polynomial' `src, `dst`, `order` (polynomial order, default order is 2)
Also see examples below.
 Returns
 tform
GeometricTransform
Transform object containing the transformation parameters and providing access to forward and inverse transformation functions.
 tform
Examples
>>> import cupy as cp >>> from cucim.skimage import transform
>>> # estimate transformation parameters >>> src = cp.array([0, 0, 10, 10]).reshape((2, 2)) >>> dst = cp.array([12, 14, 1, 20]).reshape((2, 2))
>>> tform = transform.estimate_transform('similarity', src, dst)
>>> cp.allclose(tform.inverse(tform(src)), src) True
>>> # warp image using the estimated transformation >>> from skimage import data >>> image = cp.array(data.camera())
>>> transform.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 >>> cp.allclose(tform3(src), tform2(tform(src))) True

cucim.skimage.transform.
integral_image
(image)¶ 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, “Summedarea tables for texture mapping,” ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207212.

cucim.skimage.transform.
integrate
(ii, start, end)¶ 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=np.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.])

cucim.skimage.transform.
matrix_transform
(coords, matrix)¶ 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.

cucim.skimage.transform.
pyramid_expand
(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)¶ 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 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://scikitimage.org/docs/dev/user_guide/data_types.html
 Returns
 outarray
Upsampled and smoothed float image.
References

cucim.skimage.transform.
pyramid_gaussian
(image, max_layer= 1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)¶ Yield images of the Gaussian pyramid formed by the input image.
Recursively applies the pyramid_reduce function to the image, and yields the downscaled images.
Note that the first image of the pyramid will be the original, unscaled image. The total number of images is max_layer + 1. In case all layers are computed, the last image is either a onepixel 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 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://scikitimage.org/docs/dev/user_guide/data_types.html
 Returns
 pyramidgenerator
Generator yielding pyramid layers as float images.
References

cucim.skimage.transform.
pyramid_laplacian
(image, max_layer= 1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)¶ 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 onepixel 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 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://scikitimage.org/docs/dev/user_guide/data_types.html
 Returns
 pyramidgenerator
Generator yielding pyramid layers as float images.
References

cucim.skimage.transform.
pyramid_reduce
(image, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)¶ 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 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://scikitimage.org/docs/dev/user_guide/data_types.html
 Returns
 outarray
Smoothed and downsampled float image.
References

cucim.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)¶ Scale image by a certain factor.
Performs interpolation to upscale or downscale Ndimensional images. Note that antialiasing should be enabled when downsizing images to avoid aliasing artifacts. For downsampling with an integer factor also see 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 05. See skimage.transform.warp for detail.
 mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’}, optional
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
 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://scikitimage.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 downscaling. It is crucial to filter when downsampling the image to avoid aliasing artifacts. If input image data type is bool, no antialiasing 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 downscaling 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 cucim.skimage.transform import rescale >>> image = cp.array(data.camera()) >>> rescale(image, 0.1).shape (51, 51) >>> rescale(image, 0.5).shape (256, 256)

cucim.skimage.transform.
resize
(image, output_shape, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None)¶ Resize image to match a certain size.
Performs interpolation to upsize or downsize Ndimensional images. Note that antialiasing should be enabled when downsizing images to avoid aliasing artifacts. For downsampling with an integer factor also see 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 ndimensional 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 05. See skimage.transform.warp for detail.
 mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’}, optional
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
 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://scikitimage.org/docs/dev/user_guide/data_types.html
 anti_aliasingbool, optional
Whether to apply a Gaussian filter to smooth the image prior to downscaling. It is crucial to filter when downsampling the image to avoid aliasing artifacts. If input image data type is bool, no antialiasing 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 downscaling factor, where s > 1. For the upsize case, s < 1, no antialiasing 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 cucim.skimage.transform import resize >>> image = cp.array(data.camera()) >>> resize(image, (100, 100)).shape (100, 100)

cucim.skimage.transform.
rotate
(image, angle, resize=False, center=None, order=None, mode='constant', cval=0, clip=True, preserve_range=False)¶ Rotate image by a certain angle around its center.
 Parameters
 imagendarray
Input image.
 anglefloat
Rotation angle in degrees in counterclockwise 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 05. See skimage.transform.warp for detail.
 mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’}, optional
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
 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://scikitimage.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 cucim.skimage.transform import rotate >>> image = cp.array(data.camera()) >>> rotate(image, 2).shape (512, 512) >>> rotate(image, 2, resize=True).shape (530, 530) >>> rotate(image, 90, resize=True).shape (512, 512)

cucim.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)¶ 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 05. See skimage.transform.warp for detail.
 mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’}, optional
Points outside the boundaries of the input are filled according to the given mode, with ‘constant’ used as the default. Modes match the behaviour of numpy.pad.
 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://scikitimage.org/docs/dev/user_guide/data_types.html

cucim.skimage.transform.
warp
(image, inverse_map, map_args={}, output_shape=None, order=None, mode='constant', cval=0.0, clip=True, preserve_range=False)¶ Warp an image according to a given coordinate transformation.
 Parameters
 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 2D image can have 2 dimensions for grayscale images, or 3 dimensions with color information.
For 2D images, you can directly pass a transformation object, e.g. skimage.transform.SimilarityTransform, or its inverse.
For 2D images, you can pass a
(3, 3)
homogeneous transformation matrix, e.g. skimage.transform.SimilarityTransform.params.For 2D 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 ND 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 2D images, you need to pass an array of shape
(2, rows, cols)
, where rows and cols determine the shape of the output image, and the first dimension contains the(row, col)
coordinate in the input image. See scipy.ndimage.map_coordinates for further documentation.
Note, that a
(3, 3)
matrix is interpreted as a homogeneous transformation matrix, so you cannot interpolate values from a 3D 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 multiband images, only rows and columns need to be specified.
 orderint, optional
 The order of interpolation. The order has to be in the range 05:
0: Nearestneighbor
1: Bilinear (default)
2: Biquadratic
3: Bicubic
4: Biquartic
5: Biquintic
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.
 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://scikitimage.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, AffineTransform and ProjectiveTransform and order in [0, 3] this function uses the underlying transformation matrix to warp the image with a much faster routine.
Examples
>>> from cucim.skimage.transform import warp >>> from skimage import data >>> image = cp.array(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 cucim.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):
>>> import cupy as cp >>> matrix = cp.asarray([[1, 0, 0], [0, 1, 10], [0, 0, 1]]) >>> warped = warp(image, matrix) >>> from cucim.skimage.transform import ProjectiveTransform, warp >>> warped = warp(image, ProjectiveTransform(matrix=matrix))
You can also use the inverse of a geometric transformation (fast):
>>> warped = warp(image, tform.inverse)
For ND 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 3D cube, you can do:
>>> cube_shape = (30, 30, 30) >>> cube = cp.random.rand(*cube_shape)
Setup the coordinate array, that defines the scaling:
>>> scale = 0.1 >>> output_shape = tuple(int(scale * s) for s in cube_shape) >>> coords0, coords1, coords2 = cp.mgrid[:output_shape[0], ... :output_shape[1], :output_shape[2]] >>> coords = cp.asarray([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)

cucim.skimage.transform.
warp_coords
(coord_map, shape, dtype=<class 'numpy.float64'>)¶ Build the source coordinates for the output of a 2D 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, 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 lowerlevel routine that produces the source coordinates for 2D images used by warp().
It is provided separately from warp to give additional flexibility to users who would like, for example, to reuse a particular coordinate mapping, to use specific dtypes at various points along the the imagewarping process, or to implement different postprocessing logic than warp performs after the call to ndi.map_coordinates.
Examples
Produce a coordinate map that shifts an image up and to the right:
>>> import cupy as cp >>> from cucim.skimage.transform import warp_coords >>> from skimage import data >>> from cupyx.scipy.ndimage import map_coordinates >>> >>> def shift_up10_left20(xy): ... return xy  cp.array([20, 10])[None, :] >>> >>> image = cp.array(data.astronaut().astype(cp.float32)) >>> coords = warp_coords(shift_up10_left20, image.shape) >>> warped_image = map_coordinates(image, coords)

cucim.skimage.transform.
warp_polar
(image, center=None, *, radius=None, output_shape=None, scaling='linear', multichannel=False, **kwargs)¶ Remap image to polar or logpolar coordinates space.
 Parameters
 imagendarray
Input image. Only 2D arrays are accepted by default. If multichannel=True, 3D 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 logpolar. Defaults to ‘linear’.
 multichannelbool, optional
Whether the image is a 3D array in which the third axis is to be interpreted as multiple channels. If set to False (default), only 2D arrays are accepted.
 **kwargskeyword arguments
Passed to transform.warp.
 Returns
 warpedndarray
The polar or logpolar warped image.
Examples
Perform a basic polar warp on a grayscale image:
>>> from skimage import data >>> from cucim.skimage.transform import warp_polar >>> image = cp.array(data.checkerboard()) >>> warped = warp_polar(image)
Perform a logpolar warp on a grayscale image:
>>> warped = warp_polar(image, scaling='log')
Perform a logpolar 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 logpolar warp on a color image:
>>> image = data.astronaut() >>> warped = warp_polar(image, scaling='log', multichannel=True)
util¶

cucim.skimage.util.
crop
(ar, crop_width, copy=False, order='K')¶ Crop array ar by crop_width along each dimension.
 Parameters
 ararraylike 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,)
orn
for integern
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. Seenp.copy
.
 Returns
 croppedarray
The cropped array. If
copy=False
(default), this is a sliced view of the input array.

cucim.skimage.util.
dtype_limits
(image, clip_negative=False)¶ 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.

cucim.skimage.util.
img_as_bool
(image, force_copy=False)¶ 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.

cucim.skimage.util.
img_as_float
(image, force_copy=False)¶ Convert an image to floating point format.
This function is similar to img_as_float64, but will not convert lowerprecision 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].

cucim.skimage.util.
img_as_float32
(image, force_copy=False)¶ Convert an image to singleprecision (32bit) 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].

cucim.skimage.util.
img_as_float64
(image, force_copy=False)¶ Convert an image to doubleprecision (64bit) 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].

cucim.skimage.util.
img_as_int
(image, force_copy=False)¶ Convert an image to 16bit 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 datatype is positiveonly (e.g., uint8), then the output image will still only have positive values.

cucim.skimage.util.
img_as_ubyte
(image, force_copy=False)¶ Convert an image to 8bit 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.

cucim.skimage.util.
img_as_uint
(image, force_copy=False)¶ Convert an image to 16bit 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.

cucim.skimage.util.
invert
(image, signed_float=False)¶ Invert an image.
Invert the intensity range of the input image, so that the dtype maximum is now the dtype minimum, and viceversa. 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
>>> import cupy as cp >>> img = cp.asarray([[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 = cp.asarray([[ 2, 0, 128], ... [127, 0, 5]], np.int8) >>> invert(img2) array([[ 1, 1, 127], [128, 1, 6]], dtype=int8) >>> img3 = cp.asarray([[ 0., 1., 0.5, 0.75]]) >>> invert(img3) array([[1. , 0. , 0.5 , 0.25]]) >>> img4 = cp.asarray([[ 0., 1., 1., 0.25]]) >>> invert(img4, signed_float=True) array([[0. , 1. , 1. , 0.25]])

cucim.skimage.util.
map_array
(input_arr, input_vals, output_vals, out=None)¶ 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.

cucim.skimage.util.
random_noise
(image, mode='gaussian', seed=None, clip=True, **kwargs)¶ Function to add random noise of various types to a floatingpoint 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’ Gaussiandistributed additive noise.
 ‘localvar’ Gaussiandistributed additive noise, with specified
local variance at each point of image.
‘poisson’ Poissondistributed 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 pseudorandom 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 floatingpoint 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 floatingpoint 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 floatingpoint result, after which it is scaled back down to the floatingpoint 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.

cucim.skimage.util.
view_as_blocks
(arr_in, block_shape)¶ Block view of the input ndimensional array (using restriding).
Blocks are nonoverlapping views of the input array.
 Parameters
 arr_inndarray
Nd 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. If arr_in is noncontiguous, a copy is made.
Examples
>>> import cupy as cp >>> from cucim.skimage.util.shape import view_as_blocks >>> A = cp.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 = cp.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]]]])

cucim.skimage.util.
view_as_windows
(arr_in, window_shape, step=1)¶ Rolling window view of the input ndimensional 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
Nd input array.
 window_shapeinteger or tuple of length arr_in.ndim
Defines the shape of the elementary ndimensional orthotope (better know as hyperrectangle [1]) of the rolling window view. If an integer is given, the shape will be a hypercube of sidelength given by its value.
 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 2dimensional 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*(1003+1)**3*3**3 which is about 203 MB! The scaling becomes even worse as the dimension of the input array becomes larger.References
Examples
>>> import cupy as cp >>> from cucim.skimage.util.shape import view_as_windows >>> A = cp.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 = cp.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 = cp.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]]]])
Submodule Contents¶
skimage¶
GPU Image Processing for Python
This module is a CuPy based implementation of a subset of scikitimage.
It is a collection of algorithms for image processing and computer vision.
The main package 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.
 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.
 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.
Utility Functions¶
 img_as_float
Convert an image to floating point format, with values in [0, 1]. Is similar to img_as_float64, but will not convert lowerprecision floating point arrays to float64.
 img_as_float32
Convert an image to singleprecision (32bit) floating point format, with values in [0, 1].
 img_as_float64
Convert an image to doubleprecision (64bit) 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.