图像旋转
图像旋转是非常重要的数字图像常规处理,在深度学习中也会应用图像旋转进行图像增强。图像旋转一般分为两种,第一种要保持图像大小,但是会丢失部分图像信息;第二种是根据旋转角度建立大小变化的新的图像,这可以保持图像信息的完整性。如下代码是对这两种情况分别进行操作的。
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
Mat src = imread("bench.jpg");
imshow("Src Image", src);
double angle = 45; // 逆时针旋转45度
Point2f center((src.cols - 1) / 2.0, (src.rows - 1) / 2.0);
// rotation_matix = [cos sin 0
// -sin cos 0]
Mat rotation_matix = getRotationMatrix2D(center, angle, 1.0); // 旋转中心, 旋转角度,缩放比例
// 保持图像大小不变,但是会丢失部分图像信息
Mat rotationImg;
warpAffine(src, rotationImg, rotation_matix, Size(src.cols, src.rows), INTER_LINEAR, 0);
imshow("rotation Image", rotationImg);
更改图像大小,保留所有图像的信息
//double cosValue = abs(rotation_matix.at<double>(0, 0));
//double sinValue = abs(rotation_matix.at<double>(0, 1));
//int newcols = cosValue * src.cols + sinValue * src.rows;
//int newrows = sinValue * src.cols + cosValue * src.rows;
为了使旋转中心在图像正中心需要修改旋转矩阵,修改为
rotation_matix = [cos sin 0+newcols - src.cols
-sin cos 0+newrows - src.rows]
//rotation_matix.at<double>(0, 2) += (newcols * 0.5 - src.cols * 0.5);
//rotation_matix.at<double>(1, 2) += (newrows * 0.5 - src.rows * 0.5);
//Mat rotationImg1;
//warpAffine(src, rotationImg1, rotation_matix, Size(newcols, newrows), INTER_LINEAR, 0);
//imshow("rotation Img1", rotationImg1);
waitKey(0);
}
注释部分是第二种情况,需要的话将此部分注释去掉同时注释掉上面三行代码即可。从实际项目来看,第一种情况应用是比较多的。