class skimage.transform.EuclideanTransform(matrix=None, rotation=None, translation=None) [source]

Bases: skimage.transform._geometric.ProjectiveTransform 2D Euclidean transformation. Has the following form: X = a0 * x - b0 * y + a1 =
  = x * cos(rotation) - y * sin(rotation) + a1

Y = b0 * x + a0 * y + b1 =
  = x * sin(rotation) + y * cos(rotation) + b1
 where the homogeneous transformation matrix is: [[a0  b0  a1]
 [b0  a0  b1]
 [0   0    1]]
 The Euclidean transformation is a rigid transformation with rotation and translation parameters. The similarity transformation extends the Euclidean transformation with a single scaling factor.  Parameters

matrix(3, 3) array, optional

Homogeneous transformation matrix.
rotationfloat, optional

Rotation angle in counter-clockwise direction as radians.
translation(tx, ty) as array, list or tuple, optional

x, y translation parameters.    Attributes

params(3, 3) array

Homogeneous transformation matrix.
__init__(matrix=None, rotation=None, translation=None) [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.

property rotation

property translation


estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.


__init__(matrix=None, rotation=None, translation=None) [source]

Initialize self. See help(type(self)) for accurate signature.


skimage.transform.frt2(a) [source]

Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array.  Parameters

aarray_like

A 2-D square n x n integer array.    Returns

FRT2-D ndarray

Finite Radon Transform array of (n+1) x n integer coefficients.      See also
ifrt2

The two-dimensional inverse FRT.    Notes The FRT has a unique inverse if and only if n is prime. [FRT] The idea for this algorithm is due to Vlad Negnevitski. References
FRT
A. Kingston and I. Svalbe, “Projective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006)   Examples Generate a test image: Use a prime number for the array dimensions >>> SIZE = 59
>>> img = np.tri(SIZE, dtype=np.int32)
 Apply the Finite Radon Transform: >>> f = frt2(img)


class skimage.transform.FundamentalMatrixTransform(matrix=None) [source]

Bases: skimage.transform._geometric.GeometricTransform Fundamental matrix transformation. The fundamental matrix relates corresponding points between a pair of uncalibrated images. The matrix transforms homogeneous image points in one image to epipolar lines in the other image. The fundamental matrix is only defined for a pair of moving images. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images (ProjectiveTransform). 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.
__init__(matrix=None) [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst) [source]

Estimate fundamental matrix using 8-point algorithm. The 8-point algorithm requires at least 8 corresponding point pairs for a well-conditioned solution, otherwise the over-determined solution is estimated.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.

inverse(coords) [source]

Apply inverse transformation.  Parameters

coords(N, 2) array

Destination coordinates.    Returns

coords(N, 3) array

Epipolar lines in the source image.

residuals(src, dst) [source]

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.


estimate(src, dst) [source]

Estimate fundamental matrix using 8-point algorithm. The 8-point algorithm requires at least 8 corresponding point pairs for a well-conditioned solution, otherwise the over-determined solution is estimated.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.


inverse(coords) [source]

Apply inverse transformation.  Parameters

coords(N, 2) array

Destination coordinates.    Returns

coords(N, 3) array

Epipolar lines in the source image.


residuals(src, dst) [source]

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.


__init__(matrix=None) [source]

Initialize self. See help(type(self)) for accurate signature.


skimage.transform.hough_circle(image, radius, normalize=True, full_output=False) [source]

Perform a circular Hough transform.  Parameters

image(M, N) ndarray

Input image with nonzero values representing edges.
radiusscalar or sequence of scalars

Radii at which to compute the Hough transform. Floats are converted to integers.
normalizeboolean, optional (default True)

Normalize the accumulator with the number of pixels used to draw the radius.
full_outputboolean, optional (default False)

Extend the output size by twice the largest radius in order to detect centers outside the input picture.    Returns

H3D ndarray (radius index, (M + 2R, N + 2R) ndarray)

Hough transform accumulator for each radius. R designates the larger radius if full_output is True. Otherwise, R = 0.     Examples >>> from skimage.transform import hough_circle
>>> from skimage.draw import circle_perimeter
>>> img = np.zeros((100, 100), dtype=bool)
>>> rr, cc = circle_perimeter(25, 35, 23)
>>> img[rr, cc] = 1
>>> try_radii = np.arange(5, 50)
>>> res = hough_circle(img, try_radii)
>>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape)
>>> r, c, try_radii[ridx]
(25, 35, 23)


skimage.transform.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=inf, total_num_peaks=inf, normalize=False) [source]

Return peaks in a circle Hough transform. Identifies most prominent circles separated by certain distances in given Hough spaces. Non-maximum suppression with different sizes is applied separately in the first and second dimension of the Hough space to identify peaks. For circles with different radius but close in distance, only the one with highest peak is kept.  Parameters

hspaces(N, M) array

Hough spaces returned by the hough_circle function.
radii(M,) array

Radii corresponding to Hough spaces.
min_xdistanceint, optional

Minimum distance separating centers in the x dimension.
min_ydistanceint, optional

Minimum distance separating centers in the y dimension.
thresholdfloat, optional

Minimum intensity of peaks in each Hough space. Default is 0.5 * max(hspace).
num_peaksint, optional

Maximum number of peaks in each Hough space. When the number of peaks exceeds num_peaks, only num_peaks coordinates based on peak intensity are considered for the corresponding radius.
total_num_peaksint, optional

Maximum number of peaks. When the number of peaks exceeds num_peaks, return num_peaks coordinates based on peak intensity.
normalizebool, optional

If True, normalize the accumulator by the radius to sort the prominent peaks.    Returns

accum, cx, cy, radtuple of array

Peak values in Hough space, x and y center coordinates and radii.     Notes Circles with bigger radius have higher peaks in Hough space. If larger circles are preferred over smaller ones, normalize should be False. Otherwise, circles will be returned in the order of decreasing voting number. Examples >>> from skimage import transform, draw
>>> img = np.zeros((120, 100), dtype=int)
>>> radius, x_0, y_0 = (20, 99, 50)
>>> y, x = draw.circle_perimeter(y_0, x_0, radius)
>>> img[x, y] = 1
>>> hspaces = transform.hough_circle(img, radius)
>>> accum, cx, cy, rad = hough_circle_peaks(hspaces, [radius,])


skimage.transform.hough_ellipse(image, threshold=4, accuracy=1, min_size=4, max_size=None) [source]

Perform an elliptical Hough transform.  Parameters

image(M, N) ndarray

Input image with nonzero values representing edges.
thresholdint, optional

Accumulator threshold value.
accuracydouble, optional

Bin size on the minor axis used in the accumulator.
min_sizeint, optional

Minimal major axis length.
max_sizeint, optional

Maximal minor axis length. If None, the value is set to the half of the smaller image dimension.    Returns

resultndarray with fields [(accumulator, yc, xc, a, b, orientation)].

Where (yc, xc) is the center, (a, b) the major and minor axes, respectively. The orientation value follows skimage.draw.ellipse_perimeter convention.     Notes The accuracy must be chosen to produce a peak in the accumulator distribution. In other words, a flat accumulator distribution with low values may be caused by a too low bin size. References
1
Xie, Yonghong, and Qiang Ji. “A new efficient ellipse detection method.” Pattern Recognition, 2002. Proceedings. 16th International Conference on. Vol. 2. IEEE, 2002   Examples >>> from skimage.transform import hough_ellipse
>>> from skimage.draw import ellipse_perimeter
>>> img = np.zeros((25, 25), dtype=np.uint8)
>>> rr, cc = ellipse_perimeter(10, 10, 6, 8)
>>> img[cc, rr] = 1
>>> result = hough_ellipse(img, threshold=8)
>>> result.tolist()
[(10, 10.0, 10.0, 8.0, 6.0, 0.0)]


skimage.transform.hough_line(image, theta=None) [source]

Perform a straight line Hough transform.  Parameters

image(M, N) ndarray

Input image with nonzero values representing edges.
theta1D ndarray of double, optional

Angles at which to compute the transform, in radians. Defaults to a vector of 180 angles evenly spaced from -pi/2 to pi/2.    Returns

hspace2-D ndarray of uint64

Hough transform accumulator.
anglesndarray

Angles at which the transform is computed, in radians.
distancesndarray

Distance values.     Notes The origin is the top left corner of the original image. X and Y axis are horizontal and vertical edges respectively. The distance is the minimal algebraic distance from the origin to the detected line. The angle accuracy can be improved by decreasing the step size in the theta array. Examples Generate a test image: >>> img = np.zeros((100, 150), dtype=bool)
>>> img[30, :] = 1
>>> img[:, 65] = 1
>>> img[35:45, 35:50] = 1
>>> for i in range(90):
...     img[i, i] = 1
>>> img += np.random.random(img.shape) > 0.95
 Apply the Hough transform: >>> out, angles, d = hough_line(img)
 import numpy as np
import matplotlib.pyplot as plt

from skimage.transform import hough_line
from skimage.draw import line

img = np.zeros((100, 150), dtype=bool)
img[30, :] = 1
img[:, 65] = 1
img[35:45, 35:50] = 1
rr, cc = line(60, 130, 80, 10)
img[rr, cc] = 1
img += np.random.random(img.shape) > 0.95

out, angles, d = hough_line(img)

fix, axes = plt.subplots(1, 2, figsize=(7, 4))

axes[0].imshow(img, cmap=plt.cm.gray)
axes[0].set_title('Input image')

axes[1].imshow(
    out, cmap=plt.cm.bone,
    extent=(np.rad2deg(angles[-1]), np.rad2deg(angles[0]), d[-1], d[0]))
axes[1].set_title('Hough transform')
axes[1].set_xlabel('Angle (degree)')
axes[1].set_ylabel('Distance (pixel)')

plt.tight_layout()
plt.show()
 (Source code, png, pdf)


skimage.transform.hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, threshold=None, num_peaks=inf) [source]

Return peaks in a straight line Hough transform. Identifies most prominent lines separated by a certain angle and distance in a Hough transform. Non-maximum suppression with different sizes is applied separately in the first (distances) and second (angles) dimension of the Hough space to identify peaks.  Parameters

hspace(N, M) array

Hough space returned by the hough_line function.
angles(M,) array

Angles returned by the hough_line function. Assumed to be continuous. (angles[-1] - angles[0] == PI).
dists(N, ) array

Distances returned by the hough_line function.
min_distanceint, optional

Minimum distance separating lines (maximum filter size for first dimension of hough space).
min_angleint, optional

Minimum angle separating lines (maximum filter size for second dimension of hough space).
thresholdfloat, optional

Minimum intensity of peaks. Default is 0.5 * max(hspace).
num_peaksint, optional

Maximum number of peaks. When the number of peaks exceeds num_peaks, return num_peaks coordinates based on peak intensity.    Returns

accum, angles, diststuple of array

Peak values in Hough space, angles and distances.     Examples >>> from skimage.transform import hough_line, hough_line_peaks
>>> from skimage.draw import line
>>> img = np.zeros((15, 15), dtype=bool)
>>> rr, cc = line(0, 0, 14, 14)
>>> img[rr, cc] = 1
>>> rr, cc = line(0, 14, 14, 0)
>>> img[cc, rr] = 1
>>> hspace, angles, dists = hough_line(img)
>>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists)
>>> len(angles)
2


skimage.transform.ifrt2(a) [source]

Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array.  Parameters

aarray_like

A 2-D (n+1) row x n column integer array.    Returns

iFRT2-D n x n ndarray

Inverse Finite Radon Transform array of n x n integer coefficients.      See also
frt2

The two-dimensional FRT    Notes The FRT has a unique inverse if and only if n is prime. See [1] for an overview. The idea for this algorithm is due to Vlad Negnevitski. References
1
A. Kingston and I. Svalbe, “Projective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006)   Examples >>> SIZE = 59
>>> img = np.tri(SIZE, dtype=np.int32)
 Apply the Finite Radon Transform: >>> f = frt2(img)
 Apply the Inverse Finite Radon Transform to recover the input >>> fi = ifrt2(f)
 Check that it’s identical to the original >>> assert len(np.nonzero(img-fi)[0]) == 0


skimage.transform.integral_image(image) [source]

Integral image / summed area table. The integral image contains the sum of all elements above and to the left of it, i.e.:  \[S[m, n] = \sum_{i \leq m} \sum_{j \leq n} X[i, j]\]  Parameters

imagendarray

Input image.    Returns

Sndarray

Integral image/summed area table of same shape as input image.     References
1
F.C. Crow, “Summed-area tables for texture mapping,” ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212.


skimage.transform.integrate(ii, start, end) [source]

Use an integral image to integrate over a given window.  Parameters

iindarray

Integral image.
startList of tuples, each tuple of length equal to dimension of ii

Coordinates of top left corner of window(s). Each tuple in the list contains the starting row, col, … index i.e [(row_win1, col_win1, …), (row_win2, col_win2,…), …].
endList of tuples, each tuple of length equal to dimension of ii

Coordinates of bottom right corner of window(s). Each tuple in the list containing the end row, col, … index i.e [(row_win1, col_win1, …), (row_win2, col_win2, …), …].    Returns

Sscalar or ndarray

Integral (sum) over the given window(s).     Examples >>> arr = np.ones((5, 6), dtype=float)
>>> ii = integral_image(arr)
>>> integrate(ii, (1, 0), (1, 2))  # sum from (1, 0) to (1, 2)
array([3.])
>>> integrate(ii, [(3, 3)], [(4, 5)])  # sum from (3, 3) to (4, 5)
array([6.])
>>> # sum from (1, 0) to (1, 2) and from (3, 3) to (4, 5)
>>> integrate(ii, [(1, 0), (3, 3)], [(1, 2), (4, 5)])
array([3., 6.])


skimage.transform.iradon(radon_image, theta=None, output_size=None, filter_name='ramp', interpolation='linear', circle=True, preserve_range=True) [source]

Inverse radon transform. Reconstruct an image from the radon transform, using the filtered back projection algorithm.  Parameters

radon_imagearray

Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index radon_image.shape[0] // 2 along the 0th dimension of radon_image.
thetaarray_like, optional

Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of radon_image is (N, M)).
output_sizeint, optional

Number of rows and columns in the reconstruction.
filter_namestr, optional

Filter used in frequency domain filtering. Ramp filter used by default. Filters available: ramp, shepp-logan, cosine, hamming, hann. Assign None to use no filter.
interpolationstr, optional

Interpolation method used in reconstruction. Methods available: ‘linear’, ‘nearest’, and ‘cubic’ (‘cubic’ is slow).
circleboolean, optional

Assume the reconstructed image is zero outside the inscribed circle. Also changes the default output_size to match the behaviour of radon called with circle=True.
preserve_rangebool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

reconstructedndarray

Reconstructed image. The rotation axis will be located in the pixel with indices (reconstructed.shape[0] // 2, reconstructed.shape[1] // 2).    Changed in version 0.19: In iradon, filter argument is deprecated in favor of filter_name.    Notes It applies the Fourier slice theorem to reconstruct an image by multiplying the frequency domain of the filter with the FFT of the projection data. This algorithm is called filtered back projection. References
1
AC Kak, M Slaney, “Principles of Computerized Tomographic Imaging”, IEEE Press 1988.
2
B.R. Ramesh, N. Srinivasa, K. Rajgopal, “An Algorithm for Computing the Discrete Radon Transform With Some Applications”, Proceedings of the Fourth IEEE Region 10 International Conference, TENCON ‘89, 1989


skimage.transform.iradon_sart(radon_image, theta=None, image=None, projection_shifts=None, clip=None, relaxation=0.15, dtype=None) [source]

Inverse radon transform. Reconstruct an image from the radon transform, using a single iteration of the Simultaneous Algebraic Reconstruction Technique (SART) algorithm.  Parameters

radon_image2D array

Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index radon_image.shape[0] // 2 along the 0th dimension of radon_image.
theta1D array, optional

Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of radon_image is (N, M)).
image2D array, optional

Image containing an initial reconstruction estimate. Shape of this array should be (radon_image.shape[0], radon_image.shape[0]). The default is an array of zeros.
projection_shifts1D array, optional

Shift the projections contained in radon_image (the sinogram) by this many pixels before reconstructing the image. The i’th value defines the shift of the i’th column of radon_image.
cliplength-2 sequence of floats, optional

Force all values in the reconstructed tomogram to lie in the range [clip[0], clip[1]]
relaxationfloat, optional

Relaxation parameter for the update step. A higher value can improve the convergence rate, but one runs the risk of instabilities. Values close to or higher than 1 are not recommended.
dtypedtype, optional

Output data type, must be floating point. By default, if input data type is not float, input is cast to double, otherwise dtype is set to input data type.    Returns

reconstructedndarray

Reconstructed image. The rotation axis will be located in the pixel with indices (reconstructed.shape[0] // 2, reconstructed.shape[1] // 2).     Notes Algebraic Reconstruction Techniques are based on formulating the tomography reconstruction problem as a set of linear equations. Along each ray, the projected value is the sum of all the values of the cross section along the ray. A typical feature of SART (and a few other variants of algebraic techniques) is that it samples the cross section at equidistant points along the ray, using linear interpolation between the pixel values of the cross section. The resulting set of linear equations are then solved using a slightly modified Kaczmarz method. When using SART, a single iteration is usually sufficient to obtain a good reconstruction. Further iterations will tend to enhance high-frequency information, but will also often increase the noise. References
1
AC Kak, M Slaney, “Principles of Computerized Tomographic Imaging”, IEEE Press 1988.
2
AH Andersen, AC Kak, “Simultaneous algebraic reconstruction technique (SART): a superior implementation of the ART algorithm”, Ultrasonic Imaging 6 pp 81–94 (1984)
3
S Kaczmarz, “Angenäherte auflösung von systemen linearer gleichungen”, Bulletin International de l’Academie Polonaise des Sciences et des Lettres 35 pp 355–357 (1937)
4
Kohler, T. “A projection access scheme for iterative reconstruction based on the golden section.” Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
5
Kaczmarz’ method, Wikipedia, https://en.wikipedia.org/wiki/Kaczmarz_method


skimage.transform.matrix_transform(coords, matrix) [source]

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.


skimage.transform.order_angles_golden_ratio(theta) [source]

Order angles to reduce the amount of correlated information in subsequent projections.  Parameters

theta1D array of floats

Projection angles in degrees. Duplicate angles are not allowed.    Returns

indices_generatorgenerator yielding unsigned integers

The returned generator yields indices into theta such that theta[indices] gives the approximate golden ratio ordering of the projections. In total, len(theta) indices are yielded. All non-negative integers < len(theta) are yielded exactly once.     Notes The method used here is that of the golden ratio introduced by T. Kohler. References
1
Kohler, T. “A projection access scheme for iterative reconstruction based on the golden section.” Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
2
Winkelmann, Stefanie, et al. “An optimal radial profile order based on the Golden Ratio for time-resolved MRI.” Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76.


class skimage.transform.PiecewiseAffineTransform [source]

Bases: skimage.transform._geometric.GeometricTransform 2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform.  Attributes

affineslist of AffineTransform objects

Affine transformations for each triangle in the mesh.
inverse_affineslist of AffineTransform objects

Inverse affine transformations for each triangle in the mesh.
__init__() [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.

inverse(coords) [source]

Apply inverse transformation. Coordinates outside of the mesh will be set to - 1.  Parameters

coords(N, 2) array

Source coordinates.    Returns

coords(N, 2) array

Transformed coordinates.


estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.


inverse(coords) [source]

Apply inverse transformation. Coordinates outside of the mesh will be set to - 1.  Parameters

coords(N, 2) array

Source coordinates.    Returns

coords(N, 2) array

Transformed coordinates.


__init__() [source]

Initialize self. See help(type(self)) for accurate signature.


class skimage.transform.PolynomialTransform(params=None) [source]

Bases: skimage.transform._geometric.GeometricTransform 2D polynomial transformation. Has the following form: X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))
  Parameters

params(2, N) array, optional

Polynomial coefficients where N * 2 = (order + 1) * (order + 2). So, a_ji is defined in params[0, :] and b_ji in params[1, :].    Attributes

params(2, N) array

Polynomial coefficients where N * 2 = (order + 1) * (order + 2). So, a_ji is defined in params[0, :] and b_ji in params[1, :].
__init__(params=None) [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst, order=2) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))
 These equations can be transformed to the following form: 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y
 which exist for each set of corresponding points, so we have a set of N * 2 equations. The coefficients appear linearly so we can write A x = 0, where: A   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
       [0 ...                 0 1 x y x**2 x*y y**2 -Y]
        ...
        ...
      ]
x.T = [a00 a10 a11 a20 a21 a22 ... ann
       b00 b10 b11 b20 b21 b22 ... bnn c3]
 In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.
orderint, optional

Polynomial order (number of coefficients is order + 1).    Returns

successbool

True, if model estimation succeeds.

inverse(coords) [source]

Apply inverse transformation.  Parameters

coords(N, 2) array

Destination coordinates.    Returns

coords(N, 2) array

Source coordinates.


estimate(src, dst, order=2) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))
 These equations can be transformed to the following form: 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y
 which exist for each set of corresponding points, so we have a set of N * 2 equations. The coefficients appear linearly so we can write A x = 0, where: A   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
       [0 ...                 0 1 x y x**2 x*y y**2 -Y]
        ...
        ...
      ]
x.T = [a00 a10 a11 a20 a21 a22 ... ann
       b00 b10 b11 b20 b21 b22 ... bnn c3]
 In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.
orderint, optional

Polynomial order (number of coefficients is order + 1).    Returns

successbool

True, if model estimation succeeds.


inverse(coords) [source]

Apply inverse transformation.  Parameters

coords(N, 2) array

Destination coordinates.    Returns

coords(N, 2) array

Source coordinates.


__init__(params=None) [source]

Initialize self. See help(type(self)) for accurate signature.


skimage.transform.probabilistic_hough_line(image, threshold=10, line_length=50, line_gap=10, theta=None, seed=None) [source]

Return lines from a progressive probabilistic line Hough transform.  Parameters

image(M, N) ndarray

Input image with nonzero values representing edges.
thresholdint, optional

Threshold
line_lengthint, optional

Minimum accepted length of detected lines. Increase the parameter to extract longer lines.
line_gapint, optional

Maximum gap between pixels to still form a line. Increase the parameter to merge broken lines more aggressively.
theta1D ndarray, dtype=double, optional

Angles at which to compute the transform, in radians. If None, use a range from -pi/2 to pi/2.
seedint, optional

Seed to initialize the random number generator.    Returns

lineslist

List of lines identified, lines in format ((x0, y0), (x1, y1)), indicating line start and end.     References
1
C. Galamhos, J. Matas and J. Kittler, “Progressive probabilistic Hough transform for line detection”, in IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 1999.


class skimage.transform.ProjectiveTransform(matrix=None) [source]

Bases: skimage.transform._geometric.GeometricTransform Projective transformation. Apply a projective transformation (homography) on coordinates. For each homogeneous coordinate \(\mathbf{x} = [x, y, 1]^T\), its target position is calculated by multiplying with the given matrix, \(H\), to give \(H \mathbf{x}\): [[a0 a1 a2]
 [b0 b1 b2]
 [c0 c1 1 ]].
 E.g., to rotate by theta degrees clockwise, the matrix should be: [[cos(theta) -sin(theta) 0]
 [sin(theta)  cos(theta) 0]
 [0            0         1]]
 or, to translate x by 10 and y by 20: [[1 0 10]
 [0 1 20]
 [0 0 1 ]].
  Parameters

matrix(3, 3) array, optional

Homogeneous transformation matrix.    Attributes

params(3, 3) array

Homogeneous transformation matrix.
__init__(matrix=None) [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)
 These equations can be transformed to the following form: 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y
 which exist for each set of corresponding points, so we have a set of N * 2 equations. The coefficients appear linearly so we can write A x = 0, where: A   = [[x y 1 0 0 0 -x*X -y*X -X]
       [0 0 0 x y 1 -x*Y -y*Y -Y]
        ...
        ...
      ]
x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]
 In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3. In case of the affine transformation the coefficients c0 and c1 are 0. Thus the system of equations is: A   = [[x y 1 0 0 0 -X]
       [0 0 0 x y 1 -Y]
        ...
        ...
      ]
x.T = [a0 a1 a2 b0 b1 b2 c3]
  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.

inverse(coords) [source]

Apply inverse transformation.  Parameters

coords(N, 2) array

Destination coordinates.    Returns

coords(N, 2) array

Source coordinates.


estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)
 These equations can be transformed to the following form: 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y
 which exist for each set of corresponding points, so we have a set of N * 2 equations. The coefficients appear linearly so we can write A x = 0, where: A   = [[x y 1 0 0 0 -x*X -y*X -X]
       [0 0 0 x y 1 -x*Y -y*Y -Y]
        ...
        ...
      ]
x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]
 In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3. In case of the affine transformation the coefficients c0 and c1 are 0. Thus the system of equations is: A   = [[x y 1 0 0 0 -X]
       [0 0 0 x y 1 -Y]
        ...
        ...
      ]
x.T = [a0 a1 a2 b0 b1 b2 c3]
  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.


__init__(matrix=None) [source]

Initialize self. See help(type(self)) for accurate signature.


skimage.transform.pyramid_expand(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False) [source]

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://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

outarray

Upsampled and smoothed float image.     References
1
http://persci.mit.edu/pub_pdfs/pyramid83.pdf


skimage.transform.pyramid_gaussian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False) [source]

Yield images of the Gaussian pyramid formed by the input image. Recursively applies the pyramid_reduce function to the image, and yields the downscaled images. Note that the first image of the pyramid will be the original, unscaled image. The total number of images is max_layer + 1. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape.  Parameters

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://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

pyramidgenerator

Generator yielding pyramid layers as float images.     References
1
http://persci.mit.edu/pub_pdfs/pyramid83.pdf


skimage.transform.pyramid_laplacian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False) [source]

Yield images of the laplacian pyramid formed by the input image. Each layer contains the difference between the downsampled and the downsampled, smoothed image: layer = resize(prev_layer) - smooth(resize(prev_layer))
 Note that the first image of the pyramid will be the difference between the original, unscaled image and its smoothed version. The total number of images is max_layer + 1. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape.  Parameters

imagendarray

Input image.
max_layerint, optional

Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers.
downscalefloat, optional

Downscale factor.
sigmafloat, optional

Sigma for Gaussian filter. Default is 2 * downscale / 6.0 which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution.
orderint, optional

Order of splines used in interpolation of downsampling. See skimage.transform.warp for detail.
mode{‘reflect’, ‘constant’, ‘edge’, ‘symmetric’, ‘wrap’}, optional

The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’.
cvalfloat, optional

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

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
preserve_rangebool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

pyramidgenerator

Generator yielding pyramid layers as float images.     References
1
http://persci.mit.edu/pub_pdfs/pyramid83.pdf
2
http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html


skimage.transform.pyramid_reduce(image, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False) [source]

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://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

outarray

Smoothed and downsampled float image.     References
1
http://persci.mit.edu/pub_pdfs/pyramid83.pdf


skimage.transform.radon(image, theta=None, circle=True, *, preserve_range=False) [source]

Calculates the radon transform of an image given specified projection angles.  Parameters

imagearray_like

Input image. The rotation axis will be located in the pixel with indices (image.shape[0] // 2, image.shape[1] // 2).
thetaarray_like, optional

Projection angles (in degrees). If None, the value is set to np.arange(180).
circleboolean, optional

Assume image is zero outside the inscribed circle, making the width of each projection (the first dimension of the sinogram) equal to min(image.shape).
preserve_rangebool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

radon_imagendarray

Radon transform (sinogram). The tomography rotation axis will lie at the pixel index radon_image.shape[0] // 2 along the 0th dimension of radon_image.     Notes Based on code of Justin K. Romberg (https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html) References
1
AC Kak, M Slaney, “Principles of Computerized Tomographic Imaging”, IEEE Press 1988.
2
B.R. Ramesh, N. Srinivasa, K. Rajgopal, “An Algorithm for Computing the Discrete Radon Transform With Some Applications”, Proceedings of the Fourth IEEE Region 10 International Conference, TENCON ‘89, 1989


skimage.transform.rescale(image, scale, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, multichannel=False, anti_aliasing=None, anti_aliasing_sigma=None) [source]

Scale image by a certain factor. Performs interpolation to up-scale or down-scale N-dimensional images. Note that anti-aliasing should be enabled when down-sizing images to avoid aliasing artifacts. For down-sampling with an integer factor also see skimage.transform.downscale_local_mean.  Parameters

imagendarray

Input image.
scale{float, tuple of floats}

Scale factors. Separate scale factors can be defined as (rows, cols[, …][, dim]).    Returns

scaledndarray

Scaled version of the input.    Other Parameters

orderint, optional

The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp 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://scikit-image.org/docs/dev/user_guide/data_types.html
multichannelbool, optional

Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension.
anti_aliasingbool, optional

Whether to apply a Gaussian filter to smooth the image prior to down-scaling. It is crucial to filter when down-sampling the image to avoid aliasing artifacts. If input image data type is bool, no anti-aliasing is applied.
anti_aliasing_sigma{float, tuple of floats}, optional

Standard deviation for Gaussian filtering to avoid aliasing artifacts. By default, this value is chosen as (s - 1) / 2 where s is the down-scaling factor.     Notes Modes ‘reflect’ and ‘symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. Examples >>> from skimage import data
>>> from skimage.transform import rescale
>>> image = data.camera()
>>> rescale(image, 0.1).shape
(51, 51)
>>> rescale(image, 0.5).shape
(256, 256)


skimage.transform.resize(image, output_shape, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None) [source]

Resize image to match a certain size. Performs interpolation to up-size or down-size N-dimensional images. Note that anti-aliasing should be enabled when down-sizing images to avoid aliasing artifacts. For down-sampling with an integer factor also see skimage.transform.downscale_local_mean.  Parameters

imagendarray

Input image.
output_shapetuple or ndarray

Size of the generated output image (rows, cols[, …][, dim]). If dim is not provided, the number of channels is preserved. In case the number of input channels does not equal the number of output channels a n-dimensional interpolation is applied.    Returns

resizedndarray

Resized version of the input.    Other Parameters

orderint, optional

The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp 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://scikit-image.org/docs/dev/user_guide/data_types.html
anti_aliasingbool, optional

Whether to apply a Gaussian filter to smooth the image prior to down-scaling. It is crucial to filter when down-sampling the image to avoid aliasing artifacts. If input image data type is bool, no anti-aliasing is applied.
anti_aliasing_sigma{float, tuple of floats}, optional

Standard deviation for Gaussian filtering to avoid aliasing artifacts. By default, this value is chosen as (s - 1) / 2 where s is the down-scaling factor, where s > 1. For the up-size case, s < 1, no anti-aliasing is performed prior to rescaling.     Notes Modes ‘reflect’ and ‘symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. Examples >>> from skimage import data
>>> from skimage.transform import resize
>>> image = data.camera()
>>> resize(image, (100, 100)).shape
(100, 100)


skimage.transform.rotate(image, angle, resize=False, center=None, order=None, mode='constant', cval=0, clip=True, preserve_range=False) [source]

Rotate image by a certain angle around its center.  Parameters

imagendarray

Input image.
anglefloat

Rotation angle in degrees in counter-clockwise direction.
resizebool, optional

Determine whether the shape of the output image will be automatically calculated, so the complete rotated image exactly fits. Default is False.
centeriterable of length 2

The rotation center. If center=None, the image is rotated around its center, i.e. center=(cols / 2 - 0.5, rows / 2 - 0.5). Please note that this parameter is (cols, rows), contrary to normal skimage ordering.    Returns

rotatedndarray

Rotated version of the input.    Other Parameters

orderint, optional

The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp 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://scikit-image.org/docs/dev/user_guide/data_types.html     Notes Modes ‘reflect’ and ‘symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. Examples >>> from skimage import data
>>> from skimage.transform import rotate
>>> image = data.camera()
>>> rotate(image, 2).shape
(512, 512)
>>> rotate(image, 2, resize=True).shape
(530, 530)
>>> rotate(image, 90, resize=True).shape
(512, 512)


class skimage.transform.SimilarityTransform(matrix=None, scale=None, rotation=None, translation=None) [source]

Bases: skimage.transform._geometric.EuclideanTransform 2D similarity transformation. Has the following form: X = a0 * x - b0 * y + a1 =
  = s * x * cos(rotation) - s * y * sin(rotation) + a1

Y = b0 * x + a0 * y + b1 =
  = s * x * sin(rotation) + s * y * cos(rotation) + b1
 where s is a scale factor and the homogeneous transformation matrix is: [[a0  b0  a1]
 [b0  a0  b1]
 [0   0    1]]
 The similarity transformation extends the Euclidean transformation with a single scaling factor in addition to the rotation and translation parameters.  Parameters

matrix(3, 3) array, optional

Homogeneous transformation matrix.
scalefloat, optional

Scale factor.
rotationfloat, optional

Rotation angle in counter-clockwise direction as radians.
translation(tx, ty) as array, list or tuple, optional

x, y translation parameters.    Attributes

params(3, 3) array

Homogeneous transformation matrix.
__init__(matrix=None, scale=None, rotation=None, translation=None) [source]

Initialize self. See help(type(self)) for accurate signature.

estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.

property scale


estimate(src, dst) [source]

Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match.  Parameters

src(N, 2) array

Source coordinates.
dst(N, 2) array

Destination coordinates.    Returns

successbool

True, if model estimation succeeds.


__init__(matrix=None, scale=None, rotation=None, translation=None) [source]

Initialize self. See help(type(self)) for accurate signature.


skimage.transform.swirl(image, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=None, mode='reflect', cval=0, clip=True, preserve_range=False) [source]

Perform a swirl transformation.  Parameters

imagendarray

Input image.
center(column, row) tuple or (2,) ndarray, optional

Center coordinate of transformation.
strengthfloat, optional

The amount of swirling applied.
radiusfloat, optional

The extent of the swirl in pixels. The effect dies out rapidly beyond radius.
rotationfloat, optional

Additional rotation applied to the image.    Returns

swirledndarray

Swirled version of the input.    Other Parameters

output_shapetuple (rows, cols), optional

Shape of the output image generated. By default the shape of the input image is preserved.
orderint, optional

The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp 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://scikit-image.org/docs/dev/user_guide/data_types.html


skimage.transform.warp(image, inverse_map, map_args={}, output_shape=None, order=None, mode='constant', cval=0.0, clip=True, preserve_range=False) [source]

Warp an image according to a given coordinate transformation.  Parameters

imagendarray

Input image.
inverse_maptransformation object, callable cr = f(cr, **kwargs), or ndarray

Inverse coordinate map, which transforms coordinates in the output images into their corresponding coordinates in the input image. There are a number of different options to define this map, depending on the dimensionality of the input image. A 2-D image can have 2 dimensions for gray-scale images, or 3 dimensions with color information.  For 2-D images, you can directly pass a transformation object, e.g. skimage.transform.SimilarityTransform, or its inverse. For 2-D images, you can pass a (3, 3) homogeneous transformation matrix, e.g. skimage.transform.SimilarityTransform.params. For 2-D images, a function that transforms a (M, 2) array of (col, row) coordinates in the output image to their corresponding coordinates in the input image. Extra parameters to the function can be specified through map_args. For N-D images, you can directly pass an array of coordinates. The first dimension specifies the coordinates in the input image, while the subsequent dimensions determine the position in the output image. E.g. in case of 2-D images, you need to pass an array of shape (2, rows, cols), where rows and cols determine the shape of the output image, and the first dimension contains the (row, col) coordinate in the input image. See scipy.ndimage.map_coordinates for further documentation.  Note, that a (3, 3) matrix is interpreted as a homogeneous transformation matrix, so you cannot interpolate values from a 3-D input, if the output is of shape (3,). See example section for usage.
map_argsdict, optional

Keyword arguments passed to inverse_map.
output_shapetuple (rows, cols), optional

Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.
orderint, optional

 The order of interpolation. The order has to be in the range 0-5:

 0: Nearest-neighbor 1: Bi-linear (default) 2: Bi-quadratic 3: Bi-cubic 4: Bi-quartic 5: Bi-quintic  Default is 0 if image.dtype is bool and 1 otherwise.
mode{‘constant’, ‘edge’, ‘symmetric’, ‘reflect’, ‘wrap’}, optional

Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
cvalfloat, optional

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

Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_rangebool, optional

Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html    Returns

warpeddouble ndarray

The warped input image.     Notes  The input image is converted to a double image. In case of a SimilarityTransform, AffineTransform and ProjectiveTransform and order in [0, 3] this function uses the underlying transformation matrix to warp the image with a much faster routine.  Examples >>> from skimage.transform import warp
>>> from skimage import data
>>> image = data.camera()
 The following image warps are all equal but differ substantially in execution time. The image is shifted to the bottom. Use a geometric transform to warp an image (fast): >>> from skimage.transform import SimilarityTransform
>>> tform = SimilarityTransform(translation=(0, -10))
>>> warped = warp(image, tform)
 Use a callable (slow): >>> def shift_down(xy):
...     xy[:, 1] -= 10
...     return xy
>>> warped = warp(image, shift_down)
 Use a transformation matrix to warp an image (fast): >>> matrix = np.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]])
>>> warped = warp(image, matrix)
>>> from skimage.transform import ProjectiveTransform
>>> warped = warp(image, ProjectiveTransform(matrix=matrix))
 You can also use the inverse of a geometric transformation (fast): >>> warped = warp(image, tform.inverse)
 For N-D images you can pass a coordinate array, that specifies the coordinates in the input image for every element in the output image. E.g. if you want to rescale a 3-D cube, you can do: >>> cube_shape = np.array([30, 30, 30])
>>> cube = np.random.rand(*cube_shape)
 Setup the coordinate array, that defines the scaling: >>> scale = 0.1
>>> output_shape = (scale * cube_shape).astype(int)
>>> coords0, coords1, coords2 = np.mgrid[:output_shape[0],
...                    :output_shape[1], :output_shape[2]]
>>> coords = np.array([coords0, coords1, coords2])
 Assume that the cube contains spatial data, where the first array element center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to account for this extra offset when scaling the image: >>> coords = (coords + 0.5) / scale - 0.5
>>> warped = warp(cube, coords)


skimage.transform.warp_coords(coord_map, shape, dtype=<class 'numpy.float64'>) [source]

Build the source coordinates for the output of a 2-D image warp.  Parameters

coord_mapcallable like GeometricTransform.inverse

Return input coordinates for given output coordinates. Coordinates are in the shape (P, 2), where P is the number of coordinates and each element is a (row, col) pair.
shapetuple

Shape of output image (rows, cols[, bands]).
dtypenp.dtype or string

dtype for return value (sane choices: float32 or float64).    Returns

coords(ndim, rows, cols[, bands]) array of dtype dtype

Coordinates for scipy.ndimage.map_coordinates, that will yield an image of shape (orows, ocols, bands) by drawing from source points according to the coord_transform_fn.     Notes This is a lower-level routine that produces the source coordinates for 2-D images used by warp(). It is provided separately from warp to give additional flexibility to users who would like, for example, to re-use a particular coordinate mapping, to use specific dtypes at various points along the the image-warping process, or to implement different post-processing logic than warp performs after the call to ndi.map_coordinates. Examples Produce a coordinate map that shifts an image up and to the right: >>> from skimage import data
>>> from scipy.ndimage import map_coordinates
>>>
>>> def shift_up10_left20(xy):
...     return xy - np.array([-20, 10])[None, :]
>>>
>>> image = data.astronaut().astype(np.float32)
>>> coords = warp_coords(shift_up10_left20, image.shape)
>>> warped_image = map_coordinates(image, coords)


skimage.transform.warp_polar(image, center=None, *, radius=None, output_shape=None, scaling='linear', multichannel=False, **kwargs) [source]

Remap image to polar or log-polar coordinates space.  Parameters

imagendarray

Input image. Only 2-D arrays are accepted by default. If multichannel=True, 3-D arrays are accepted and the last axis is interpreted as multiple channels.
centertuple (row, col), optional

Point in image that represents the center of the transformation (i.e., the origin in cartesian space). Values can be of type float. If no value is given, the center is assumed to be the center point of the image.
radiusfloat, optional

Radius of the circle that bounds the area to be transformed.
output_shapetuple (row, col), optional

scaling{‘linear’, ‘log’}, optional

Specify whether the image warp is polar or log-polar. Defaults to ‘linear’.
multichannelbool, optional

Whether the image is a 3-D array in which the third axis is to be interpreted as multiple channels. If set to False (default), only 2-D arrays are accepted.
**kwargskeyword arguments

Passed to transform.warp.    Returns

warpedndarray

The polar or log-polar warped image.     Examples Perform a basic polar warp on a grayscale image: >>> from skimage import data
>>> from skimage.transform import warp_polar
>>> image = data.checkerboard()
>>> warped = warp_polar(image)
 Perform a log-polar warp on a grayscale image: >>> warped = warp_polar(image, scaling='log')
 Perform a log-polar warp on a grayscale image while specifying center, radius, and output shape: >>> warped = warp_polar(image, (100,100), radius=100,
...                     output_shape=image.shape, scaling='log')
 Perform a log-polar warp on a color image: >>> image = data.astronaut()
>>> warped = warp_polar(image, scaling='log', multichannel=True)


Tutorials  Image Segmentation How to parallelize loops


Module: util
skimage.util.apply_parallel(function, array) Map a function in parallel across an array.
skimage.util.compare_images(image1, image2) Return an image showing the differences between two images.
skimage.util.crop(ar, crop_width[, copy, order]) Crop array ar by crop_width along each dimension.
skimage.util.dtype_limits(image[, clip_negative]) Return intensity limits, i.e.
skimage.util.img_as_bool(image[, force_copy]) Convert an image to boolean format.
skimage.util.img_as_float(image[, force_copy]) Convert an image to floating point format.
skimage.util.img_as_float32(image[, force_copy]) Convert an image to single-precision (32-bit) floating point format.
skimage.util.img_as_float64(image[, force_copy]) Convert an image to double-precision (64-bit) floating point format.
skimage.util.img_as_int(image[, force_copy]) Convert an image to 16-bit signed integer format.
skimage.util.img_as_ubyte(image[, force_copy]) Convert an image to 8-bit unsigned integer format.
skimage.util.img_as_uint(image[, force_copy]) Convert an image to 16-bit unsigned integer format.
skimage.util.invert(image[, signed_float]) Invert an image.
skimage.util.map_array(input_arr, …[, out]) Map values from input array from input_vals to output_vals.
skimage.util.montage(arr_in[, fill, …]) Create a montage of several single- or multichannel images.
skimage.util.pad(array, pad_width[, mode]) Pad an array.
skimage.util.random_noise(image[, mode, …]) Function to add random noise of various types to a floating-point image.
skimage.util.regular_grid(ar_shape, n_points) Find n_points regularly spaced along ar_shape.
skimage.util.regular_seeds(ar_shape, n_points) Return an image with ~`n_points` regularly-spaced nonzero pixels.
skimage.util.unique_rows(ar) Remove repeated rows from a 2D array.
skimage.util.view_as_blocks(arr_in, block_shape) Block view of the input n-dimensional array (using re-striding).
skimage.util.view_as_windows(arr_in, …[, step]) Rolling window view of the input n-dimensional array.   apply_parallel
skimage.util.apply_parallel(function, array, chunks=None, depth=0, mode=None, extra_arguments=(), extra_keywords={}, *, dtype=None, multichannel=False, compute=None) [source]

Map a function in parallel across an array. Split an array into possibly overlapping chunks of a given depth and boundary type, call the given function in parallel on the chunks, combine the chunks and return the resulting array.  Parameters

functionfunction

Function to be mapped which takes an array as an argument.
arraynumpy array or dask array

Array which the function will be applied to.
chunksint, tuple, or tuple of tuples, optional

A single integer is interpreted as the length of one side of a square chunk that should be tiled across the array. One tuple of length array.ndim represents the shape of a chunk, and it is tiled across the array. A list of tuples of length ndim, where each sub-tuple is a sequence of chunk sizes along the corresponding dimension. If None, the array is broken up into chunks based on the number of available cpus. More information about chunks is in the documentation here.
depthint, optional

Integer equal to the depth of the added boundary cells. Defaults to zero.
mode{‘reflect’, ‘symmetric’, ‘periodic’, ‘wrap’, ‘nearest’, ‘edge’}, optional

type of external boundary padding.
extra_argumentstuple, optional

Tuple of arguments to be passed to the function.
extra_keywordsdictionary, optional

Dictionary of keyword arguments to be passed to the function.
dtypedata-type or None, optional

The data-type of the function output. If None, Dask will attempt to infer this by calling the function on data of shape (1,) * ndim. For functions expecting RGB or multichannel data this may be problematic. In such cases, the user should manually specify this dtype argument instead.  New in version 0.18: dtype was added in 0.18.
multichannelbool, optional

If chunks is None and multichannel is True, this function will keep only a single chunk along the channels axis. When depth is specified as a scalar value, that depth will be applied only to the non-channels axes (a depth of 0 will be used along the channels axis). If the user manually specified both chunks and a depth tuple, then this argument will have no effect.  New in version 0.18: multichannel was added in 0.18.
computebool, optional

If True, compute eagerly returning a NumPy Array. If False, compute lazily returning a Dask Array. If None (default), compute based on array type provided (eagerly for NumPy Arrays and lazily for Dask Arrays).    Returns

outndarray or dask Array

Returns the result of the applying the operation. Type is dependent on the compute argument.     Notes Numpy edge modes ‘symmetric’, ‘wrap’, and ‘edge’ are converted to the equivalent dask boundary modes ‘reflect’, ‘periodic’ and ‘nearest’, respectively. Setting compute=False can be useful for chaining later operations. For example region selection to preview a result or storing large data to disk instead of loading in memory.
 compare_images
skimage.util.compare_images(image1, image2, method='diff', *, n_tiles=(8, 8)) [source]

Return an image showing the differences between two images.  New in version 0.16.   Parameters

image1, image22-D array

Images to process, must be of the same shape.
methodstring, optional

Method used for the comparison. Valid values are {‘diff’, ‘blend’, ‘checkerboard’}. Details are provided in the note section.
n_tilestuple, optional

Used only for the checkerboard method. Specifies the number of tiles (row, column) to divide the image.    Returns

comparison2-D array

Image showing the differences.     Notes 'diff' computes the absolute difference between the two images. 'blend' computes the mean value. 'checkerboard' makes tiles of dimension n_tiles that display alternatively the first and the second image.
 crop
skimage.util.crop(ar, crop_width, copy=False, order='K') [source]

Crop array ar by crop_width along each dimension.  Parameters

ararray-like of rank N

Input array.
crop_width{sequence, int}

Number of values to remove from the edges of each axis. ((before_1, after_1), … (before_N, after_N)) specifies unique crop widths at the start and end of each axis. ((before, after),) or (before, after) specifies a fixed start and end crop for every axis. (n,) or n for integer n is a shortcut for before = after = n for all axes.
copybool, optional

If True, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

If copy==True, control the memory layout of the copy. See np.copy.    Returns

croppedarray

The cropped array. If copy=False (default), this is a sliced view of the input array.
 dtype_limits
skimage.util.dtype_limits(image, clip_negative=False) [source]

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

imagendarray

Input image.
clip_negativebool, optional

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

imin, imaxtuple

Lower and upper intensity limits.
 img_as_bool
skimage.util.img_as_bool(image, force_copy=False) [source]

Convert an image to boolean format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of bool (bool_)

Output image.     Notes The upper half of the input dtype’s positive range is True, and the lower half is False. All negative values (if present) are False.
 img_as_float
skimage.util.img_as_float(image, force_copy=False) [source]

Convert an image to floating point format. This function is similar to img_as_float64, but will not convert lower-precision floating point arrays to float64.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of float

Output image.     Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
 img_as_float32
skimage.util.img_as_float32(image, force_copy=False) [source]

Convert an image to single-precision (32-bit) floating point format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of float32

Output image.     Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
 img_as_float64
skimage.util.img_as_float64(image, force_copy=False) [source]

Convert an image to double-precision (64-bit) floating point format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of float64

Output image.     Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0].
 img_as_int
skimage.util.img_as_int(image, force_copy=False) [source]

Convert an image to 16-bit signed integer format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of int16

Output image.     Notes The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values.
 img_as_ubyte
skimage.util.img_as_ubyte(image, force_copy=False) [source]

Convert an image to 8-bit unsigned integer format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of ubyte (uint8)

Output image.     Notes Negative input values will be clipped. Positive values are scaled between 0 and 255.
 img_as_uint
skimage.util.img_as_uint(image, force_copy=False) [source]

Convert an image to 16-bit unsigned integer format.  Parameters

imagendarray

Input image.
force_copybool, optional

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

outndarray of uint16

Output image.     Notes Negative input values will be clipped. Positive values are scaled between 0 and 65535.
 invert
skimage.util.invert(image, signed_float=False) [source]

Invert an image. Invert the intensity range of the input image, so that the dtype maximum is now the dtype minimum, and vice-versa. This operation is slightly different depending on the input dtype:  unsigned integers: subtract the image from the dtype maximum signed integers: subtract the image from -1 (see Notes) floats: subtract the image from 1 (if signed_float is False, so we assume the image is unsigned), or from 0 (if signed_float is True).  See the examples for clarification.  Parameters

imagendarray

Input image.
signed_floatbool, optional

If True and the image is of type float, the range is assumed to be [-1, 1]. If False and the image is of type float, the range is assumed to be [0, 1].    Returns

invertedndarray

Inverted image.     Notes Ideally, for signed integers we would simply multiply by -1. However, signed integer ranges are asymmetric. For example, for np.int8, the range of possible values is [-128, 127], so that -128 * -1 equals -128! By subtracting from -1, we correctly map the maximum dtype value to the minimum. Examples >>> img = np.array([[100,  0, 200],
...                 [  0, 50,   0],
...                 [ 30,  0, 255]], np.uint8)
>>> invert(img)
array([[155, 255,  55],
       [255, 205, 255],
       [225, 255,   0]], dtype=uint8)
>>> img2 = np.array([[ -2, 0, -128],
...                  [127, 0,    5]], np.int8)
>>> invert(img2)
array([[   1,   -1,  127],
       [-128,   -1,   -6]], dtype=int8)
>>> img3 = np.array([[ 0., 1., 0.5, 0.75]])
>>> invert(img3)
array([[1.  , 0.  , 0.5 , 0.25]])
>>> img4 = np.array([[ 0., 1., -1., -0.25]])
>>> invert(img4, signed_float=True)
array([[-0.  , -1.  ,  1.  ,  0.25]])

 Examples using skimage.util.invert

  Use rolling-ball algorithm for estimating background intensity   map_array
skimage.util.map_array(input_arr, input_vals, output_vals, out=None) [source]

Map values from input array from input_vals to output_vals.  Parameters

input_arrarray of int, shape (M[, N][, P][, …])

The input label image.
input_valsarray of int, shape (N,)

The values to map from.
output_valsarray, shape (N,)

The values to map to.  out: array, same shape as `input_arr`

The output array. Will be created if not provided. It should have the same dtype as output_vals.    Returns

outarray, same shape as input_arr

The array of mapped values.
 montage
skimage.util.montage(arr_in, fill='mean', rescale_intensity=False, grid_shape=None, padding_width=0, multichannel=False) [source]

Create a montage of several single- or multichannel images. Create a rectangular montage from an input array representing an ensemble of equally shaped single- (gray) or multichannel (color) images. For example, montage(arr_in) called with the following arr_in
1 2 3   will return
1 2
3
      where the ‘*’ patch will be determined by the fill parameter.  Parameters

arr_in(K, M, N[, C]) ndarray

An array representing an ensemble of K images of equal shape.
fillfloat or array-like of floats or ‘mean’, optional

Value to fill the padding areas and/or the extra tiles in the output array. Has to be float for single channel collections. For multichannel collections has to be an array-like of shape of number of channels. If mean, uses the mean value over all images.
rescale_intensitybool, optional

Whether to rescale the intensity of each image to [0, 1].
grid_shapetuple, optional

The desired grid shape for the montage (ntiles_row, ntiles_column). The default aspect ratio is square.
padding_widthint, optional

The size of the spacing between the tiles and between the tiles and the borders. If non-zero, makes the boundaries of individual images easier to perceive.
multichannelboolean, optional

If True, the last arr_in dimension is threated as a color channel, otherwise as spatial.    Returns

arr_out(K*(M+p)+p, K*(N+p)+p[, C]) ndarray

Output array with input images glued together (including padding p).     Examples >>> import numpy as np
>>> from skimage.util import montage
>>> arr_in = np.arange(3 * 2 * 2).reshape(3, 2, 2)
>>> arr_in
array([[[ 0,  1],
        [ 2,  3]],
       [[ 4,  5],
        [ 6,  7]],
       [[ 8,  9],
        [10, 11]]])
>>> arr_out = montage(arr_in)
>>> arr_out.shape
(4, 4)
>>> arr_out
array([[ 0,  1,  4,  5],
       [ 2,  3,  6,  7],
       [ 8,  9,  5,  5],
       [10, 11,  5,  5]])
>>> arr_in.mean()
5.5
>>> arr_out_nonsquare = montage(arr_in, grid_shape=(1, 3))
>>> arr_out_nonsquare
array([[ 0,  1,  4,  5,  8,  9],
       [ 2,  3,  6,  7, 10, 11]])
>>> arr_out_nonsquare.shape
(2, 6)

 pad
skimage.util.pad(array, pad_width, mode='constant', **kwargs) [source]

Pad an array.  Parameters

arrayarray_like of rank N

The array to pad.
pad_width{sequence, array_like, int}

Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.
modestr or function, optional

One of the following string values or a user supplied function.  ‘constant’ (default)

Pads with a constant value.  ‘edge’

Pads with the edge values of array.  ‘linear_ramp’

Pads with the linear ramp between end_value and the array edge value.  ‘maximum’

Pads with the maximum value of all or part of the vector along each axis.  ‘mean’

Pads with the mean value of all or part of the vector along each axis.  ‘median’

Pads with the median value of all or part of the vector along each axis.  ‘minimum’

Pads with the minimum value of all or part of the vector along each axis.  ‘reflect’

Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.  ‘symmetric’

Pads with the reflection of the vector mirrored along the edge of the array.  ‘wrap’

Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.  ‘empty’

Pads with undefined values.  New in version 1.17.   <function>

Padding function, see Notes.
stat_lengthsequence or int, optional

Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value. ((before_1, after_1), … (before_N, after_N)) unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat_length,) or int is a shortcut for before = after = statistic length for all axes. Default is None, to use the entire axis.
constant_valuessequence or scalar, optional

Used in ‘constant’. The values to set the padded values for each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad constants for each axis. ((before, after),) yields same before and after constants for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.
end_valuessequence or scalar, optional

Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded array. ((before_1, after_1), ... (before_N, after_N)) unique end values for each axis. ((before, after),) yields same before and after end values for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.
reflect_type{‘even’, ‘odd’}, optional

Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.    Returns

padndarray

Padded array of rank equal to array with shape increased according to pad_width.     Notes  New in version 1.7.0.  For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis. The padding function, if used, should modify a rank 1 array in-place. It has the following signature: padding_func(vector, iaxis_pad_width, iaxis, kwargs)
 where
vectorndarray

A rank 1 array already padded with zeros. Padded values are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].
iaxis_pad_widthtuple

A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector.
iaxisint

The axis currently being calculated.
kwargsdict

Any keyword arguments the function requires.   Examples >>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
array([4, 4, 1, ..., 6, 6, 6])
 >>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, ..., 5, 5, 5])
 >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])
 >>> np.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
 >>> np.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
 >>> np.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
 >>> a = [[1, 2], [3, 4]]
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])
 >>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
 >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])
 >>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
 >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
 >>> np.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
 >>> def pad_with(vector, pad_width, iaxis, kwargs):
...     pad_value = kwargs.get('padder', 10)
...     vector[:pad_width[0]] = pad_value
...     vector[-pad_width[1]:] = pad_value
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, 2, pad_with)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])
>>> np.pad(a, 2, pad_with, padder=100)
array([[100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100,   0,   1,   2, 100, 100],
       [100, 100,   3,   4,   5, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100]])

 random_noise
skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs) [source]

Function to add random noise of various types to a floating-point image.  Parameters

imagendarray

Input image data. Will be converted to float.
modestr, optional

One of the following strings, selecting the type of noise to add:  ‘gaussian’ Gaussian-distributed additive noise.
 ‘localvar’ Gaussian-distributed additive noise, with specified

local variance at each point of image.    ‘poisson’ Poisson-distributed noise generated from the data. ‘salt’ Replaces random pixels with 1.
 ‘pepper’ Replaces random pixels with 0 (for unsigned images) or

-1 (for signed images).

‘s&p’ Replaces random pixels with either 1 or low_val, where

low_val is 0 for unsigned images or -1 for signed images.
 ‘speckle’ Multiplicative noise using out = image + n*image, where

n is Gaussian noise with specified mean & variance.
seedint, optional

If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons.
clipbool, optional

If True (default), the output will be clipped after noise applied for modes ‘speckle’, ‘poisson’, and ‘gaussian’. This is needed to maintain the proper image data range. If False, clipping is not applied, and the output may extend beyond the range [-1, 1].
meanfloat, optional

Mean of random distribution. Used in ‘gaussian’ and ‘speckle’. Default : 0.
varfloat, optional

Variance of random distribution. Used in ‘gaussian’ and ‘speckle’. Note: variance = (standard deviation) ** 2. Default : 0.01
local_varsndarray, optional

Array of positive floats, same shape as image, defining the local variance at every image point. Used in ‘localvar’.
amountfloat, optional

Proportion of image pixels to replace with noise on range [0, 1]. Used in ‘salt’, ‘pepper’, and ‘salt & pepper’. Default : 0.05
salt_vs_pepperfloat, optional

Proportion of salt vs. pepper noise for ‘s&p’ on range [0, 1]. Higher values represent more salt. Default : 0.5 (equal amounts)    Returns

outndarray

Output floating-point image data on range [0, 1] or [-1, 1] if the input image was unsigned or signed, respectively.     Notes Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside the valid image range. The default is to clip (not alias) these values, but they may be preserved by setting clip=False. Note that in this case the output may contain values outside the ranges [0, 1] or [-1, 1]. Use this option with care. Because of the prevalence of exclusively positive floating-point images in intermediate calculations, it is not possible to intuit if an input is signed based on dtype alone. Instead, negative values are explicitly searched for. Only if found does this function assume signed input. Unexpected results only occur in rare, poorly exposes cases (e.g. if all values are above 50 percent gray in a signed image). In this event, manually scaling the input to the positive domain will solve the problem. The Poisson distribution is only defined for positive integers. To apply this noise type, the number of unique values in the image is found and the next round power of two is used to scale up the floating-point result, after which it is scaled back down to the floating-point image range. To generate Poisson noise against a signed image, the signed image is temporarily converted to an unsigned image in the floating point domain, Poisson noise is generated, then it is returned to the original range.
 regular_grid
skimage.util.regular_grid(ar_shape, n_points) [source]

Find n_points regularly spaced along ar_shape. The returned points (as slices) should be as close to cubically-spaced as possible. Essentially, the points are spaced by the Nth root of the input array size, where N is the number of dimensions. However, if an array dimension cannot fit a full step size, it is “discarded”, and the computation is done for only the remaining dimensions.  Parameters

ar_shapearray-like of ints

The shape of the space embedding the grid. len(ar_shape) is the number of dimensions.
n_pointsint

The (approximate) number of points to embed in the space.    Returns

slicestuple of slice objects

A slice along each dimension of ar_shape, such that the intersection of all the slices give the coordinates of regularly spaced points.  Changed in version 0.14.1: In scikit-image 0.14.1 and 0.15, the return type was changed from a list to a tuple to ensure compatibility with Numpy 1.15 and higher. If your code requires the returned result to be a list, you may convert the output of this function to a list with: >>> result = list(regular_grid(ar_shape=(3, 20, 40), n_points=8))
      Examples >>> ar = np.zeros((20, 40))
>>> g = regular_grid(ar.shape, 8)
>>> g
(slice(5, None, 10), slice(5, None, 10))
>>> ar[g] = 1
>>> ar.sum()
8.0
>>> ar = np.zeros((20, 40))
>>> g = regular_grid(ar.shape, 32)
>>> g
(slice(2, None, 5), slice(2, None, 5))
>>> ar[g] = 1
>>> ar.sum()
32.0
>>> ar = np.zeros((3, 20, 40))
>>> g = regular_grid(ar.shape, 8)
>>> g
(slice(1, None, 3), slice(5, None, 10), slice(5, None, 10))
>>> ar[g] = 1
>>> ar.sum()
8.0

 regular_seeds
skimage.util.regular_seeds(ar_shape, n_points, dtype=<class 'int'>) [source]

Return an image with ~`n_points` regularly-spaced nonzero pixels.  Parameters

ar_shapetuple of int

The shape of the desired output image.
n_pointsint

The desired number of nonzero points.
dtypenumpy data type, optional

The desired data type of the output.    Returns

seed_imgarray of int or bool

The desired image.     Examples >>> regular_seeds((5, 5), 4)
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 2, 0],
       [0, 0, 0, 0, 0],
       [0, 3, 0, 4, 0],
       [0, 0, 0, 0, 0]])

 unique_rows
skimage.util.unique_rows(ar) [source]

Remove repeated rows from a 2D array. In particular, if given an array of coordinates of shape (Npoints, Ndim), it will remove repeated points.  Parameters

ar2-D ndarray

The input array.    Returns

ar_out2-D ndarray

A copy of the input array with repeated rows removed.    Raises

ValueErrorif ar is not two-dimensional.
   Notes The function will generate a copy of ar if it is not C-contiguous, which will negatively affect performance for large input arrays. Examples >>> ar = np.array([[1, 0, 1],
...                [0, 1, 0],
...                [1, 0, 1]], np.uint8)
>>> unique_rows(ar)
array([[0, 1, 0],
       [1, 0, 1]], dtype=uint8)

 view_as_blocks
skimage.util.view_as_blocks(arr_in, block_shape) [source]

Block view of the input n-dimensional array (using re-striding). Blocks are non-overlapping views of the input array.  Parameters

arr_inndarray

N-d input array.
block_shapetuple

The shape of the block. Each dimension must divide evenly into the corresponding dimensions of arr_in.    Returns

arr_outndarray

Block view of the input array.     Examples >>> import numpy as np
>>> from skimage.util.shape import view_as_blocks
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> B = view_as_blocks(A, block_shape=(2, 2))
>>> B[0, 0]
array([[0, 1],
       [4, 5]])
>>> B[0, 1]
array([[2, 3],
       [6, 7]])
>>> B[1, 0, 1, 1]
13
 >>> A = np.arange(4*4*6).reshape(4,4,6)
>>> A
array([[[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11],
        [12, 13, 14, 15, 16, 17],
        [18, 19, 20, 21, 22, 23]],
       [[24, 25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34, 35],
        [36, 37, 38, 39, 40, 41],
        [42, 43, 44, 45, 46, 47]],
       [[48, 49, 50, 51, 52, 53],
        [54, 55, 56, 57, 58, 59],
        [60, 61, 62, 63, 64, 65],
        [66, 67, 68, 69, 70, 71]],
       [[72, 73, 74, 75, 76, 77],
        [78, 79, 80, 81, 82, 83],
        [84, 85, 86, 87, 88, 89],
        [90, 91, 92, 93, 94, 95]]])
>>> B = view_as_blocks(A, block_shape=(1, 2, 2))
>>> B.shape
(4, 2, 3, 1, 2, 2)
>>> B[2:, 0, 2]
array([[[[52, 53],
         [58, 59]]],
       [[[76, 77],
         [82, 83]]]])

 view_as_windows
skimage.util.view_as_windows(arr_in, window_shape, step=1) [source]

Rolling window view of the input n-dimensional array. Windows are overlapping views of the input array, with adjacent windows shifted by a single row or column (or an index of a higher dimension).  Parameters

arr_inndarray

N-d input array.
window_shapeinteger or tuple of length arr_in.ndim

Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [1]) of the rolling window view. If an integer is given, the shape will be a hypercube of sidelength given by its value.
stepinteger or tuple of length arr_in.ndim

Indicates step size at which extraction shall be performed. If integer is given, then the step is uniform in all dimensions.    Returns

arr_outndarray

(rolling) window view of the input array.     Notes One should be very careful with rolling views when it comes to memory usage. Indeed, although a ‘view’ has the same memory footprint as its base array, the actual array that emerges when this ‘view’ is used in a computation is generally a (much) larger array than the original, especially for 2-dimensional arrays and above. For example, let us consider a 3 dimensional array of size (100, 100, 100) of float64. This array takes about 8*100**3 Bytes for storage which is just 8 MB. If one decides to build a rolling view on this array with a window of (3, 3, 3) the hypothetical size of the rolling view (if one was to reshape the view for example) would be 8*(100-3+1)**3*3**3 which is about 203 MB! The scaling becomes even worse as the dimension of the input array becomes larger. References
1
https://en.wikipedia.org/wiki/Hyperrectangle   Examples >>> import numpy as np
>>> from skimage.util.shape import view_as_windows
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> window_shape = (2, 2)
>>> B = view_as_windows(A, window_shape)
>>> B[0, 0]
array([[0, 1],
       [4, 5]])
>>> B[0, 1]
array([[1, 2],
       [5, 6]])
 >>> A = np.arange(10)
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(8, 3)
>>> B
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
 >>> A = np.arange(5*4).reshape(5, 4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> window_shape = (4, 3)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(2, 2, 4, 3)
>>> B
array([[[[ 0,  1,  2],
         [ 4,  5,  6],
         [ 8,  9, 10],
         [12, 13, 14]],
        [[ 1,  2,  3],
         [ 5,  6,  7],
         [ 9, 10, 11],
         [13, 14, 15]]],
       [[[ 4,  5,  6],
         [ 8,  9, 10],
         [12, 13, 14],
         [16, 17, 18]],
        [[ 5,  6,  7],
         [ 9, 10, 11],
         [13, 14, 15],
         [17, 18, 19]]]])


skimage.util.apply_parallel(function, array, chunks=None, depth=0, mode=None, extra_arguments=(), extra_keywords={}, *, dtype=None, multichannel=False, compute=None) [source]

Map a function in parallel across an array. Split an array into possibly overlapping chunks of a given depth and boundary type, call the given function in parallel on the chunks, combine the chunks and return the resulting array.  Parameters

functionfunction

Function to be mapped which takes an array as an argument.
arraynumpy array or dask array

Array which the function will be applied to.
chunksint, tuple, or tuple of tuples, optional

A single integer is interpreted as the length of one side of a square chunk that should be tiled across the array. One tuple of length array.ndim represents the shape of a chunk, and it is tiled across the array. A list of tuples of length ndim, where each sub-tuple is a sequence of chunk sizes along the corresponding dimension. If None, the array is broken up into chunks based on the number of available cpus. More information about chunks is in the documentation here.
depthint, optional

Integer equal to the depth of the added boundary cells. Defaults to zero.
mode{‘reflect’, ‘symmetric’, ‘periodic’, ‘wrap’, ‘nearest’, ‘edge’}, optional

type of external boundary padding.
extra_argumentstuple, optional

Tuple of arguments to be passed to the function.
extra_keywordsdictionary, optional

Dictionary of keyword arguments to be passed to the function.
dtypedata-type or None, optional

The data-type of the function output. If None, Dask will attempt to infer this by calling the function on data of shape (1,) * ndim. For functions expecting RGB or multichannel data this may be problematic. In such cases, the user should manually specify this dtype argument instead.  New in version 0.18: dtype was added in 0.18.
multichannelbool, optional

If chunks is None and multichannel is True, this function will keep only a single chunk along the channels axis. When depth is specified as a scalar value, that depth will be applied only to the non-channels axes (a depth of 0 will be used along the channels axis). If the user manually specified both chunks and a depth tuple, then this argument will have no effect.  New in version 0.18: multichannel was added in 0.18.
computebool, optional

If True, compute eagerly returning a NumPy Array. If False, compute lazily returning a Dask Array. If None (default), compute based on array type provided (eagerly for NumPy Arrays and lazily for Dask Arrays).    Returns

outndarray or dask Array

Returns the result of the applying the operation. Type is dependent on the compute argument.     Notes Numpy edge modes ‘symmetric’, ‘wrap’, and ‘edge’ are converted to the equivalent dask boundary modes ‘reflect’, ‘periodic’ and ‘nearest’, respectively. Setting compute=False can be useful for chaining later operations. For example region selection to preview a result or storing large data to disk instead of loading in memory.


skimage.util.compare_images(image1, image2, method='diff', *, n_tiles=(8, 8)) [source]

Return an image showing the differences between two images.  New in version 0.16.   Parameters

image1, image22-D array

Images to process, must be of the same shape.
methodstring, optional

Method used for the comparison. Valid values are {‘diff’, ‘blend’, ‘checkerboard’}. Details are provided in the note section.
n_tilestuple, optional

Used only for the checkerboard method. Specifies the number of tiles (row, column) to divide the image.    Returns

comparison2-D array

Image showing the differences.     Notes 'diff' computes the absolute difference between the two images. 'blend' computes the mean value. 'checkerboard' makes tiles of dimension n_tiles that display alternatively the first and the second image.


skimage.util.crop(ar, crop_width, copy=False, order='K') [source]

Crop array ar by crop_width along each dimension.  Parameters

ararray-like of rank N

Input array.
crop_width{sequence, int}

Number of values to remove from the edges of each axis. ((before_1, after_1), … (before_N, after_N)) specifies unique crop widths at the start and end of each axis. ((before, after),) or (before, after) specifies a fixed start and end crop for every axis. (n,) or n for integer n is a shortcut for before = after = n for all axes.
copybool, optional

If True, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

If copy==True, control the memory layout of the copy. See np.copy.    Returns

croppedarray

The cropped array. If copy=False (default), this is a sliced view of the input array.


skimage.util.dtype_limits(image, clip_negative=False) [source]

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.