getPerspectiveTransform函数

来源:互联网 发布:mac速度慢怎么办 编辑:程序博客网 时间:2024/05/18 01:31

getPerspectiveTransform函数

函数作用:

根据输入和输出点获得图像透视变换的矩阵

函数的调用形式:

C++: Mat getPerspectiveTransform(InputArray src, InputArray dst)

InputArray src, InputArray dst:分别为变换的输入和输出点

分别四个点

透视变换后的图像不是平行的,



函数的运用:

解变换公式的函数:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[])  
输入原始图像和变换之后的图像的对应4个点,便可以得到变换矩阵。之后用求解得到的矩阵输入perspectiveTransform便可以对一组点进行变换:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void perspectiveTransform(InputArray src, OutputArray dst, InputArray m)  
注意这里src和dst的输入并不是图像,而是图像对应的坐标。应用前一篇的例子,做个相反的变换:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int main( )  
  2. {  
  3.     Mat img=imread("boy.png");  
  4.     int img_height = img.rows;  
  5.     int img_width = img.cols;  
  6.     vector<Point2f> corners(4);  
  7.     corners[0] = Point2f(0,0);  
  8.     corners[1] = Point2f(img_width-1,0);  
  9.     corners[2] = Point2f(0,img_height-1);  
  10.     corners[3] = Point2f(img_width-1,img_height-1);  
  11.     vector<Point2f> corners_trans(4);  
  12.     corners_trans[0] = Point2f(150,250);  
  13.     corners_trans[1] = Point2f(771,0);  
  14.     corners_trans[2] = Point2f(0,img_height-1);  
  15.     corners_trans[3] = Point2f(650,img_height-1);  
  16.   
  17.     Mat transform = getPerspectiveTransform(corners,corners_trans);  
  18.     cout<<transform<<endl;  
  19.     vector<Point2f> ponits, points_trans;  
  20.     for(int i=0;i<img_height;i++){  
  21.         for(int j=0;j<img_width;j++){  
  22.             ponits.push_back(Point2f(j,i));  
  23.         }  
  24.     }  
  25.   
  26.     perspectiveTransform( ponits, points_trans, transform);  
  27.     Mat img_trans = Mat::zeros(img_height,img_width,CV_8UC3);  
  28.     int count = 0;  
  29.     for(int i=0;i<img_height;i++){  
  30.         uchar* p = img.ptr<uchar>(i);  
  31.         for(int j=0;j<img_width;j++){  
  32.             int y = points_trans[count].y;  
  33.             int x = points_trans[count].x;  
  34.             uchar* t = img_trans.ptr<uchar>(y);  
  35.             t[x*3]  = p[j*3];  
  36.             t[x*3+1]  = p[j*3+1];  
  37.             t[x*3+2]  = p[j*3+2];  
  38.             count++;  
  39.         }  
  40.     }  
  41.     imwrite("boy_trans.png",img_trans);  
  42.   
  43.     return 0;  
  44. }  

得到变换之后的图片:


0 1
原创粉丝点击