如何使用 C++ 在 OpenCV 中旋转图像?

opencvc++server side programmingprogramming

使用 OpenCV 的内置函数旋转图像非常简单。要旋转图像,我们需要使用"highgui.hpp"和"imgproc.hpp"头文件,我们将在此程序中介绍更多处理图像旋转的函数。

以下程序演示了如何使用 C++ 在 OpenCV 中旋转图像。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
   Mat before_rotation = imread("bright.jpg");//将图像加载到矩阵
   namedWindow("BeforeRotation");//声明显示原始图像的窗口//
   imshow("BeforeRotation", before_rotation);//显示旋转前的图像//
   namedWindow("AfterRotation");//声明显示旋转后图像的窗口//
   int Rotation = 180;//初始化旋转角度//
   createTrackbar(&";Rotation&";, &"AfterRotation&";, &Rotation, 360);//创建轨迹条//
   int Height = before_rotation.rows / 2;//获取行的中间点//
   int Width = before_rotation.cols / 2;//获取高度的中间点//
   while (true) {
      Mat for_Rotation = getRotationMatrix2D(Point(Width, Height), (Rotation - 180), 1);//二维旋转的仿射变换矩阵//
      Mat for_Rotated;//声明旋转图像的矩阵
      warpAffine(before_rotation, for_Rotated, for_Rotation, before_rotation.size());//应用仿射变换//
      imshow("AfterRotation", for_Rotated);//显示旋转后的图像//
      int termination = waitKey(30);//允许系统等待 30 毫秒来创建旋转效果//
      if (termination == 27){ //按下 Esc 键则终止//
         break;
      }
   }
   return 0;
}

输出


相关文章