1. 程式人生 > >opencv中的仿射變換(程式)

opencv中的仿射變換(程式)

(一)仿射變換的步驟:
1.得到仿射變換的運算元
2.進行仿射變換的操作。

仿射變換的操作:
1.平移操作:三個點的座標進行加運算
2.旋轉操作:中心點,旋轉角度,縮放比例構成仿射運算元
3.縮放:可以根據旋轉操作來,旋轉操作中的角度為0度,有縮放比例來進行縮放操作,也可以用三點來進行縮放的操作。
最重要的一點是隻要是重對映能操作的仿射變換均能進行操作的。
仿射變換的函式:warpAffine(輸入,輸出,仿射運算元,輸出影象的大小)
1.getAffineTransform 獲得簡單的仿射運算元
2.getRotationMatrix2D 獲得旋轉縮放的仿射運算元
仿射變換的程式:
#include <opencv2\opencv.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\highgui\highgui.hpp>

using namespace cv;
using namespace std;

void showHelpText()
{
printf("\n\n\n\n 當前的程式是仿射變換\n\n");
printf("當前的opencv的版本為:"CV_VERSION);
}
int main()
{
showHelpText();
Point2f srcTriangle[3];
Point2f dstTriangle[3];//定義兩組點,每組有三個點
Mat rotMat(2,3,CV_32FC1);
Mat warpMat(2,3,CV_32FC1);//定義兩個23的矩陣
Mat srcImg,dstImg,dstImg_warpRotate;
srcImg=imread(“2.jpg”);
if(!srcImg.data){
printf(“載入圖片失敗”);
return false;
}
dstImg=Mat::zeros(srcImg.size(),srcImg.type());
srcTriangle[0]=Point2f(0,0);
srcTriangle[1]=Point2f(static_cast(srcImg.cols-1),0);
srcTriangle[2]=Point2f(0,static_cast(srcImg.rows-1));
dstTriangle[0]=Point2f(static_cast(srcImg.cols

0.0),static_cast(srcImg.rows0.33));
dstTriangle[1]=Point2f(static_cast(srcImg.cols
0.65),static_cast(srcImg.rows0.35));
dstTriangle[2]=Point2f(static_cast(srcImg.cols
0.15),static_cast(srcImg.rows*0.6));
//求得仿射變換
warpMat=getAffineTransform(srcTriangle,dstTriangle);//仿射因子
warpAffine(srcImg,dstImg,warpMat,dstImg.size());
//對影象縮放後在進行旋轉,先仿射變換在進行旋轉仿射變換
/Point center=Point(dstImg.cols/2,dstImg.rows/2);
double angle=30.0;
double scale=0.8;
//在仿射變換的基礎上進行旋轉變換
rotMat=getRotationMatrix2D(center,angle,scale); //旋轉因子
warpAffine(dstImg,dstImg_warpRotate,rotMat,dstImg.size());
/
Point center=Point(srcImg.cols/2,srcImg.rows/2); //對原圖進行旋轉變換
double angle=0.0;
double scale=0.5;
//在仿射變換的基礎上進行旋轉變換
rotMat=getRotationMatrix2D(center,angle,scale); //旋轉因子
warpAffine(srcImg,dstImg_warpRotate,rotMat,srcImg.size()); imshow(“原始的影象”,srcImg);
imshow(“仿射變換的影象”,dstImg);
imshow(“仿射變換之後進行旋轉的影象”,dstImg_warpRotate);
waitKey(0);
return 1;
}