Image.warp_affine#

Image.warp_affine(M: Any, inverse: bool = False, size: tuple[int, int] | None = None, bgcolor: Any = None, dst: Any = None) Self[source]#

Affine warp of image

Parameters:
  • M (ndarray(2,3), SE2) – affine matrix

  • inverse (bool, optional) – warp with inverse of M, defaults to False

  • size (array_like(2), optional) – size of output image, defaults to size of input image

  • bgcolor (scalar, str, array_like, optional) – background color, defaults to None

  • dst (Image) – destination image, optional

Returns:

warped image

Return type:

Image

Return a copy of the image with an affine warp applied. Pixels in the output image that correspond to pixels outside the input image are set to bgcol.

\[\begin{split}Y_{u,v} = X_{u^\prime, v^\prime} \mbox{, where } \begin{pmatrix} u^\prime \\ v^\prime \end{pmatrix} = \mat{M} \begin{pmatrix} u \\ v \\ 1 \end{pmatrix}\end{split}\]

Example:

>>> from machinevisiontoolbox import Image
>>> import numpy as np
>>> from spatialmath import SE2
>>> img = Image.Read('monalisa.png')
>>> M = np.diag([0.25, 0.25, 1]) * SE2(100, 200)  # scale and translate
>>> M
array([[ 0.25,  0.  , 25.  ],
       [ 0.  ,  0.25, 50.  ],
       [ 0.  ,  0.  ,  1.  ]])
>>> out = img.warp_affine(M, bgcolor=np.nan)  # unmapped pixels are NaNs
>>> out.disp(badcolor="r")  # display warped image with NaNs as red
<matplotlib.image.AxesImage object at 0x7f076d2e78c0>

Note

Only the first two rows of M are used.

An alternative approach is to warp the image into another image by using the dst option. In this case no bgcolor or size should be specified. Only those pixels that correspond to pixels in the input image will be changed in dst. This can be useful when warping multiple images into the same output image.

>>> from machinevisiontoolbox import Image
>>> import numpy as np
>>> from spatialmath import SE2
>>> img = Image.Read('monalisa.png')
>>> out = Image.Constant(0, size=(1000, 200))
>>> for i in range(10):
...     M = SE2(90 * (i + 1), 100) * SE2(i * np.pi * 2 / 15) * np.diag([0.1, 0.1, 1])  # scale, rotate, translate
...     img.warp_affine(M, dst=out)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
Image(size=(1000, 200), dtype=uint8, nplanes=3, colororder=R:G:B)
>>> out.disp()
<matplotlib.image.AxesImage object at 0x7f076d3bfad0>
Seealso:

warp opencv.warpAffine