Skip to main content
`Ctrl`+`K`
scipy.ndimage.

# affine_transform

scipy.ndimage.affine_transform(input, matrix, offset=0.0, output_shape=None, output=None, order=3, mode='constant', cval=0.0, prefilter=True)

  Apply an affine transformation.

  Given an output image pixel index vector `o`, the pixel value is determined from the input image at position `np.dot(matrix, o) + offset`.

  This does ‘pull’ (or ‘backward’) resampling, transforming the output space to the input to locate data. Affine transformations are often described in the ‘push’ (or ‘forward’) direction, transforming input to output. If you have a matrix for the ‘push’ transformation, use its inverse (`numpy.linalg.inv`) in this function.

  Parameters:
    input array_like

      The input array.

    matrix ndarray

      The inverse coordinate transformation matrix, mapping output coordinates to input coordinates. If `ndim` is the number of dimensions of `input`, the given matrix must have one of the following shapes:

      - `(ndim, ndim)`: the linear transformation matrix for each output coordinate.

      - `(ndim,)`: assume that the 2-D transformation matrix is diagonal, with the diagonal specified by the given value. A more efficient algorithm is then used that exploits the separability of the problem.

      - `(ndim + 1, ndim + 1)`: assume that the transformation is specified using homogeneous coordinates [1]. In this case, any value passed to `offset` is ignored.

      - `(ndim, ndim + 1)`: as above, but the bottom row of a homogeneous transformation matrix is always `[0, 0, ..., 1]`, and may be omitted.

    offset float or sequence, optional

      The offset into the array where the transform is applied. If a float, offset is the same for each axis. If a sequence, offset should contain one value for each axis.

    output_shape tuple of ints, optional

      Shape tuple.

    output array or dtype, optional

      The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.

    order int, optional

      The order of the spline interpolation, default is 3. The order has to be in the range 0-5.

    mode{‘reflect’, ‘grid-mirror’, ‘constant’, ‘grid-constant’, ‘nearest’, ‘mirror’, ‘grid-wrap’, ‘wrap’}, optional

      The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘constant’. Behavior for each valid value is as follows (see additional plots and details on boundary modes):

      ‘reflect’ (d c b a | a b c d | d c b a)

        The input is extended by reflecting about the edge of the last pixel. This mode is also sometimes referred to as half-sample symmetric.

      ‘grid-mirror’

        This is a synonym for ‘reflect’.

      ‘constant’ (k k k k | a b c d | k k k k)

        The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. No interpolation is performed beyond the edges of the input.

      ‘grid-constant’ (k k k k | a b c d | k k k k)

        The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter. Interpolation occurs for samples outside the input’s extent as well.

      ‘nearest’ (a a a a | a b c d | d d d d)

        The input is extended by replicating the last pixel.

      ‘mirror’ (d c b | a b c d | c b a)

        The input is extended by reflecting about the center of the last pixel. This mode is also sometimes referred to as whole-sample symmetric.

      ‘grid-wrap’ (a b c d | a b c d | a b c d)

        The input is extended by wrapping around to the opposite edge.

      ‘wrap’ (b c d b c | a b c d | b c a b c)

        The input is extended by wrapping around to the opposite edge, but in a way such that the last point and initial point exactly overlap. In this case it is not well defined which sample will be chosen at the point of overlap.

        For the example illustrated above, the edge values `a` and `d` overlap, while the inner pattern `b c` repeats. The example demonstrates one possible output, while `b c a b c | a b c d | b c d b c` is another, since either `a` or `d` may occur at each point of overlap.

    cval scalar, optional

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

    prefilter bool, optional

      Determines if the input array is prefiltered with `spline_filter` before interpolation. The default is True, which will create a temporary float64 array of filtered values if `order > 1`. If setting this to False, the output will be slightly blurred if `order > 1`, unless the input is prefiltered, i.e. it is the result of calling `spline_filter` on the original input.

  Returns:
    affine_transform ndarray

      The transformed input.

  Notes

  The given matrix and offset are used to find for each point in the output the corresponding coordinates in the input by an affine transformation. The value of the input at those coordinates is determined by spline interpolation of the requested order. Points outside the boundaries of the input are filled according to the given mode.

  Changed in version 0.18.0: Previously, the exact interpretation of the affine transformation depended on whether the matrix was supplied as a 1-D or a 2-D array. If a 1-D array was supplied to the matrix parameter, the output pixel value at index `o` was determined from the input image at position `matrix * (o + offset)`.

  For complex-valued input, this function transforms the real and imaginary components independently.

  Added in version 1.6.0: Complex-valued support added.

  Array API Standard Support

  `affine_transform` has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable `SCIPY_ARRAY_API=1` and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.

  Library | CPU | GPU
  --- | --- | ---
  NumPy | ✅ | n/a
  CuPy | n/a | ✅
  PyTorch | ✅ | ⛔
  JAX | ⚠️ no JIT | ⛔
  Dask | ⚠️ computes graph | n/a

  See Support for the array API standard for more information.

  References

  [1]

  https://en.wikipedia.org/wiki/Homogeneous_coordinates

  Examples

  Use `affine_transform` to stretch an image:

      >>> from scipy.ndimage import affine_transform
      >>> from scipy.datasets import face
      >>> from matplotlib import pyplot as plt
      >>> import numpy as np
      >>> im = face(gray=True)
      >>> matrix = (0.5, 2)
      >>> im2 = affine_transform(im, matrix)
      >>> plt.imshow(im2)
      >>> plt.show()

  Rotate an image by 90 degrees and project it onto an expanded canvas:

      >>> matrix = ((0, 1), (1, 0))
      >>> im3 = affine_transform(im, matrix, output_shape=(1024, 1024))
      >>> plt.imshow(im3)
      >>> plt.show()

  Offset the rotation so that the image is centred:

      >>> output_shape = (1200, 1200)
      >>> offset = (np.array(im.shape) - output_shape) / 2
      >>> im4 = affine_transform(im, matrix, offset=offset, output_shape=output_shape)
      >>> plt.imshow(im4)
      >>> plt.show()