Tuesday, 25 January 2022

How to use the rotatedRect in opencv c++?

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main(int argc, char* argv){

    cv::Mat src = cv::imread("../tony.jpg");
    // rect is the RotatedRect (I got it from a contour...)
    cv::RotatedRect rect(cv::Point2f(453, 127), cv::Size(230,140), 45);
        // matrices we'll use
    cv::Mat M, rotated, cropped;
        // get angle and size from the bounding box
        float angle = rect.angle;
    cv::Size rect_size = rect.size;
        if (rect.angle < -45.) {
            angle += 90.0;
        cv::swap(rect_size.width, rect_size.height);
        }
        // get the rotation matrix
        M = cv::getRotationMatrix2D(rect.center, angle, 1.0);
        // perform the affine transformation
    cv::warpAffine(src, rotated, M, src.size(), cv::INTER_CUBIC);
        // crop the resulting image
    cv::getRectSubPix(rotated, rect_size, rect.center, cropped);

    cv::imshow("cropped", cropped);
    cv::waitKey(0);
    return 0;

}

No comments:

Post a Comment