Perspective Transform
In this exercise, you will implement a perspective transform that places one image into another. An example of the expected result is shown at the end of the exercise.
A perspective transform is defined by
After the transformation, , , and are homogeneous coordinates. The corresponding Cartesian coordinates are
Fig. 1: Projective transformation between two images.
Consider a projective transform defined by four corresponding point pairs.
Let be points in the input image and their corresponding points in the output image. In Fig. 1, the points are chosen as the corners of the input image.
Let the coordinates of be , and let the coordinates of the corresponding point be .
Define
and
From Eq. (1), each point correspondence gives
From the third row of Eq. (2),
Substituting this expression into the first two rows gives
Written explicitly, Eq. (3) becomes
Four point correspondences provide eight equations, but the perspective matrix contains nine coefficients. Since a projective transform is defined only up to a non-zero scale factor, one coefficient can be fixed. For example, set
Move the first column of the system in Eq. (4) to the right-hand side. The resulting system is
Using all four point correspondences produces an linear system that can be solved for the remaining eight coefficients.
Implementation Details
Use the following point correspondences, listed clockwise starting from the top-left corner:
- Flag:
(0, 0),(323, 0),(323, 215),(0, 215) - Building:
(69, 107),(227, 76),(228, 122),(66,134)
Use OpenCV’s cv::solve function to solve the system of linear equations.
When generating the transformed image, remember that the transformed coordinates are generally real-valued. Use an appropriate interpolation method when sampling the source image.
Expected Output
Fig. 2: Input images (top left and bottom); output image after the perspective transform (top right).