OpenCV旋转图像保持图像信息不丢失方法

时间:2024-04-03 15:38:04

OpenCV旋转图像保持图像信息不丢失方法OpenCV旋转图像保持图像信息不丢失方法

效果如上图,直接上代码,C++和Python版本略有差异

C++ Code:

#include "opencv2/opencv.hpp"

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

    // get rotation matrix for rotating the image around its center in pixel coordinates
    cv::Point2f center((src.cols-1)/2.0, (src.rows-1)/2.0);
    cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
    // determine bounding rectangle, center not relevant
    cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), src.size(), angle).boundingRect2f();
    // adjust transformation matrix
    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;
}

Python Code:

heightNew=int(cols*fabs(sin(radians(angle)))+rows*fabs(cos(radians(angle))))
widthNew=int(rows*fabs(sin(radians(angle)))+cols*fabs(cos(radians(angle))))


M = cv2.getRotationMatrix2D(center,angle,1)#获得旋转矩阵
print(M)
M[0,2] +=(widthNew-cols)/2  
M[1,2] +=(heightNew-rows)/2 
print(M)

dst  = cv2.warpAffine(image,M,(widthNew,heightNew))#仿射变换旋转图像