Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách xoay ảnh trong OpenCV C++


Giới thiệu

Xoay ảnh dùng getRotationMatrix2D (tạo ma trận affine 2D) và warpAffine (áp dụng biến đổi). Trackbar điều chỉnh góc xoay real-time.

Chương trình xoay ảnh

#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);
        if (waitKey(30) == 27) break;
    }
    return 0;
}

Kết quả

Hai cửa sổ: ảnh gốc và ảnh xoay. Trackbar "Rotation" 0-360 độ điều chỉnh góc xoay quanh tâm ảnh.