您的位置:首页 > 运维架构

仿射变换及OpenCV实现

2015-11-15 11:36 453 查看

仿射变换及OpenCV实现

本文由 @lonelyrains出品,转载请注明出处。

文章链接: http://blog.csdn.net/lonelyrains/article/details/49847623

翻译自opencv官网,对原文有删改

仿射变换是什么

可以用矩阵相乘或者向量叠加到矩阵表示的所有操作

所以可以用来做的操作有:

– 旋转

– 平移(向量叠加)

– 缩放

数学表达

– 利用如下矩阵:

A=[a00a10a01a11]2×2,B=[b00b10]2×1

M=[AB]=[a00a10a01a11b00b10]2×3

对一个2D向量

X=[xy]

进行操作,可以列出如下等式:

T=A⋅[xy]+B

或者

T=M⋅[x,y,1]T

T=[a00x+a01y+b00a10x+a11y+b10]

如何得到仿射变换

由 T 的公式可知,一共有六个未知参数,所以需要3个2D点的映射关系,即一共六个一次方程,来决定平面。如下图:



用OpenCV实现

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>

using namespace cv;
using namespace std;

/// Global variables
char* source_window = "Source image";
char* warp_window = "Warp";
char* warp_rotate_window = "Warp + Rotate";

/** @function main */
int main( int argc, char** argv )
{
Point2f srcTri[3];
Point2f dstTri[3];

Mat rot_mat( 2, 3, CV_32FC1 );
Mat warp_mat( 2, 3, CV_32FC1 );
Mat src, warp_dst, warp_rotate_dst;

/// Load the image
src = imread( argv[1], 1 );

/// Set the dst image the same type and size as src
warp_dst = Mat::zeros( src.rows, src.cols, src.type() );

/// Set your 3 points to calculate the  Affine Transform
srcTri[0] = Point2f( 0,0 );
srcTri[1] = Point2f( src.cols - 1, 0 );
srcTri[2] = Point2f( 0, src.rows - 1 );

dstTri[0] = Point2f( src.cols*0.0, src.rows*0.33 );
dstTri[1] = Point2f( src.cols*0.85, src.rows*0.25 );
dstTri[2] = Point2f( src.cols*0.15, src.rows*0.7 );

/// Get the Affine Transform
warp_mat = getAffineTransform( srcTri, dstTri );

/// Apply the Affine Transform just found to the src image
warpAffine( src, warp_dst, warp_mat, warp_dst.size() );

/** Rotating the image after Warp */

/// Compute a rotation matrix with respect to the center of the image
Point center = Point( warp_dst.cols/2, warp_dst.rows/2 );
double angle = -50.0;
double scale = 0.6;

/// Get the rotation matrix with the specifications above
rot_mat = getRotationMatrix2D( center, angle, scale );

/// Rotate the warped image
warpAffine( warp_dst, warp_rotate_dst, rot_mat, warp_dst.size() );

/// Show what you got
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, src );

namedWindow( warp_window, CV_WINDOW_AUTOSIZE );
imshow( warp_window, warp_dst );

namedWindow( warp_rotate_window, CV_WINDOW_AUTOSIZE );
imshow( warp_rotate_window, warp_rotate_dst );

/// Wait until user exits the program
waitKey(0);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv 仿射变换