API介绍

getRotationMatrix2D:生成旋转矩阵

Mat getRotationMatrix2D(Point2f center, double angle, double scale);

warpAffine:仿射变换

void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar());

示例1

void QuickDemo::rotato_demo(Mat &image) {
	Mat dst, M;
	int  w = image.cols;
	int h = image.rows;
	M = getRotationMatrix2D(Point2f(w / 2, h / 2), 45, 1.0);//旋转矩阵,围绕图像中心旋转45°
	warpAffine(image, dst, M, image.size(),INTER_LINEAR,0,Scalar(0,0,255));
	
	imshow("旋转45度", dst);
	imwrite("C:/Users/Desktop/opencv-0/warpAffine45.png",dst);
}

opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP

示例2

void QuickDemo::rotato_demo(Mat &image) {
	Mat dst, M;
	int  w = image.cols;
	int h = image.rows;
	M = getRotationMatrix2D(Point2f(w / 2, h / 2), 100, 1.0);//旋转矩阵,围绕图像中心旋转45°
	warpAffine(image, dst, M, image.size(),INTER_LINEAR,0,Scalar(0,0,255));
	
	imshow("旋转100度", dst);
	imwrite("C:/Users/Desktop/opencv-0/warpAffine45.png",dst);
}

opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP

怎么计算新图像的宽度高度

计算经过仿射变换或旋转后新图像的宽度和高度,尤其是在旋转图像时保持图像的完整性而不裁剪任何部分,需要一些几何计算。
opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP假设原图像的宽度为W,高度为H,旋转角度为theta,旋转后图像的新宽度W’和新高度H’。
1、将角度转换为弧度**:**
因为大多数数学函数使用弧度制,

theta_r=pi*theta/180

2、计算四个角点旋转后的位置:
先确定原图像的四个角点的坐标,然后根据旋转公式计算旋转后每个点的新坐标。旋转公式为:
opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP其中,(x, y)是原始坐标,(x’, y’)是旋转后的坐标。
3、计算新宽度和高度:
旋转后四个角点的最大和最小x、y坐标值之间的差分别给出了新图像的宽度W’和高度H’。

示例3

void QuickDemo::rotato_demo(Mat &image) {
	Mat dst, M;
	int  w = image.cols;
	int h = image.rows;
	M = getRotationMatrix2D(Point2f(w / 2, h / 2), 45, 1.0);//旋转矩阵,围绕图像中心旋转45°
	double sin = abs(M.at<double>(0, 1));
	double cos = abs(M.at<double>(0, 0));
	int nw = cos*w + sin*h;//新宽度
	int nh = sin*w + cos*h;//新高度
	M.at<double>(0, 2) = M.at<double>(0, 2) + (nw / 2 - w / 2);
	M.at<double>(1, 2) = M.at<double>(1, 2) + (nh / 2 - h / 2);

	//warpAffine(image, dst, M, image.size(),INTER_LINEAR,0,Scalar(0,0,255));
	warpAffine(image, dst, M, Size(nw,nh), INTER_LINEAR, 0, Scalar(0, 0, 255));
	imshow("旋转45度", dst);
	imwrite("C:/Users/Desktop/opencv-0/warpAffine2.png",dst);
}

opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP

示例4

void QuickDemo::rotato_demo(Mat &image) {
	Mat dst, M;
	int  w = image.cols;
	int h = image.rows;
	M = getRotationMatrix2D(Point2f(w / 2, h / 2), 100, 1.0);//旋转矩阵,围绕图像中心旋转100°
	double sin = abs(M.at<double>(0, 1));
	double cos = abs(M.at<double>(0, 0));
	int nw = cos*w + sin*h;//新宽度
	int nh = sin*w + cos*h;//新高度
	M.at<double>(0, 2) = M.at<double>(0, 2) + (nw / 2 - w / 2);
	M.at<double>(1, 2) = M.at<double>(1, 2) + (nh / 2 - h / 2);

	//warpAffine(image, dst, M, image.size(),INTER_LINEAR,0,Scalar(0,0,255));
	warpAffine(image, dst, M, Size(nw,nh), INTER_LINEAR, 0, Scalar(0, 0, 255));
	imshow("旋转100度", dst);
	imwrite("C:/Users/Desktop/opencv-0/warpAffine2.png",dst);
}

opencv中图像旋转—getRotationMatrix2D和warpAffine-LMLPHP

02-26 14:18