仿射变换与透视变换

仿射变换保证物体形状的“平直性”和“平行性”。透视变换不能保证物体形状的“平行性”。仿射变换是透视变换的特殊形式。

将透视变换写成3*3矩阵形式,即为M;

以下面这张图为例,实现仿射变换,包括旋转,平移,缩放,剪切,以图像中心为变换中心;

仿射变换

旋转(逆时针旋转30度)

Mat M=Mat::eye(3,3, CV_32FC1);
float alpha=PI/6;
float tx=0;
float ty=0;
float scale=1;

M.at<float>(0, 0) = cos(alpha);
M.at<float>(0, 1) = sin(alpha);
M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y;
M.at<float>(1, 0) = -sin(alpha);
M.at<float>(1, 1) = cos(alpha);
M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y;
M.at<float>(2, 0) = 0;
M.at<float>(2, 1) = 0;
M.at<float>(2, 2) = 1;

 

平移(水平和垂直方向各向右平移20个像素)

 Mat M=Mat::eye(3,3, CV_32FC1);
    float alpha=0;
    float tx=20;
    float ty=20;
    float scale=0;

    M.at<float>(0, 0) = cos(alpha);
    M.at<float>(0, 1) = sin(alpha);
    M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y + tx;
    M.at<float>(1, 0) = -sin(alpha);
    M.at<float>(1, 1) = cos(alpha);
    M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y + ty;
    M.at<float>(2, 0) = 0;
    M.at<float>(2, 1) = 0;
    M.at<float>(2, 2) = 1;

 

缩放(图像缩小1/2)

Mat M=Mat::eye(3,3, CV_32FC1);
    float alpha=0;
    float tx=0;
    float ty=0;
    float scale=0.5;

    M.at<float>(0, 0) = cos(alpha) * scale;
    M.at<float>(0, 1) = sin(alpha) * scale;
    M.at<float>(0, 2) = (1-cos(alpha)* scale)*center.x - sin(alpha)* center.y* scale + tx;
    M.at<float>(1, 0) = -sin(alpha) * scale;
    M.at<float>(1, 1) = cos(alpha)* scale;
    M.at<float>(1, 2) = sin(alpha)* center.x* scale +(1-cos(alpha)* scale)*center.y + ty;
    M.at<float>(2, 0) = 0;
    M.at<float>(2, 1) = 0;
    M.at<float>(2, 2) = 1;

错切变换(剪切变换):

 

Mat M=Mat::eye(3,3, CV_32FC1);
    float alpha=PI/12;
    float tx=0;
    float ty=0;
    float scale=1;

    M.at<float>(0, 0) = 1;
    M.at<float>(0, 1) = sin(alpha);
    M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y;
    M.at<float>(1, 0) = 0;
    M.at<float>(1, 1) = 1;
    M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y;
    M.at<float>(2, 0) = 0;
    M.at<float>(2, 1) = 0;
    M.at<float>(2, 2) = 1;

 

 

透视变换(透视变换不保证平行性)

Mat M=Mat::eye(3,3, CV_32FC1);
    float alpha=0;
    float tx=0;
    float ty=0;
    float scale=1;

    M.at<float>(0, 0) = cos(alpha);
    M.at<float>(0, 1) = sin(alpha);
    M.at<float>(0, 2) =(1-cos(alpha))*center.x - sin(alpha)* center.y + tx;
    M.at<float>(1, 0) = -sin(alpha);
    M.at<float>(1, 1) = cos(alpha);
    M.at<float>(1, 2) =sin(alpha)* center.x +(1-cos(alpha))*center.y + ty;
    M.at<float>(2, 0) = 0.001;
    M.at<float>(2, 1) = 0.001;
    M.at<float>(2, 2) = 1;

上述操作使用同一个opencv接口函数:warpPerspective(srcImg, dstImg, M, Size(width, height));

 

posted @ 2017-08-19 23:18  一度逍遥  阅读(12458)  评论(1编辑  收藏  举报