1 #include <iostream>
2 #include<opencv2/opencv.hpp>
3 #include <deque>
4 using namespace std;
5 using namespace cv;
6 void Rotate_vertical(Mat &src, Mat &dst, float angle)//src原图像,dst输出图像,旋转角度
7 {
8 float rad = (float)(angle / 180.0 * CV_PI);
9
10 //填充图像
11 int maxBorder = (int)(max(src.cols, src.rows)* 1.414); //即为sqrt(2)*max
12 int dx = (maxBorder - src.cols) / 2;
13 int dy = (maxBorder - src.rows) / 2;
14 copyMakeBorder(src, dst, dy, dy, dx, dx, BORDER_CONSTANT);
15
16 //旋转
17 Point2f center((float)(dst.cols / 2), (float)(dst.rows / 2));
18 Mat affine_matrix = getRotationMatrix2D(center, angle, 1.0);//求得旋转矩阵
19 warpAffine(dst, dst, affine_matrix, dst.size());
20
21 //计算图像旋转之后包含图像的最大的矩形
22 float sinVal = abs(sin(rad));
23 float cosVal = abs(cos(rad));
24 Size targetSize((int)(src.cols * cosVal + src.rows * sinVal),
25 (int)(src.cols * sinVal + src.rows * cosVal));
26
27 //剪掉多余边框
28 int x = (dst.cols - targetSize.width) / 2;
29 int y = (dst.rows - targetSize.height) / 2;
30 Rect rect(x, y, targetSize.width, targetSize.height);
31 dst = Mat(dst, rect);
32 }
33 int main()
34 {
35 Mat img = imread("1", 0);
36 Mat img_rotate;
37 float angle = 78.7;
38 Rotate_vertical(img, img_rotate, angle);
39 imshow("旋转后的图像", img_rotate);
40 waitKey(0);
41 }