天天看点

OpenCV学习几何变换-仿射变换

图像的放射变黄是指在空间直角坐标系中将一个二维坐标转换到另一个二维坐标,仿射变换是一种线性变换,放射变黄主要用来实现平移,缩放,翻转,旋转及剪裁等相关几何变换操作。

在使用OpenCV进行仿射变换时,会先计算一个仿射变换矩阵,获取仿射变换矩。

1.getRotationMatrix2D函数首先将角度转换为弧度,然后计算旋转矩阵。该函数需要已知旋转中心坐标(坐标原点为图像左上点),旋转角度(单位为度,顺时针为负,逆时针为正),缩放比例。与下面的getAffineTransform相比,无需知道变换后坐标,适用于一般情况下图像变换。

Mat getRotationMatrix2D(Point2f center, double angle, double scale) 
           

2.getAffineTransform,该函数需要已知变换前与变换后的坐标,返回相应的变换矩阵,适用于目标检测场合,通过检测得到的特征点进行图像匹配。

Mat getAffineTransform(InputArray src, InputArray dst)  
           

通过getAffineTransform和getRotationMatrix2D函数计算仿射变换矩阵后,就可以通过warpAffine函数对源图像进行仿射变换。

图像仿射变换的代码如下:

#include<opencv2/core/core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main(){
	//读入图像及验证读入正确
	Mat srcImage = imread("C:\\Users\\DELL\\Desktop\\五花肉.jpg");
	if (srcImage.empty())
		return -1;
	int nRows = srcImage.rows;
	int nCols = srcImage.cols;
	//定义仿射变换的二维点数组
	//源图像和目标图像对应映射的三个点
	Point2f srcPoint[3];
	Point2f resPoint[3];
	srcPoint[0] = Point2f(0, 0);
	srcPoint[1] = Point2f(nCols-1, 0);
	srcPoint[2] = Point2f(0, nRows - 1);
	resPoint[0] = Point2f(nCols * 0, nRows*0.33);
	resPoint[1] = Point2f(nCols * 0.85, nRows*0.25);
	resPoint[2] = Point2f(nCols * 0.15, nRows*0.7);
	//定义仿射变换矩阵2*3
	Mat warpMat(Size(2, 3), CV_32F);
	Mat resultImage = Mat::zeros(nRows, nCols, srcImage.type());
	//计算仿射变换矩阵,即仿射变换的2*3数组
	warpMat = getAffineTransform(srcPoint, resPoint);
	//根据仿射矩阵计算图像仿射变换
	warpAffine(srcImage, resultImage, warpMat, resultImage.size());
	imshow("resultImage1", resultImage);
	//设置仿射变换参数
	Point2f centerPoint = Point2f(nCols / 2, nRows / 2);
	double angle = -50;
	double scale = 0.7;
	//获取放射变换矩阵
	warpMat = getRotationMatrix2D(centerPoint, angle, scale);
	//对源图像角度仿射变换
	warpAffine(srcImage, resultImage, warpMat, resultImage.size());
	imshow("resultImage2", resultImage);
	waitKey(0);
	system("pause");
	return 0;
}
           

运行结果:

OpenCV学习几何变换-仿射变换
OpenCV学习几何变换-仿射变换