Warping Images into Alignment
Introduction to Image Warping
Welcome back! So far in this course, we have laid a lot of the groundwork. In Units 1 and 2, you learned how to find keypoints in two different images, match them, and use the RANSAC algorithm to calculate an accurate homography matrix.
Now, here in Unit 3, we are going to actually put that homography matrix to use. A homography becomes visible when we use it to warp pixels. To do this, we need to assign roles to our two images:
- Source image: The image being stretched and moved (usually the left image).
- Target image: The image that stays fixed in place (usually the right image).
Think of the source image as a photo printed on a rubber sheet. The homography matrix is the mathematical rule telling us exactly how to pull, stretch, and move that rubber sheet so its landmarks perfectly overlap with a second photo sitting on the table.
Let's learn how to apply this rule using Python and OpenCV.
Finding the New Canvas Boundaries
When we stretch and shift our source image, its pixels will move to new coordinates. A common problem is that some pixels might be pushed into negative coordinates (off the top or left of the screen) or past the right edge. If we do not make our image "canvas" larger to make room, the warped image will be cut off.
To fix this, we first need to determine exactly where the four corners of our source image will be located after the warp. Let's start by defining the original corners of both images.
In OpenCV, functions that process geometric points often require a very specific 3D shape. We use .reshape(-1, 1, 2) to format our corners into the exact shape OpenCV expects.
Next, we will apply our homography rule to the source_corners to see where they move. We use cv2.perspectiveTransform, which applies the mathematical rule to specific coordinate points rather than full images.
Now we have a list of all eight corners. To find our new canvas size, we simply need to find the absolute minimum and maximum x and y values among all these points.
Because the source image was shifted left and up to align with the target, our xmin and ymin values are negative!
