OpenCV  4.2.0
Open Source Computer Vision
Affine Transformations

Prev Tutorial: Remapping
Next Tutorial: Histogram Equalization

Goal

In this tutorial you will learn how to:

Theory

What is an Affine Transformation?

  1. A transformation that can be expressed in the form of a matrix multiplication (linear transformation) followed by a vector addition (translation).
  2. From the above, we can use an Affine Transformation to express:

    1. Rotations (linear transformation)
    2. Translations (vector addition)
    3. Scale operations (linear transformation)

    you can see that, in essence, an Affine Transformation represents a relation between two images.

  3. The usual way to represent an Affine Transformation is by using a \(2 \times 3\) matrix.

    \[ A = \begin{bmatrix} a_{00} & a_{01} \\ a_{10} & a_{11} \end{bmatrix}_{2 \times 2} B = \begin{bmatrix} b_{00} \\ b_{10} \end{bmatrix}_{2 \times 1} \]

    \[ M = \begin{bmatrix} A & B \end{bmatrix} = \begin{bmatrix} a_{00} & a_{01} & b_{00} \\ a_{10} & a_{11} & b_{10} \end{bmatrix}_{2 \times 3} \]

    Considering that we want to transform a 2D vector \(X = \begin{bmatrix}x \\ y\end{bmatrix}\) by using \(A\) and \(B\), we can do the same with:

    \(T = A \cdot \begin{bmatrix}x \\ y\end{bmatrix} + B\) or \(T = M \cdot [x, y, 1]^{T}\)

    \[T = \begin{bmatrix} a_{00}x + a_{01}y + b_{00} \\ a_{10}x + a_{11}y + b_{10} \end{bmatrix}\]

How do we get an Affine Transformation?

  1. We mentioned that an Affine Transformation is basically a relation between two images. The information about this relation can come, roughly, in two ways:
    1. We know both \(X\) and T and we also know that they are related. Then our task is to find \(M\)
    2. We know \(M\) and \(X\). To obtain \(T\) we only need to apply \(T = M \cdot X\). Our information for \(M\) may be explicit (i.e. have the 2-by-3 matrix) or it can come as a geometric relation between points.
  2. Let's explain this in a better way (b). Since \(M\) relates 2 images, we can analyze the simplest case in which it relates three points in both images. Look at the figure below:

    the points 1, 2 and 3 (forming a triangle in image 1) are mapped into image 2, still forming a triangle, but now they have changed notoriously. If we find the Affine Transformation with these 3 points (you can choose them as you like), then we can apply this found relation to all the pixels in an image.

Code

  • What does this program do?
    • Loads an image
    • Applies an Affine Transform to the image. This transform is obtained from the relation between three points. We use the function cv::warpAffine for that purpose.
    • Applies a Rotation to the image after being transformed. This rotation is with respect to the image center
    • Waits until the user exits the program

Explanation

  • Load an image:
  • Affine Transform: As we explained in lines above, we need two sets of 3 points to derive the affine transform relation. Have a look:

You may want to draw these points to get a better idea on how they change. Their locations are approximately the same as the ones depicted in the example figure (in the Theory section). You may note that the size and orientation of the triangle defined by the 3 points change.

  • Armed with both sets of points, we calculate the Affine Transform by using OpenCV function cv::getAffineTransform :

We get a \(2 \times 3\) matrix as an output (in this case warp_mat)

  • We then apply the Affine Transform just found to the src image

with the following arguments:

  • src: Input image
  • warp_dst: Output image
  • warp_mat: Affine transform
  • warp_dst.size(): The desired size of the output image

We just got our first transformed image! We will display it in one bit. Before that, we also want to rotate it...

  • Rotate: To rotate an image, we need to know two things:

    1. The center with respect to which the image will rotate
    2. The angle to be rotated. In OpenCV a positive angle is counter-clockwise
    3. Optional: A scale factor

    We define these parameters with the following snippet:

  • We generate the rotation matrix with the OpenCV function cv::getRotationMatrix2D , which returns a \(2 \times 3\) matrix (in this case rot_mat)
  • We now apply the found rotation to the output of our previous Transformation:
  • Finally, we display our results in two windows plus the original image for good measure:
  • We just have to wait until the user exits the program

Result

  • After compiling the code above, we can give it the path of an image as argument. For instance, for a picture like:

    after applying the first Affine Transform we obtain:

    and finally, after applying a negative rotation (remember negative means clockwise) and a scale factor, we get:

cv::Mat::rows
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition: mat.hpp:2086
cv::String
std::string String
Definition: cvstd.hpp:150
cv::Point_< float >
cv::getAffineTransform
Mat getAffineTransform(const Point2f src[], const Point2f dst[])
Calculates an affine transform from three pairs of the corresponding points.
cv::samples::findFile
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
cv::Mat::zeros
static MatExpr zeros(int rows, int cols, int type)
Returns a zero array of the specified size and type.
cv::hal::warpAffine
void warpAffine(int src_type, const uchar *src_data, size_t src_step, int src_width, int src_height, uchar *dst_data, size_t dst_step, int dst_width, int dst_height, const double M[6], int interpolation, int borderType, const double borderValue[4])
cv::warpAffine
void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar &borderValue=Scalar())
Applies an affine transformation to an image.
cv::Point2f
Point_< float > Point2f
Definition: types.hpp:192
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
highgui.hpp
cv::quality::quality_utils::scale
void scale(cv::Mat &mat, const cv::Mat &range, const T min, const T max)
Definition: quality_utils.hpp:90
cv::imread
Mat imread(const String &filename, int flags=IMREAD_COLOR)
Loads an image from a file.
cv::Mat::empty
bool empty() const
Returns true if the array has no elements.
cv::Mat::cols
int cols
Definition: mat.hpp:2086
cv::getRotationMatrix2D
Mat getRotationMatrix2D(Point2f center, double angle, double scale)
Calculates an affine matrix of 2D rotation.
Definition: imgproc.hpp:2429
cv::Mat::size
MatSize size
Definition: mat.hpp:2108
imgcodecs.hpp
cv::dnn::print
static void print(const MatShape &shape, const String &name="")
Definition: shape_utils.hpp:188
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::Point
Point2i Point
Definition: types.hpp:194
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:792
cv::imshow
void imshow(const String &winname, const ogl::Texture2D &tex)
Displays OpenGL 2D texture in the specified window.
cv::Mat::type
int type() const
Returns the type of a matrix element.
cv::CommandLineParser
Designed for command line parsing.
Definition: utility.hpp:797
cv::getAffineTransform
Mat getAffineTransform(InputArray src, InputArray dst)
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:52
imgproc.hpp