1. 程式人生 > >影象幾何變換各項操作

影象幾何變換各項操作

/*
影象的幾何變換
*/
#include<opencv2\opencv.hpp>
#include<cxcore.h>
#include<iostream>
#include<cmath>
using namespace cv;
using namespace std;

int main() {
	Mat img_org = imread("D://圖片//5.jpg");
	if (img_org.empty()) {
		cout << "載入失敗!" << endl;
		return -1;
	}

	Mat img_s, img_t, img_r, img_Sk, img_Re_h, img_Re_v, img_Re_g, img_Pre;
	resize(img_org, img_s, Size(0, 0), 0.5, 0.5);   //縮小圖片

	Mat M = (Mat_<double>(2, 3) << 1, 0, 20, 0, 1, 50);
	warpAffine(img_org, img_t, M, img_org.size());        //根據變換矩陣M平移

	Mat M2 = getRotationMatrix2D(Point2f(img_org.cols / 2, img_org.cols / 2), 25, 1);
	warpAffine(img_org, img_r, M2, img_org.size());      //同上,當引數不同,變換矩陣不同時操作不同,此處為旋轉

	double m = 1 / tan(3.14 / 3);
	Mat M3 = (Mat_<double>(2, 3) << 1, m, 0, 0, 1, 0);
	warpAffine(img_org, img_Sk, M3, Size(img_org.cols + 0.5*img_org.cols, img_org.rows));   //同上,此處進行傾斜變換

	Mat M_h = (Mat_<double>(2, 3) << -1, 0, img_org.cols, 0, 1, 0);     //同上,水平反射
	Mat M_v = (Mat_<double>(2, 3) << 1, 0, 0, 0, -1, img_org.rows);       //垂直反射
	Mat M_g = (Mat_<double>(2, 3) << -1, 0, img_org.cols, 0, -1, img_org.rows);  //組合反射
	warpAffine(img_org, img_Re_h, M_h, img_org.size());
	warpAffine(img_org, img_Re_v, M_v, img_org.size());
	warpAffine(img_org, img_Re_g, M_g, img_org.size());

	Point2f img_verts[4], tem_verts[4];      //透視需要4點
	img_verts[0] = Point(195, 140);
	img_verts[1] = Point(410, 120);
	img_verts[2] = Point(220, 750);
	img_verts[3] = Point(400, 750);

	tem_verts[0] = Point(160, 100);
	tem_verts[1] = Point(530, 120);
	tem_verts[2] = Point(220, 750);
	tem_verts[3] = Point(400, 750);

	Mat M_Pre = getPerspectiveTransform(img_verts, tem_verts);     //透視變換
	warpPerspective(img_org, img_Pre, M_Pre, img_org.size());

	imshow("img_s", img_s);
	imshow("img_t", img_t);
	imshow("img_r", img_r);
	imshow("img_Sk", img_Sk);
	imshow("img_Re_h", img_Re_h);
	imshow("img_Re_v", img_Re_v);
	imshow("img_Re_g", img_Re_g);
	imshow("img_Pre", img_Pre);

	waitKey(0);
	destroyAllWindows;

	return 0;
}

執行結果: