如何使用 C++ 在 OpenCV 中旋轉影像?


使用 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");//loading image to a matrix
   namedWindow("BeforeRotation");//Declaring window to show the original image//
   imshow("BeforeRotation", before_rotation);//showing the image before rotation//
   namedWindow("AfterRotation");//declaring window to show rotated image//
   int Rotation = 180;//initialization rotation angle//
   createTrackbar("Rotation", "AfterRotation", &Rotation, 360);//creating trackbar//
   int Height = before_rotation.rows / 2;//getting middle point of rows//
   int Width = before_rotation.cols / 2;//getting middle point of height//
   while (true) {
      Mat for_Rotation = getRotationMatrix2D(Point(Width, Height), (Rotation - 180), 1);//affine transformation matrix for 2D rotation//
      Mat for_Rotated;//declaring a matrix for rotated image
      warpAffine(before_rotation, for_Rotated, for_Rotation, before_rotation.size());//applying affine transformation//
      imshow("AfterRotation", for_Rotated);//show rotated image//
      int termination = waitKey(30);//allow system 30 millisecond time to create the rottion effect//
      if (termination == 27){ //terminate if Esc button is pressed//
         break;
      }
   }
   return 0;
}

輸出

更新於:2021 年 3 月 10 日

2 千+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.