Image Warping

Image warping geometrically transforms an image so that its pixels move to new locations according to a mapping function or transformation matrix . Warping changes the domain of the image (where values sit), not the values themselves. Filtering does the opposite. Write for the map from a point of the source image to a point of the destination image . Then

In forward warping, each pixel of is sent to its new position in . The landing point is usually between pixels. Distributing its color among the neighboring destination pixels is called splatting. Forward warping is simple, but it leaves holes where stretches the image and sends several source pixels to one destination pixel where shrinks it.

Instead of pushing source pixels forward, inverse warping loops over the destination pixels and pulls each value from in the source. Since usually lies between pixels, its value is interpolated from nearby samples with nearest neighbor, bilinear, Gaussian or bicubic interpolation. Inverse warping is usually the better choice, because every output pixel gets exactly one value and no holes appear. It requires an invertible warp, which is not always available. For an affine or projective , the inverse is a matrix of the same class. The output canvas comes from transforming the four source corners with and taking their bounding box.

The Direction of

The lecture first writes warping as . In that formula maps output coordinates to input coordinates. Later slides write , where maps source to destination, which is the convention of this note. The two ‘s are inverses of each other. Libraries also differ. scipy.ndimage.affine_transform expects the output-to-input matrix, in (row, column) order. Check the direction on one point before warping a whole image.

Intuition

Forward warping scatters. Each source pixel carries its color to wherever sends it. The landing points do not line up with the destination grid, so some destination pixels receive nothing and others receive several values. With the landing points scattered irregularly, there is no regular neighborhood to interpolate from. Inverse warping gathers instead. Each destination pixel looks up where it came from in the source. That location lies on or between the points of a regular grid, where interpolation is well defined. The figure shows both for a scale by .

\usepackage{tikz}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=0.6cm,y=0.6cm,>=latex]
\node at (3.7,5.4) {forward warping};
\foreach \i in {0,1,2} \foreach \j in {0,1,2} \fill[cold] (\i,\j+1) circle (2.5pt);
\node at (1,-0.9) {\small source $f$};
\draw[->,thick] (2.5,2) -- (3.6,2) node[midway,above] {$T$};
\foreach \i in {0,...,4} \foreach \j in {0,...,4} {
  \pgfmathsetmacro{\e}{int(mod(\i,2)+mod(\j,2))}
  \ifnum\e=0 \fill[cold] (\i+4,\j) circle (2.5pt); \else \draw[hot,thick] (\i+4,\j) circle (2.5pt); \fi
}
\node at (6,-0.9) {\small destination $g$: $16$ holes};
\begin{scope}[shift={(11,0)}]
\node at (3.7,5.4) {inverse warping};
\foreach \i in {0,1,2} \foreach \j in {0,1,2} \fill[mid] (\i,\j+1) circle (2.5pt);
\draw[hot,thin] (1,1+1) -- (1.5,1.5) -- (2,1+1);
\draw[hot,thin] (1,0+1) -- (1.5,1.5) -- (2,0+1);
\fill[hot] (1.5,1.5) circle (2.5pt);
\node[hot,below] at (1.5,0.8) {\small interpolate};
\node at (1,-0.9) {\small source $f$};
\foreach \i in {0,...,4} \foreach \j in {0,...,4} \fill[cold] (\i+4,\j) circle (2.5pt);
\draw[cold,very thick] (3+4,1) circle (5pt);
\draw[->,thick,hot] (6.7,1.3) .. controls (5,3.2) and (3,3) .. (1.65,1.7);
\node[hot,above] at (4.6,3) {$T^{-1}$};
\node[align=center] at (6.3,-1.2) {\small destination $g$:\\ \small $(3,1)$ pulls from $(1.5, 0.5)$};
\end{scope}
\end{tikzpicture}
\end{document}

Properties

(Inverse Warping in Code) The loop runs over output pixels, maps each one back with , and interpolates.

The plain loop below matches the lecture’s description. Here is the source image, is a matrix from source to destination coordinates, and coordinates are (column, row).

def inverse_warp(f, T, out_h, out_w):
    g = zeros((out_h, out_w, f.shape[2]))
    T_inv = inv(T)                                   # output -> input
    for y_out in range(out_h):                       # loop over OUTPUT pixels
        for x_out in range(out_w):
            x, y, w = T_inv @ [x_out, y_out, 1]
            x, y = x / w, y / w                      # w stays 1 for affine T
            if 0 <= x <= f_width - 1 and 0 <= y <= f_height - 1:
                g[y_out, x_out] = interpolate(f, x, y)   # nearest, bilinear, ...
    return g                                          # pixels outside f stay 0

The lecture’s “life-hack” removes both loops. Build the coordinates of every output pixel at once with np.meshgrid, stack them into a array of homogeneous points, and multiply by once. Then divide by and call one interpolation routine on all points, such as scipy.ndimage.map_coordinates, cv2.remap, or MATLAB’s interp2. These routines take (row, column) or in different orders, so the order must be checked.

(Holes and Pile-Ups) Forward warping misses output pixels in proportion to the stretch, and inverse warping aliases when it shrinks.

A forward warp that scales by in both directions hits at most a fraction of the output pixels. Splatting each value over a small footprint fills gaps only up to the footprint’s size. Where shrinks the image, many source pixels land on one output pixel. The simple loop then keeps whichever value was written last. A better rule adds up colors and weights and divides at the end. Inverse warping has the mirror-image problem. When shrinks the image a lot, neighboring output pixels pull from source points several pixels apart and skip the detail in between. That is aliasing, and the fix is to blur the source before warping, for example by sampling from a coarser level of an image pyramid.

(Output Canvas) The images of the four source corners give the size and offset of the output.

An affine map sends the source rectangle to a parallelogram, so the four transformed corners bound all of the output. Take the minimum and maximum of their coordinates to get the canvas size. If the minimum is negative, compose a shift into the map, , and then invert . Output pixels whose preimage falls outside the source get a fill value, often , plus an alpha value of that later blending can use. The same corner rule works for a homography as long as at all four corners. Then no point of the rectangle is sent to infinity.

(Warps Without Inverses) When is unavailable, define the warp in the output-to-input direction from the start.

An affine map with a singular linear part flattens the image onto a line and has no inverse. A warp defined by sending each source pixel along its own motion vector has no closed-form inverse either. Morphing avoids the problem by never inverting a forward map. For each triangle of the output shape, it directly builds the affine map from that triangle to the matching source triangle. Each such map is invertible as long as no triangle collapses to a line.

Examples

(Easy) Forward Warping a Thumbnail by a Factor of 2

A thumbnail is enlarged to by forward warping with and no splatting.

(Medium) The Canvas for a Rotated Photo

A photo is rotated by about its center with the lecture’s . In image coordinates, with pointing down, this rotation looks clockwise on screen.

(Medium) Passing the Right Matrix to SciPy

The goal is to enlarge a array by with scipy.ndimage.affine_transform(img, M, output_shape=(8, 8), order=1), where order=1 means bilinear interpolation.

See Also