OpenCV 仿射变换

#include 
#include 
#include 

using namespace cv;
using namespace std;

#define WINDOW_NAME_SRC "【原始窗口】"
#define WINDOW_NAME_WARP "【经过Warp后的图像】"
#define WINDOW_NAME_WARP_AND_ROTATE "【经过Warp和Rotate后的图像】"

static void ShowHelpText();


int main()
{
    system("color 2A");

    ShowHelpText();
    string filepath = "D:\\pic\\";
    //【1】参数准备
    //定义两组点 代表两个三角形
    Point2f srcTriangle[3];
    Point2f dstTriangle[3];
    //定义Mat变量

    Mat rotMat(2, 3, CV_32FC1);
    Mat warpMat(2, 3, CV_32FC1);
    Mat srcImage, dstImage_warp, dstImage_warp_rotate;

    //【2】加载源图像并做初始化
    srcImage = imread(filepath + "1.jpg");
    if (!srcImage.data)
    {
        printf("加载图片失败,请确认目录下图像是否存在。。。");
        return -1;
    }
    //设置目标图像的大小和类型与源图像一致
    dstImage_warp.create(srcImage.rows, srcImage.cols, srcImage.type());

    //【3】设置源图像和目标图像上的三组点以计算仿射变换
    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】求得仿射变换
    warpMat = getAffineTransform(srcTriangle, dstTriangle);
    cout << warpMat << endl;
    cout <<" \n\n";
    //【5】对源图像应用仿射变换

    warpAffine(srcImage, dstImage_warp, warpMat, dstImage_warp.size());

    //【6】对源图像进行缩放后在旋转
    //计算图像中点旋转50°缩放因子0.6的旋转矩阵
    Point center = Point(dstImage_warp.cols / 2, dstImage_warp.rows / 2);
    double angle = -30.0;
    double scale = 0.6;

    rotMat = getRotationMatrix2D(center, angle, scale);
    cout << rotMat << endl;
    warpAffine(dstImage_warp, dstImage_warp_rotate, rotMat, dstImage_warp.size());

    namedWindow(WINDOW_NAME_SRC, 1);
    namedWindow(WINDOW_NAME_WARP, 1);
    namedWindow(WINDOW_NAME_WARP_AND_ROTATE, 1);

    imshow(WINDOW_NAME_SRC, srcImage);
    imshow(WINDOW_NAME_WARP, dstImage_warp);
    imshow(WINDOW_NAME_WARP_AND_ROTATE, dstImage_warp_rotate);

    waitKey();

    system("pause");
    return 0;
}

static void ShowHelpText()
{
    //
    printf("\n\n\n\t欢迎来到【仿射变换】示例程序 \n\n");
    printf("\t当前使用的OpenCV版本为OpenCV "CV_VERSION);
}

参考文献:
[1]. https://blog.csdn.net/poem_qianmo/article/details/33320997

你可能感兴趣的:(OpenCV)