Home > Backend Development > C++ > body text

How to Rotate an Image in OpenCV Without Cropping?

DDD
Release: 2024-11-16 07:42:03
Original
762 people have browsed it

How to Rotate an Image in OpenCV Without Cropping?

Rotate an Image without Cropping in OpenCV

If your goal is to rotate an image while preserving its entire content without any cropping, OpenCV provides a solution. Consider the situation where you rotate an image traditionally using cv::warpAffine, only to end up with a cropped result. This article addresses this issue and provides a code solution.

In our example, rotating the image using cv::getRotationMatrix2D and applying it with cv::warpAffine yields an image with missing corners. To rectify this, we must adjust the transformation matrix to account for the shifted image center.

Inspired by insights from related sources, our solution utilizes the following ideas:

  1. Matrix Adjustment: Modify the rotation matrix by incorporating a translation that aligns the image's new center with the original center.
  2. Rotated Rectangle: Use cv::RotatedRect to determine the bounding rectangle that encompasses the rotated image.

Our updated code (tested with OpenCV 3.4.1):

#include "opencv2/opencv.hpp"

int main() {
    cv::Mat src = cv::imread("im.png", CV_LOAD_IMAGE_UNCHANGED);
    double angle = -45;

    cv::Point2f center((src.cols - 1) / 2.0, (src.rows - 1) / 2.0);
    cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
    cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), src.size(), angle).boundingRect2f();
    rot.at<double>(0, 2) += bbox.width / 2.0 - src.cols / 2.0;
    rot.at<double>(1, 2) += bbox.height / 2.0 - src.rows / 2.0;

    cv::Mat dst;
    cv::warpAffine(src, dst, rot, bbox.size());
    cv::imwrite("rotated_im.png", dst);

    return 0;
}
Copy after login

This enhanced code preserves the original image's full content during rotation, successfully achieving our goal of rotating an image without cropping.

The above is the detailed content of How to Rotate an Image in OpenCV Without Cropping?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template