1. 程式人生 > >OpenCV3之——影象仿射變換warpAffine()和getRotationMatrix2D()

OpenCV3之——影象仿射變換warpAffine()和getRotationMatrix2D()

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

#define WINDOW_NAME1 "原始圖視窗"
#define WINDOW_NAME2 "經過warp後的影象"
#define WINDOW_NAME3 "經過warp和rotate後的影象"

int main() {
	system("color 1A");
	//定義兩組點,表示兩個三角形
	Point2f srcTriangle[3];
	Point2f dstTriangle[3];

	//定義一些Mat變數
	Mat rotMat(2, 3, CV_32FC1);
	Mat warpMat(2, 3, CV_32FC1);
	Mat srcImage, dstImage_warp, dstImage_warp_rotate;

	srcImage = imread("1.jpg",1);
	if (!srcImage.data) {
		printf("讀取圖片錯誤!\n");
		return false;
	}
	dstImage_warp = Mat::zeros(srcImage.rows, srcImage.cols, srcImage.type());

	//設定源影象和目標影象上的三組點以計算仿射變換
	srcTriangle[0] = Point2f(0, 0);
	srcTriangle[1] = Point2f(static_cast<float>(srcImage.cols - 1), 1);
	srcTriangle[2] = Point2f(0, static_cast<float>(srcImage.rows - 1));

	dstTriangle[0] = Point2f(static_cast<float>(srcImage.cols*0.0), static_cast<float>(srcImage.rows*0.33));
	dstTriangle[1] = Point2f(static_cast<float>(srcImage.cols*0.65), static_cast<float>(srcImage.rows*0.35));
	dstTriangle[2] = Point2f(static_cast<float>(srcImage.cols*0.15), static_cast<float>(srcImage.rows*0.6));

	//求得仿射變換
	warpMat = getAffineTransform(srcTriangle, dstTriangle);

	//對原影象應用上面求得的仿射變換
	warpAffine(srcImage, dstImage_warp, warpMat, dstImage_warp.size());

	//對影象進行縮放後再旋轉
	//計算繞影象中心順時針旋轉50度縮放因子為0.6的旋轉矩陣
	Point center = Point(dstImage_warp.cols / 2, dstImage_warp.rows / 2);
	double angle = -30.0;
	double scale = 0.8;
	//通過上面的旋轉細節資訊求得選裝矩陣
	rotMat = getRotationMatrix2D(center, angle, scale);

	//旋轉已縮放後的影象
	warpAffine(dstImage_warp, dstImage_warp_rotate, rotMat, dstImage_warp.size());

	//顯示結果
	imshow(WINDOW_NAME1, srcImage);
	imshow(WINDOW_NAME2, dstImage_warp);
	imshow(WINDOW_NAME3, dstImage_warp_rotate);

	waitKey(0);
	return 0;
}