9. 仿射变换

一、仿射变换

仿射变换可以通过一系列的原子变换的复合来实现,包括:平移(Translation)、缩放(Scale)、翻转(Flip)、旋转(Rotation)和剪切(Shear)。

 (1)平移

 (2)缩放

 (3)剪切

shx = tx/h;

shy = ty/w;

其中h,w分别原图像高和宽;

(4)旋转

  

         (5)综合

   

 

 二、算法实现

Mat affine_transform(Mat& img, double a, double b, double c, double d, double e, double f)
{
    int width = img.cols;
    int height = img.rows;
    int channl = img.channels();

    double det = 1 / (a*d - b * c);
    int new_width = (int)(a*width);
    int new_height = (int)(d*height);

    cout << "new_width = " << new_width << endl;
    cout << "new_height = " << new_height << endl;
    int x_old, y_old;
    int x_new, y_new;

    Mat out = Mat::zeros(new_height, new_width, CV_8UC3);
    for (y_new = 0; y_new < new_height; y_new++)
    {
        for (x_new = 0; x_new < new_width; x_new++)
        {
            x_old = (int)(det*(d*x_new - b * y_new) - e);
            y_old = (int)(det*(-c * x_new + a * y_new) - f);
            if (x_old<0 || x_old>=width) 
                continue;
            if(y_old<0 || y_old>=height)
                continue;
            for (int c = 0; c < channl; c++)
            {
                out.at<Vec3b>(y_new, x_new)[c] = img.at<Vec3b>(y_old, x_old)[c];
            }
        }
    }
    return out;
}

 

 

原文地址:https://www.cnblogs.com/xingyuanzier/p/13325527.html