Module: transform

AffineTransform

class skimage.transform.AffineTransform(matrix=None, scale=None, rotation=None, shear=None, translation=None)

Bases: skimage.transform._geometric.ProjectiveTransform

2D affine transformation of the form:

X = a0*x + a1*y + a2 =
  = sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2

Y = b0*x + b1*y + b2 =
  = sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2

where sx and sy are zoom factors in the x and y directions, and the homogeneous transformation matrix is:

[[a0  a1  a2]
 [b0  b1  b2]
 [0   0    1]]
Parameters:

matrix : (3, 3) array, optional

Homogeneous transformation matrix.

scale : (sx, sy) as array, list or tuple, optional

Scale factors.

rotation : float, optional

Rotation angle in counter-clockwise direction as radians.

shear : float, optional

Shear angle in counter-clockwise direction as radians.

translation : (tx, ty) as array, list or tuple, optional

Translation parameters.

Attributes

params (3, 3) array Homogeneous transformation matrix.
__init__(matrix=None, scale=None, rotation=None, shear=None, translation=None)
rotation
scale
shear
translation

PiecewiseAffineTransform

class skimage.transform.PiecewiseAffineTransform

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

affines list of AffineTransform objects Affine transformations for each triangle in the mesh.
inverse_affines list of AffineTransform objects Inverse affine transformations for each triangle in the mesh.
__init__()
estimate(src, dst)

Set the control points with which to perform the piecewise mapping.

Number of source and destination coordinates must match.

Parameters:

src : (N, 2) array

Source coordinates.

dst : (N, 2) array

Destination coordinates.

inverse(coords)

Apply inverse transformation.

Coordinates outside of the mesh will be set to - 1.

Parameters:

coords : (N, 2) array

Source coordinates.

Returns:

coords : (N, 2) array

Transformed coordinates.

PolynomialTransform

class skimage.transform.PolynomialTransform(params=None)

Bases: skimage.transform._geometric.GeometricTransform

2D transformation of the 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

__init__(params=None)
estimate(src, dst, order=2)

Set the transformation matrix with the explicit transformation parameters.

You can determine the over-, well- and under-determined parameters with the total least-squares method.

Number of source and destination coordinates must match.

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.

order : int, optional

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

inverse(coords)

ProjectiveTransform

class skimage.transform.ProjectiveTransform(matrix=None)

Bases: skimage.transform._geometric.GeometricTransform

Matrix 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)
estimate(src, dst)

Set the transformation matrix with the explicit transformation parameters.

You can determine the over-, well- and under-determined parameters with the total least-squares method.

Number of source and destination coordinates must match.

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.

inverse(coords)

Apply inverse transformation.

Parameters:

coords : (N, 2) array

Source coordinates.

Returns:

coords : (N, 2) array

Transformed coordinates.

SimilarityTransform

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

Bases: skimage.transform._geometric.ProjectiveTransform

2D similarity transformation of the form:

X = a0 * x - b0 * y + a1 =
  = m * x * cos(rotation) - m * y * sin(rotation) + a1

Y = b0 * x + a0 * y + b1 =
  = m * x * sin(rotation) + m * y * cos(rotation) + b1

where m is a zoom factor and the homogeneous transformation matrix is:

[[a0  b0  a1]
 [b0  a0  b1]
 [0   0    1]]
Parameters:

matrix : (3, 3) array, optional

Homogeneous transformation matrix.

scale : float, optional

Scale factor.

rotation : float, 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)
estimate(src, dst)

Set the transformation matrix with the explicit parameters.

You can determine the over-, well- and under-determined parameters with the total least-squares method.

Number of source and destination coordinates must match.

The transformation is defined as:

X = a0 * x - b0 * y + a1
Y = b0 * x + a0 * y + b1

These equations can be transformed to the following form:

0 = a0 * x - b0 * y + a1 - X
0 = b0 * x + a0 * y + b1 - 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 1 -y 0 -X]
       [y 0  x 1 -Y]
        ...
        ...
      ]
x.T = [a0 a1 b0 b1 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.

rotation
scale
translation
skimage.transform.downscale_local_mean(...) Down-sample N-dimensional image by local averaging.
skimage.transform.estimate_transform(ttype, ...) Estimate 2D geometric transformation parameters.
skimage.transform.frt2(a) Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array.
skimage.transform.hough_circle(image, radius) Perform a circular Hough transform.
skimage.transform.hough_ellipse Perform an elliptical Hough transform.
skimage.transform.hough_line Perform a straight line Hough transform.
skimage.transform.hough_line_peaks(hspace, ...) Return peaks in hough transform.
skimage.transform.ifrt2(a) Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array.
skimage.transform.integral_image(x) Integral image / summed area table.
skimage.transform.integrate(ii, r0, c0, r1, c1) Use an integral image to integrate over a given window.
skimage.transform.iradon(radon_image[, ...]) Inverse radon transform.
skimage.transform.iradon_sart(radon_image[, ...]) Inverse radon transform
skimage.transform.matrix_transform(coords, ...) Apply 2D matrix transform.
skimage.transform.probabilistic_hough_line Return lines from a progressive probabilistic line Hough transform.
skimage.transform.pyramid_expand(image[, ...]) Upsample and then smooth image.
skimage.transform.pyramid_gaussian(image[, ...]) Yield images of the Gaussian pyramid formed by the input image.
skimage.transform.pyramid_laplacian(image[, ...]) Yield images of the laplacian pyramid formed by the input image.
skimage.transform.pyramid_reduce(image[, ...]) Smooth and then downsample image.
skimage.transform.radon(image[, theta, circle]) Calculates the radon transform of an image given specified projection angles.
skimage.transform.rescale(image, scale[, ...]) Scale image by a certain factor.
skimage.transform.resize(image, output_shape) Resize image to match a certain size.
skimage.transform.rotate(image, angle[, ...]) Rotate image by a certain angle around its center.
skimage.transform.swirl(image[, center, ...]) Perform a swirl transformation.
skimage.transform.warp(image[, inverse_map, ...]) Warp an image according to a given coordinate transformation.
skimage.transform.warp_coords(coord_map, shape) Build the source coordinates for the output pixels of an image warp.

downscale_local_mean

skimage.transform.downscale_local_mean(image, factors, cval=0)

Down-sample N-dimensional image by local averaging.

The image is padded with cval if it is not perfectly divisible by the integer factors.

In contrast to the 2-D interpolation in skimage.transform.resize and skimage.transform.rescale this function may be applied to N-dimensional images and calculates the local mean of elements in each block of size factors in the input image.

Parameters:

image : ndarray

N-dimensional input image.

factors : array_like

Array containing down-sampling integer factor along each axis.

cval : float, optional

Constant padding value if image is not perfectly divisible by the integer factors.

Returns:

image : ndarray

Down-sampled image with same number of dimensions as input image.

Examples

>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> downscale_local_mean(a, (2, 3))
array([[ 3.5,  4. ],
       [ 5.5,  4.5]])

estimate_transform

skimage.transform.estimate_transform(ttype, src, dst, **kwargs)

Estimate 2D geometric transformation parameters.

You can determine the over-, well- and under-determined parameters with the total least-squares method.

Number of source and destination coordinates must match.

Parameters:

ttype : {‘similarity’, ‘affine’, ‘piecewise-affine’, ‘projective’, ‘polynomial’}

Type of transform.

kwargs : array or int

Function parameters (src, dst, n, angle):

NAME / TTYPE        FUNCTION PARAMETERS
'similarity'        `src, `dst`
'affine'            `src, `dst`
'piecewise-affine'  `src, `dst`
'projective'        `src, `dst`
'polynomial'        `src, `dst`, `order` (polynomial order,
                                          default order is 2)

Also see examples below.

Returns:

tform : GeometricTransform

Transform object containing the transformation parameters and providing access to forward and inverse transformation functions.

Examples

>>> import numpy as np
>>> from skimage import transform as tf
>>> # estimate transformation parameters
>>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
>>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))
>>> tform = tf.estimate_transform('similarity', src, dst)
>>> np.allclose(tform.inverse(tform(src)), src)
True
>>> # warp image using the estimated transformation
>>> from skimage import data
>>> image = data.camera()
>>> warp(image, inverse_map=tform.inverse) 
>>> # create transformation with explicit parameters
>>> tform2 = tf.SimilarityTransform(scale=1.1, rotation=1,
...     translation=(10, 20))
>>> # unite transformations, applied in order from left to right
>>> tform3 = tform + tform2
>>> np.allclose(tform3(src), tform2(tform(src)))
True

frt2

skimage.transform.frt2(a)

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

Parameters:

a : array_like

A 2-D square n x n integer array.

Returns:

FRT : 2-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 iff n is prime. [FRT] The idea for this algorithm is due to Vlad Negnevitski.

References

[FRT]A. Kingston and I. Svalbe, “Projective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006)

Examples

Generate a test image: Use a prime number for the array dimensions

>>> SIZE = 59
>>> img = np.tri(SIZE, dtype=np.int32)

Apply the Finite Radon Transform:

>>> f = frt2(img)

hough_circle

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

Perform a circular Hough transform.

Parameters:

image : (M, N) ndarray

Input image with nonzero values representing edges.

radius : ndarray

Radii at which to compute the Hough transform.

normalize : boolean, optional (default True)

Normalize the accumulator with the number of pixels used to draw the radius.

full_output : boolean, optional (default False)

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

Returns:

H : 3D 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.

hough_ellipse

skimage.transform.hough_ellipse()

Perform an elliptical Hough transform.

Parameters:

img : (M, N) ndarray

Input image with nonzero values representing edges.

threshold: int, optional (default 4) :

Accumulator threshold value.

accuracy : double, optional (default 1)

Bin size on the minor axis used in the accumulator.

min_size : int, optional (default 4)

Minimal major axis length.

max_size : int, optional

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

Returns:

result : ndarray with fields [(accumulator, y0, x0, 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

[R313]Xie, Yonghong, and Qiang Ji. “A new efficient ellipse detection method.” Pattern Recognition, 2002. Proceedings. 16th International Conference on. Vol. 2. IEEE, 2002

Examples

>>> 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)
[(10, 10.0, 8.0, 6.0, 0.0, 10.0)]

hough_line

skimage.transform.hough_line()

Perform a straight line Hough transform.

Parameters:

img : (M, N) ndarray

Input image with nonzero values representing edges.

theta : 1D ndarray of double

Angles at which to compute the transform, in radians. Defaults to -pi/2 .. pi/2

Returns:

H : 2-D ndarray of uint64

Hough transform accumulator.

theta : ndarray

Angles at which the transform was computed, in radians.

distances : ndarray

Distance values.

Notes

The origin is the top left corner of the original image. X and Y axis are horizontal and vertical edges respectively. The distance is the minimal algebraic distance from the origin to the detected line.

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)

plt.subplot(1, 2, 1)

plt.imshow(img, cmap=plt.cm.gray)
plt.title('Input image')

plt.subplot(1, 2, 2)
plt.imshow(out, cmap=plt.cm.bone,
           extent=(np.rad2deg(angles[-1]), np.rad2deg(angles[0]),
                   d[-1], d[0]))
plt.title('Hough transform')
plt.xlabel('Angle (degree)')
plt.ylabel('Distance (pixel)')

plt.subplots_adjust(wspace=0.4)
plt.show()

(Source code, png, pdf)

../_images/hough_tf.png

hough_line_peaks

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

Return peaks in 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_distance : int

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

min_angle : int

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

threshold : float

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

num_peaks : int

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

Returns:

hspace, angles, dists : tuple of array

Peak values in hough space, angles and distances.

Examples

>>> from skimage.transform import hough_line, hough_line_peaks
>>> from skimage.draw import line
>>> img = np.zeros((15, 15), dtype=np.bool_)
>>> rr, cc = line(0, 0, 14, 14)
>>> img[rr, cc] = 1
>>> rr, cc = line(0, 14, 14, 0)
>>> img[cc, rr] = 1
>>> hspace, angles, dists = hough_line(img)
>>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists)
>>> len(angles)
2

ifrt2

skimage.transform.ifrt2(a)

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

Parameters:

a : array_like

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

Returns:

iFRT : 2-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 iff n is prime. See [R314] for an overview. The idea for this algorithm is due to Vlad Negnevitski.

References

[R314](1, 2) 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