拉伸,扭曲,旋转图像的函数叫做几何变换函数。
对于平面区域,有两种方式的几何转换: 一种是基于2x3矩阵进行的变换,叫仿射变换; 另一种是基于3x3矩阵的变换,称透视变换或单位映射。
有两种情况用到仿射变换:1.有一幅想要转换的图像(或感兴趣的区域)。2.有一个点序列并想以此计算出变换。
稠密仿射变换:
WarpAffine
对图像做仿射变换
void cvWarpAffine( const CvArr* src, CvArr* dst, const CvMat* map_matrix, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) );
-
src
- 输入图像. dst
- 输出图像. map_matrix
- 2×3 变换矩阵 flags
-
插值方法和以下开关选项的组合:
- CV_WARP_FILL_OUTLIERS - 填充所有输出图像的象素。如果部分象素落在输入图像的边界外,那么它们的值设定为 fillval.
- CV_WARP_INVERSE_MAP - 指定 map_matrix 是输出图像到输入图像的反变换,因此可以直接用来做象素插值。否则, 函数从 map_matrix 得到反变换。
-
fillval
- 用来填充边界外面的值
函数 cvWarpAffine 利用下面指定的矩阵变换输入图像:
- 如果没有指定 CV_WARP_INVERSE_MAP , ,
- 否则,
函数与 cvGetQuadrangleSubPix 类似,但是不完全相同。 cvWarpAffine 要求输入和输出图像具有同样的数据类型,有更大的资源开销(因此对小图像不太合适)而且输出图像的部分可以保留不变。而 cvGetQuadrangleSubPix 可以精确地从8位图像中提取四边形到浮点数缓存区中,具有比较小的系统开销,而且总是全部改变输出图像的内容。
要变换稀疏矩阵,使用 cxcore 中的函数 cvTransform 。
GetAffineTransform
由三个不共线点计算仿射变换
CvMat* cvGetAffineTransform( const CvPoint2D32f* src, const CvPoint2D32f* dst, CvMat* map_matrix );
-
src
- 输入图像的三角形顶点坐标。 dst
- 输出图像的相应的三角形顶点坐标。 map_matrix
- 指向2×3输出矩阵的指针。
函数cvGetAffineTransform计算满足以下关系的仿射变换矩阵:
- 这里, dst(i) = (x'i,y'i),src(i) = (xi,yi),i = 0..2.
2DRotationMatrix
计算二维旋转的仿射变换矩阵
CvMat* cv2DRotationMatrix( CvPoint2D32f center, double angle, double scale, CvMat* map_matrix );
-
center
- 输入图像的旋转中心坐标 angle
- 旋转角度(度)。正值表示逆时针旋转(坐标原点假设在左上角). scale
- 各项同性的尺度因子 map_matrix
- 输出 2×3 矩阵的指针
函数 cv2DRotationMatrix 计算矩阵:
[ α β | (1-α)*center.x - β*center.y ] [ -β α | β*center.x + (1-α)*center.y ] where α=scale*cos(angle), β=scale*sin(angle)
该变换并不改变原始旋转中心点的坐标,如果这不是操作目的,则可以通过调整平移量改变其坐标(译者注:通过简单的推导可知,仿射变换的实现是首先将旋转中心置为坐标原点,再进行旋转和尺度变换,最后重新将坐标原点设定为输入图像的左上角,这里的平移量是center.x, center.y).
代码:
/*
* 仿射变换
*/
#include "highgui.h"
#include "cv.h"
void doAffine(IplImage* img)
{
CvPoint2D32f srcTri[3], dstTri[3];
CvMat* rot_mat = cvCreateMat(2,3, CV_32FC1);
CvMat* warp_mat = cvCreateMat(2,3,CV_32FC1);
IplImage* dst = cvCloneImage(img);
dst->origin = img->origin;
cvZero(dst);
srcTri[0].x = 0;
srcTri[0].y = 0;
srcTri[1].x = img->width-1;
srcTri[1].y = 0;
srcTri[2].x = 0;
srcTri[2].y = img->height-1;
dstTri[0].x = img->width * 0.0;
dstTri[0].y = img->height * 0.33;
dstTri[1].x = img->width * 0.85;
dstTri[1].y = img->height * 0.25;
dstTri[2].x = img->width * 0.15;
dstTri[2].y = img->height * 0.7;
cvGetAffineTransform(srcTri, dstTri, warp_mat); // 计算仿射矩阵
cvWarpAffine(img, dst, warp_mat);
cvCopy(dst, img);
// 计算旋转矩阵
CvPoint2D32f center = cvPoint2D32f(
img ->width/2,
img ->height/2
);
double angle = -50.0;
double scale = 0.6;
cv2DRotationMatrix(center, angle, scale, rot_mat);
cvWarpAffine(img, dst, rot_mat);
cvNamedWindow("Affine", 1);
cvShowImage("Affine", dst);
cvWaitKey(0);
cvReleaseImage(&dst);
cvReleaseMat(&rot_mat);
cvReleaseMat(&warp_mat);
}
输出结果: