opencv仿射与透视变换

版权声明: https://blog.csdn.net/weixin_40614261/article/details/80636542
介绍仿射变换与透视变换的例程。

扫描二维码关注公众号,回复: 6173539 查看本文章

这是仿射变换和透视变换的简单程序,仿射和透视变换都是根据提供输入的点,对应输出的点的位置计算变换矩阵,根据变化矩阵与输入图像可以得出变换后的图形,但是如果你想自己初始话变化矩阵(随意设数)可以参考dst_perspective2=myPerspectiveTrans这个函数,还有一个是实现图像的旋转,可以任意取旋转中心和旋转角度。

   注意读入图片写入图片路径的格式。

               

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;

Mat AffineTrans(Mat src, Point2f* scrPoints, Point2f* dstPoints)
{
	Mat dst;
	Mat Trans = getAffineTransform(scrPoints, dstPoints);
	warpAffine(src, dst, Trans, Size(src.cols, src.rows));//, BORDER_REPLICATE这个函数是边缘补充函数
	return dst;
}
Mat PerspectiveTrans(Mat src, Point2f* scrPoints, Point2f* dstPoints)
{
	Mat dst;
	//int i, j;
	Mat Trans = getPerspectiveTransform(scrPoints, dstPoints);
	warpPerspective(src, dst, Trans, Size(src.cols, src.rows), CV_INTER_CUBIC, BORDER_REPLICATE);
	//cout << Trans << endl;可以打印矩阵
	return dst;
}
Mat myPerspectiveTrans(Mat src, Point2f* scrPoints, Point2f* dstPoints)
{
	Mat dst;
	float Trans_num[3][3] = { { 1, 0.001, 0 }, { 0.0005, 1, 0 }, { 0, 0, 1 } };
	Mat Trans(3, 3, CV_32F, Trans_num);//cout << Trans << endl;
	warpPerspective(src, dst, Trans, Size(src.cols, src.rows), CV_INTER_CUBIC);
	return dst;
}

int main()
{
	Mat img = imread("1.jpg");//或者是绝对路径imread("F:/test/1.jpg");注意/
	int img_height = img.rows;
	int img_width = img.cols;
	Point2f AffinePoints0[4] = { Point2f(100, 100), Point2f(100, img_height - 100), Point2f(img_width - 100, 100), Point2f(img_width - 100, img_height - 100) };
	Point2f AffinePoints1[4] = { Point2f(300, 300), Point2f(300, img_height - 300), Point2f(img_width - 240, 300), Point2f(img_width - 240, img_height - 300) };
	
	Mat dst_affine = AffineTrans(img, AffinePoints0, AffinePoints1);
	Mat dst_perspective1 = PerspectiveTrans(img, AffinePoints0, AffinePoints1);
	Mat dst_perspective2 = myPerspectiveTrans(img, AffinePoints0, AffinePoints1);

	Mat rotMat(2, 3, CV_32FC1);
	Point center = Point(img.cols / 2, img.rows / 2);
	double angle = -30.0;
	double scale = 1;
	Mat dst_rot;
	// 通过上面的旋转细节信息求得旋转矩阵  
	rotMat = getRotationMatrix2D(center, angle, scale);
	warpAffine(img, dst_rot, rotMat, img.size(), CV_INTER_CUBIC, BORDER_REPLICATE);// 旋转 

	imshow("origin", img);
	imwrite("origin.jpg", img);//可以保存到指定文件夹下,imwrite("F:/test/result/origin.jpg", img);
	imshow("affine", dst_affine);
	imwrite("affine.jpg", dst_affine);
	imshow("perspective1", dst_perspective1);
	imwrite("perspective1.jpg", dst_perspective1);
	imshow("perspective2", dst_perspective2);
	imwrite("perspective2.jpg", dst_perspective2);
	imshow("dst_rot", dst_rot);
	imwrite("dst_rot.jpg", dst_rot);
	waitKey();
}







猜你喜欢

转载自blog.csdn.net/weixin_40614261/article/details/80636542