c++ visual processing—functions of affine transformation and two-dimensional rotation transformation matrix

Affine transformationcv::warpAffine

cv::warpAffine is a function in OpenCV used to perform affine transformation. An affine transformation is a linear transformation that can be used to perform operations such as translation, rotation, scaling, and shearing. The following is the basic usage of the cv::warpAffine function:

cv::warpAffine(src, dst, M, dsize, flags, borderMode, borderValue);
  • src: Input image.
  • dst: Output image, used to store the result of affine transformation.
  • M: 2×3 affine transformation matrix, containing transformation parameters.
  • dsize: The size of the output image.
  • flags: Interpolation method, usually used
    • cv::INTER_LINEAR performs bilinear interpolation.
    • cv::INTER_NEAREST nearest neighbor interpolation
    • cv::INTER_AREA area interpolation
    • cv::INTER_CUBIC cubic spline interpolation
    • cv::INTER_LANCZOS4 Lanczos interpolation
    • cv::CV_WARP_FILL_OUTLIERS Fills all pixels of the output image. If some pixels fall outside the boundaries of the input image, their values are set to fillval
    • cv::CV_WARP_INVERSE_MAP means M is the inverse transformation of the output image to the input image. Therefore it can be used directly for pixel interpolation. Otherwise, the warpAffine function gets the inverse transformation from the M matrix
  • borderMode: Border mode, optional parameter, defines the processing method when pixels exceed the image border, usually use cv::BORDER_CONSTANT or cv::BORDER_REPLICATE.
  • borderValue: Used when borderMode is cv::BORDER_CONSTANT to specify the pixel value outside the image boundary.

By providing an affine transformation matrix M, you can specify how the image is transformed, including translation, rotation, scaling, and shearing. Then, the cv::warpAffine function transforms the input image according to the given transformation parameters, and the output result is saved in dst.

The following is a simple example that demonstrates how to use cv::warpAffine to perform image translation operations:

#include <opencv2/opencv.hpp>

int main() {<!-- -->
    cv::Mat image = cv::imread("1.jpg", cv::IMREAD_COLOR);

    if (image.empty()) {<!-- -->
        std::cerr << "Unable to load image" << std::endl;
        return -1;
    }

    //Define affine transformation matrix (translation operation)
    cv::Mat warpMatrix = (cv::Mat_<double>(2, 3) << 1, 0, 50, 0, 1, 30);

    cv::Mat result;
    //Apply affine transformation
    cv::warpAffine(image, result, warpMatrix, image.size());

    cv::imshow("original image", image);
    cv::imshow("Image after affine transformation", result);
    cv::waitKey(0);

    return 0;
}

In this example, we define an affine transformation matrix warpMatrix that contains the parameters of the translation operation. We then applied the transformation to the original image using the cv::warpAffine function, producing the transformed result. You can modify the values in warpMatrix as needed to achieve different affine transformation effects.

Function of two-dimensional rotation transformation matrix: cv::getRotationMatrix2D

cv::getRotationMatrix2D is a function used in OpenCV to obtain a two-dimensional rotation transformation matrix. This function is used to construct an affine transformation matrix that is used to perform rotation operations on a two-dimensional image. The following is the basic usage of the cv::getRotationMatrix2D function:

cv::Mat cv::getRotationMatrix2D(cv::Point2f center, double angle, double scale);
  • center: The coordinates of the rotation center, usually the center point of the rotated image.
  • angle: Angle of rotation in degrees.
  • scale: Scaling factor, usually set to 1.0.

The function returns a 2×3 affine transformation matrix that contains rotation and scaling parameters.

Here is an example that demonstrates how to use the cv::getRotationMatrix2D function to construct a rotation transformation matrix and then apply that transformation matrix to rotate an image:

#include <opencv2/opencv.hpp>

int main() {<!-- -->
    cv::Mat image = cv::imread("1.jpg", cv::IMREAD_COLOR);

    if (image.empty()) {<!-- -->
        std::cerr << "Unable to load image" << std::endl;
        return -1;
    }

    //Rotation center coordinates
    cv::Point2f center(image.cols / 2.0, image.rows / 2.0);

    // Angle of rotation (in degrees)
    double angle = 30;

    // scaling factor
    double scale = 1.0;

    // Get the rotation transformation matrix
    cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, scale);

    cv::Mat result;
    //Apply affine transformation
    cv::warpAffine(image, result, rotationMatrix, image.size());

    cv::imshow("original image", image);
    cv::imshow("Rotated image", result);
    cv::waitKey(0);

    return 0;
}

In this example, we use the cv::getRotationMatrix2D function to get the rotation transformation matrix, and then apply the transformation matrix to the original image to achieve the rotation effect. You can adjust the center, angle and scale parameters as needed to perform different rotation and scaling operations.

Comprehensive case

#include <opencv2/opencv.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;
#include <iostream>
#include <fstream>
using namespace cv; //Contains the cv namespace
#include <opencv2/core/core.hpp>
#define WINDOW_NAME1 "[Original picture window] " //Macro defined for window title
#define WINDOW_NAME2 " [Image after Warp] " //Macro defined for window title
#define WINDOW_NAME3 " [Image after Warp and Rotate] " //Determine the window title
static void ShowHelpText();
/// [main() function]-------------------------- -
// Description: The entry function of the console application, our program starts execution from here
int main()
{<!-- -->
//【0】Change console font color
system("color 1A");
//【0】Display welcome and help text
ShowHelpText();
//【1】Parameter preparation
//Define two sets of points, representing two triangles
Point2f srcTriangle[3];
Point2f dstTriangle[3];
//Define some Mat variables
Mat rotMat(2, 3, CV_32FC1);
Mat warpMat(2, 3, CV_32FC1);
Mat srcImage, dstImage_warp, dstImage_warp_rotate;
//【2】Load the source image and do some initialization
srcImage = imread("1.jpg", 1);
if (!srcImage.data) {<!-- --> printf("Error reading image, please make sure there is an image specified by imread function in the directory~! \\
"); return false; }
//Set the size and type of the target image to be consistent with the source image
dstImage_warp = Mat::zeros(srcImage.rows, srcImage.cols, srcImage.type());
//【3】Set three groups of points on the source image and target image to calculate affine transformation
srcTriangle[0] = Point2f(0, 0);
srcTriangle[1] = Point2f(static_cast<float>(srcImage.cols - 1), 0);
srcTriangle[2] = Point2f(0, static_cast<float>(srcImage.rows - 1));
dstTriangle[0] = Point2f(static_cast<float>(srcImage.cols * 0.0), static_cast<float>(srcImage.rows * 0.33));
dstTriangle[1] = Point2f(static_cast<float>(srcImage.cols * 0.65), static_cast<float>(srcImage.rows * 0.35));
dstTriangle[2] = Point2f(static_cast<float>(srcImage.cols * 0.15), static_cast<float>(srcImage.rows * 0.6));
//[4] Obtain affine transformation
warpMat = getAffineTransform(srcTriangle, dstTriangle);
//【5】Apply the affine transformation just obtained to the source image
warpAffine(srcImage, dstImage_warp, warpMat, dstImage_warp.size());
//[6] Scale and then rotate the image
// Calculate the rotation matrix that rotates 50 degrees clockwise around the midpoint of the image with a scaling factor of 0.6
Point center = Point(dstImage_warp.cols / 2, dstImage_warp.rows / 2);
double angle = -30.0;
double scale = 0.8;
// Obtain the rotation matrix through the above rotation details information
rotMat = getRotationMatrix2D(center, angle, scale);
// Rotate the scaled image
warpAffine(dstImage_warp, dstImage_warp_rotate, rotMat, dstImage_warp.size());
//【7】Display results
imshow(WINDOW_NAME1, srcImage);
imshow(WINDOW_NAME2, dstImage_warp);
imshow(WINDOW_NAME3, dstImage_warp_rotate);
// Wait for the user to press any key to exit the program
waitKey(0);
return 0;
}
//1 [ShowHelpText() function]---------------------- -
// Description: Output some help information
static void ShowHelpText()
{<!-- -->
//Output some help information
printf("\\
\\
\\
\tWelcome to the [Affine Transformation] sample program~ \\
\\
");
//printf("\tThe OpenCV version currently used is OpenCV "CV_VERSION);
}