Opencv學習筆記——仿射變換

主要通過Opencv中提供的cvWarpAffine和cv2DRotationMatrix函數來對圖像進行各種變換,具體功能實現如代碼:

#include "stdio.h"
#include "cv.h"
#include "highgui.h"

int main(int argc, char* argv[])
{
	CvPoint2D32f srcTri[3],dstTri[3];
	/*typedef struct CvPoint
{
int x;   X座標, 通常以0爲基點 
int y;   y座標, 通常以0爲基點 
}
CvPoint;
CvPoint2D32f則是CvPoint的變形,這是將x,y表示爲float型
	*/
	CvMat* rot_mat=cvCreateMat(2,3,CV_32FC1);
	CvMat* warp_mat=cvCreateMat(2,3,CV_32FC1);
	/*
	CvMat* cvCreateMat(int rows, int cols, int type);
	rows表示行數,cols表示列數,type表示矩陣的存儲的類型,通常以 CV_<比特數>(S|U|F)C<通道數>型式描述,如:
	CV_8UC1 表示8位無符號單通道矩陣, CV_32SC2表示32位有符號雙通道矩陣
	*/
	IplImage *src,*dst;
	src=cvLoadImage("Lena.png");
	dst=cvCloneImage(src);
	dst->origin=src->origin;
	cvZero(dst);
	srcTri[0].x=0;
    srcTri[0].y=0;
    srcTri[1].x=src->width-1;
	srcTri[1].y=0;
    srcTri[2].x=src->width-1;
	srcTri[2].y=src->height-1;
	dstTri[0].x=src->width*0;
    dstTri[0].y=src->height*0.33;
    dstTri[1].x=src->width*0.85;
    dstTri[1].y=src->height*0.25;
    dstTri[2].x=src->width*0.7;
    dstTri[2].y=src->height*0.7;
	cvGetAffineTransform(srcTri,dstTri,warp_mat);
	/*對圖像做仿射變換,獲取仿射變換的矩陣,這裏warp_mat便是從srcTri到dstTri的變換矩陣,在這過程中至少需要三個點,三個點定義了一個平行四邊形
	這三個點可以是圖像四個頂點中任意三個,但要明確變形後的三個點的位置並能夠對應上*/
	cvWarpAffine(src,dst,warp_mat);
	/*利用已經得到的仿射矩陣對圖像矩陣進行仿射,即dst=src*warp_mat */
    cvCopy(dst,src);
    CvPoint2D32f center=cvPoint2D32f(src->width/2,src->height/2);
	//結構體的定義與類構造函數是不同的
	double angle=-45;
	double scale=0.6;
	cv2DRotationMatrix(center,angle,scale,rot_mat);
	/*CvMat* cv2DrotationMatrix(CvPoint2D32f center,double angle,double scale,CvMat* map_matrix)
	這個函數是求對圖像進行旋轉和縮放的所要左乘的矩陣,其中center是設定的旋轉中心點,angle是旋轉角度,scale是縮放比例
	最後的map_matrix是我們要求的左乘矩陣
	*/
	cvWarpAffine(src,dst,rot_mat);
	//利用左乘矩陣進行變換
	cvNamedWindow("ImageShow",1);
	cvShowImage("ImageShow",dst);
	cvWaitKey(0);
	printf("Hello World!\n");
	return 0;
}

結果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章