仿射变换:就是把一张图片做了平移-放大-旋转-错切等变换.被变换的矩阵就叫仿射变换矩阵。
下图为平移(25,25)后的对象对比图。
上代码:
Mat image, warpMat, result;
image = imread(path);
//1.平移-偏移量(25,25)
float warpMatValues[] = { 1.0,0.0,25.0,
0.0,1.0,25.0 };
warpMat = Mat(2, 3, CV_32F, warpMatValues);
Size outDim = image.size();//得到图像尺寸
warpAffine(image, result, warpMat, outDim);
imshow("result", result);
waitKey(0);
//2.宽度、高度放大两倍
float warpMatValues2[] = { 2.0,0.0,0.0,
0.0,2.0,0.0 };
warpMat = Mat(2, 3, CV_32F, warpMatValues2);
warpAffine(image, result, warpMat, Size(outDim.width * 2, outDim.height * 2));
imshow("result", result);
waitKey(0);
//3.旋转 角度
float angleInRadians = 30;
angleInRadians = 30 * 3.14 / 180.0;
float cosTheta = cos(angleInRadians);
float sinTheta = sin(angleInRadians);
float warpMatValues3[] = { cosTheta,sinTheta,0.0,-sinTheta,cosTheta,0.0 };
warpMat = Mat(2, 3, CV_32F, warpMatValues3);
warpAffine(image, result, warpMat, outDim);
imshow("result", result);
waitKey(0);
//4.基于中心点的旋转
float centerX = image.size().width / 2; //得到中心点
float centerY = image.size().height / 2;
float tx = (1 - cosTheta) * centerX - sinTheta * centerY;//得到中心点的偏移量
float ty = sinTheta * centerX + (1 - cosTheta) * centerY;
float warpMatValues4[] = { cosTheta,sinTheta,tx,-sinTheta,cosTheta,ty };
warpMat = Mat(2, 3, CV_32F, warpMatValues3);
warpAffine(image, result, warpMat, outDim);
imshow("result", result);
waitKey(0);
//5.图像错切
float shearAmount = 0.1;
float warpMatValues5[] = { 1, shearAmount, 0, 0, 1.0, 0 };
warpMat = Mat(2, 3, CV_32F, warpMatValues5);
warpAffine(image, result, warpMat, outDim);
imshow("result", result);
waitKey(0);
destroyAllWindows();