BookNotesSlidesP-sets Syllabusdraft · v0.2.64.1

Problem set 6 · Homographies and Manual Panoramas

Due Wednesday October 28 at 9:00pm

Where to hand in. Submit at
https://compphoto-portal.fredopdurand.workers.dev/
Make sure your files sit in the asst directory at the root of the zip. The Submission section at the end of this handout has the details, along with the questions the form will ask you.

AI policy.

  • You are only allowed to use the class's AI assistant at
    https://comp-photo-book.pages.dev/
    embedded in the book, notes, slides, and problem sets.

    • it is built to help you think, not to hand you the answer

    • it knows our material: chapters, notes, demos, problem sets

  • Fine: brainstorming, explanations, editing, debugging, learning support.

  • Not fine: pasting problem statements into other (general) AI tools, asking for solutions to assigned problems, or submitting AI-written text, code, equations or analysis as your own.

  • Keep the line visible: distinguish your own work from AI-assisted work, and mention how the AI helped you (or not).

Extra credit. Percentages are of the regular points of your own version of the class, 6.8370 or 6.8371. An extension is worth what the handout says, 5% unless marked otherwise; for 6.8371, a part marked “6.8370 only” counts as extra credit at the percentage it gives. All extra credit on one problem set together is capped at 10%, so a problem set gives at most 110%.

Questions. Ask on Piazza, where the whole class sees the answer:
https://piazza.com/mit/fall2026/683701

Summary

Be careful. You will need to reuse this code for pset 7 when we will implement fully automatic panorama stitching and blending.

Also, take a look at homography.h for some potentially useful functions.

Homogeneous Coordinates

We will work with homogeneous coordinates to deal with the perspective transforms involved in panorama stitching. A point in the Euclidean plane $(x, y)^T$ is represented in the projective plane by the family of homogeneous coordinates $(xw, yw, w)^T$ for any non-zero scalar $w$. Since a family of points in the projective plane (for all non-zero $w$) map to the same point in the 2D plane, we will often choose $w=1$ as representative. We will think of it as the point in the screen space. Consult the class notes for more details.

Linear Algebra

In this problem set we will need some matrix algebra. We will use the Eigen package as our linear algebra library http://eigen.tuxfamily.org/index.php?title=Main_Page. We've implemented a few aliases for you in matrix.h. Please have a look at a6_main.cpp for examples on how to use matrices and vectors in testEigen, namely:

For more information about the Matrix class and functions, see matrix.h and the tests in a6_main.cpp.

For additional information see the Eigen tutorials https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html or this reference sheet https://eigen.tuxfamily.org/dox/AsciiQuickReference.txt.

Warp and Image with a Homography

Homography Matrix

$H$ is the matrix that transforms the source coordinates to the output coordinates (forward transformation).

Keep in mind that just like in Morphing we want to transform the output pixel coordinates into source pixel coordinates to be able to sample from the source image. This can be done using the inverse of a transform that maps source coordinates into output coordinates.

You apply a homography matrix to a 2D point $(x, y)$ in the output image by computing the product:

$$H^{-1} \left( \begin{array}{cc} x\\y\\1 \end{array}\right) = \left( \begin{array}{cc} x'\\y'\\w' \end{array}\right) \; .$$

This will result in the point $(x', y', w')$ in the input image. To get the final pixel coordinates of the projection plane in the input image, we then divide by the last projective coordinate:

$$\left( \begin{array}{cc} x'/w'\\y'/w' \end{array}\right) \;.$$
Pixel Boundaries

We will treat pixels coordinates outside the source image differently from previous problem sets. If we sample a location outside of the bounds of the source image, we want to leave the corresponding output pixels in the out image untouched. Therefore, you need to test if the warped coordinates are outside the source image before updating the pixel value.

This scheme might lead to stair artifacts int the output, but we will not worry about it now. In a later assignment, we will perform nice feathering at the boundaries between images.

  • 1.a

    Write a function void applyHomography(const Image &source,
    const Matrix &H, Image &out, bool bilinear=false)
    that modifies an image out by compositing on top of it the source image warped using the $3 \times 3$ homography matrix H. If the Boolean bilinear is True, use bilinear reconstruction, otherwise use simple nearest neighbor. Use H.inverse() to calculate $H^{-1}$ and clamp = true during interpolation. Note: this function does not return anything, it just modifies out, which is passed as a reference.

  • 1.b

    Create three small images of your own to use for testing and debugging applyHomography, and include them in your submission, named warp_1_… png to warp_3_… png under Input/debug/ as described below. Warp each with a homography $H$ you choose and can predict by hand, for example a translation by a fraction of a pixel, a rotation by $90^\circ$ about the image center, or a map of a square onto a trapezoid. For each one, say what the image is, why you chose it and its $H$, where you expect its corners to land, and how you expect the nearest-neighbor and bilinear results to differ. (Answer in the form)

Test your function on the provided green.png and poster.png images using testApplyHomography provided in a6_main.cpp, see Fig. 1.

Your test images.

Put the images you make in Input/debug/, lowercase, at most $256\times256$ pixels, named warp_<n>_<what>.png. make prepare copies Input/debug/ into your submission, so they travel with your code. Keep the code that makes them, their homographies and the calls to applyHomography, in a6_main.cpp, and write the results into Output/ under the same name with _out added (composite each onto a black image of a size you choose).

Figure 1. Composing image green.png with the image poster.png by applying a homography to the latter.

Compute Homography from 4 Pairs of Points

UI

In this section, a user provides correspondences between two images by clicking in a web interface (pano_ui.html), and your job is to infer the homography matrix that maps the 4 points from the first image to the corresponding 4 points in the other image. As in the morphing interface, points come in numbered pairs shown on both images, and a point can be moved to another pair or dragged, so the clicking order does not matter. Select points that are as well spread as possible for the computation to be well conditioned; in particular, avoid three points on a line. The interface flags points that are nearly on a line, and pairs arranged differently on the two images, which usually means two pairs are swapped. It writes the C++ array of CorrespondencePair to copy into your code.

Correspondences

The correspondences will be provided as an array of
CorrespondencePair, where each CorrespondencePair stores ($x1,y1,z1)$, the coordinates of the point in the first image and ($x2,y2,z2)$, the coordinates in the second. The test function testComputeHomography in a6_main.cpp gives an example of how to use it.

Homography scaling

A homography matrix is always defined up to a scaling factor. This means that $H$ and $kH$ represent the same geometric transformation for any non-zero scalar $k$. In this assignment, we will use a quick and dirty way to resolve the scale ambiguity and will assume that the bottom right coefficient of the homography is 1. This could create some problems if the true family of matrices $H$ had a zero there, but we will ignore this and leave the cleaner solution based on SVD as extra credit.

  • 2.a

    Write a function Matrix computeHomography(const
    CorrespondencePair correspondences[4])
    that takes a list of 4 point correspondences and returns a $3 \times 3$ homography matrix that maps the first point of each pair to the second point. That is, the homography maps from the first image to the second image.

  • 2.b

    Write a function testComputeHomographyKnown() in a6_main.cpp that calls computeHomography on four sets of four correspondences whose answer you know. Make three of them by applying a homography you choose (for example the identity, a translation, and a scaling combined with a translation) to four points of your own, and check that computeHomography returns the matrix you chose. In the fourth, put three of the four points on a line. Say which homographies you chose and whether you got them back, and what happened with the collinear points, and why. (Answer in the form)

The details of the algorithm are exposed below.

Outline of Steps

[(a)]

  1. We would like to solve for the homography that maps 4 points in the first image to the corresponding 4 points in the second image. In general, a homography $H$ correspondence equations can be written:

    $$H \left( \begin{array}{c}x \\ y \\ 1 \end{array} \right) = \left(\begin{array}{ccc} a & b & c \\ d & e & f \\ g & h & 1\end{array}\right) \left( \begin{array}{c}x \\ y \\ 1 \end{array} \right) =\left( \begin{array}{c}w'x' \\ w'y' \\ w' \end{array} \right)$$

    Where the unknowns are $a, b, c, d, e, f, g, h$, and we know $x, y$ and $x', y'$ for 4 sets of points. $w'$ is not known, but can be deduced easily from other quantities.

  2. You need to create a matrix $A$ and vector $B$ so that the 8 remaining coefficients ( $a, b, c, d, e, f, g, h$) of the homography are encoded in an 8-dimensional vector $x$ that satisfies $Ax=B$.

    You have two equations for each pair of corresponding points. To be clear, the $x$ vector in $Ax=B$ is actually $(a, b, c, d, e, f, g, h)^T$.

    Do not get confused between the $3 \times 3$ homography matrix and the $8 \times 8$ matrix $A$ for the linear system.

    We recommend that you write a subroutine that fills in two rows of the matrix and vector for a given correspondence pair, since the pattern is the same for all pairs of points.

  3. Solve the system with a solver, A.fullPivLu().solve(B), as recommended above. Computing A.inverse() and multiplying it with $B$ also works for this small system.

  4. Once you have solved the system, reshape your vector $x$ into a $3\times 3$ matrix.

Debugging

Homographies and projective spaces are big scary things. Do not try directly with the provided pairs of points. Use simpler cases. Think about pairs of correspondences where you can compute the matrix easily by hand. Try to infer the identity or a translation. You can also use testComputeHomography in a6_main.cpp to help test your function, it should give you the coefficients from testApplyHomography.

Bounding boxes

In the examples so far, the output image is the same size as one of the two inputs. But for panorama stitching, we want to create a bigger output image that encompasses all points from both images.

For this, we need to compute the size of the final output image. Additionally, the final image might be extended towards the negative coordinates with respect to the reference image. To handle this we will translate the reference, so that the pixel coordinates in the final output start at $(0,0)$.

Transform a bounding box

To compute the required size for one image, we forward-transform its four corners to the output space. We will represent the resulting required size as a bounding box, encoded by its minimum and maximum $x, y$ coordinates.

Be careful: whereas we usually need to consider the inverse warp to go from output coordinates into source ones, here we need to do the opposite and figure out where the bounds of the source project into the output space.

The four corners are the centers of the corner pixels: $(0,0)$, $(w-1,0)$, $(w-1,h-1)$ and $(0,h-1)$ for an image of width $w$ and height $h$. A BoundingBox is inclusive and holds integers: x1 and x2 are the first and last columns it covers, so it is x2-x1+1 pixels wide. The transformed corners are not integers; we convert their minimum and maximum to int the way C++ does, toward zero, which is what passing them to the BoundingBox constructor does.

  • 3

    Write a function BoundingBox computeTransformedBBox(int
    imwidth, int imheight, Matrix H)
    that takes an image size and a homography as input and returns the BoundingBox of the output coordinates.

Use testComputeTransformedBBox in a6_main.cpp to help test your function. Hint: implementing the optional Image drawBoundingBox(const Image &im, BoundingBox bbox) is useful for debugging bounding boxes.

Bounding box union

When stitching N images, the output is the union of the N bounding boxes.

  • 4

    Write a function BoundingBox bboxUnion(BoundingBox B1,
    BoundingBox B2)
    that takes two bounding boxes and returns a bigger bounding box that tightly encompasses the union of the bounding boxes.

Use testBBoxUnion in a6_main.cpp to help test your function.

Translation

After computing and merging the bounding boxes of the N images (including that of the reference), we often will have the situation where the upper-left corner of the bounding box has negative coordinates. This is illustrated in Fig. 2.

Figure 2. Bounding Boxes.

If the upper-left corner of the bounding box has negative coordinates, we need to translate the coordinate system of the reference image to set this corner to coordinates $(0, 0)$. The translation vector is simply the negative of this corner's coordinates. You can then obtain the translation homography matrix for translation by $(t_x t_y)^T$ as:

$$\left( \begin{array}{ccc} 1 & 0 & t_x \\ 0 & 1 & t_y \\ 0 & 0 & 1 \end{array} \right) \; .$$

  • 5

    Write a function Matrix makeTranslation(BoundingBox B) that takes a bounding box as input and returns a $3\times 3$ matrix corresponding to a translation that moves the upper left corner of the bounding box to $(0, 0)$.

Use testTranslate in a6_main.cpp to help test your function.

Putting it all together

  • 6

    Write a function Image stitch(const Image &im1, const Image &im2, const CorrespondencePair correspondences[4]) that takes two images and their point correspondences and outputs a stitched panorama in the coordinate system of the second (reference) image.

You first need to compute the homography between the two images. Then compute the resulting bounding box and translation matrix. Create a new black image of the size of the bounding box. Then use a combination of your translation and homography matrix to composite both images into the output. In its own coordinates, the reference image covers BoundingBox(0, w-1, 0, h-1), and the output image is x2-x1+1 by y2-y1+1 pixels for the union (x1, x2, y1, y2). Be careful that you also need to transform the second (reference) image to take the translation into account and that you need to combine the translation and the homography for the first image. Use the right matrix product!

Use testStitchStata, testStitchMonu, and testStitchGuedelon in a6_main.cpp to help test your function. See Fig. 3

Figure 3. Sample panoramas.

6.8370 only (Or 5% Extra Credit for 6.8371): Speed up Warping using Bounding Boxes

Accelerate the warping function by restricting the warping loop using the bounding box of each image.

  • 7

    Implement void applyHomographyFast(const Image &source,
    const Matrix &H, Image &out, bool bilinear=false)
    . Make sure you see a speed-up of at least 5x for the green and poster example. Use H.inverse() to calculate $H^{-1}$ and clamp = true during interpolation.

Use testApplyHomographyFast in a6_main.cpp to help test your function.

6.8370 only (Or 5% Extra Credit for 6.8371): Extra Test Cases and Images

  • 8

    In homography_extra_tests.h, similar to testStitchStata, write the following test cases:
    testStitchScience(), to stitch science-1.png and science-2.png;
    testStitchConvention(), to stitch convention-1.png and convention-2.png;
    testStitchBoston1(), to stitch boston1-1.png and boston1-2.png.

    Create output files science-stitch.png, and convention-stitch.png, and boston1-stitch.png. Copy these three images to the top of your assignment folder, beside a6_main.cpp (not in Output/): make prepare puts every PNG there into your submission. Use the provided javascript UI to choose the 4 point pairs needed for stitching.

Extra Credit (up to 10% total)

How to hand in extra credit.

Each extension comes with a test that runs it; an extension that is described but not tested earns at most about half its value.

extraCredit.cpp is compiled together with your required code, so if it does not compile, every regular test fails too: submit only extra credit code that builds. The grader keeps the images in Output/extra_credit/ (or Output/) and ignores PNG files anywhere else.

Submission

Turn in your files to the online submission system and make sure all your files are in the asst directory under the root of the zip file. If your code compiles on the submission system, it is organized correctly. The submission system will run code in your main function, but we will not use this code for grading. The submission system should also show you the image your code writes to the ./Output directory

Leave the input images we provide out of the zip: make prepare copies only the images you made yourself (Input/debug/, or a file a question asks for by name), the submission system supplies the provided ones, and grading uses its own copy. Uploads are limited to 100 MB.

In the submission system, there will be a form in which you should answer every written question this handout marks with “(Answer in the form)”, and these:

  • How long did the assignment take? (in minutes)

  • Potential issues with your solution and explanation of partial completion (for partial credit)

  • Any extra credit you may have implemented and their function signatures if applicable

  • Collaboration acknowledgment (you must write your own code)

  • What was most unclear/difficult?

  • What was most exciting?

◀▲⌂▶