C++OpenCV旋转操作角度
时间: 2025-01-17 19:38:32 浏览: 43
### 使用 C++ 和 OpenCV 实现图像旋转
为了实现带有指定角度的图像旋转,在 C++ 中可以利用 `cv::getRotationMatrix2D` 函数来获取旋转变换矩阵,再通过 `cv::warpAffine` 应用此变换到输入图片上。
下面是一段用于执行上述功能的具体代码示例:
```cpp
#include <opencv2/opencv.hpp>
using namespace cv;
void rotate_image(const Mat& inputImage, double angle, Mat& outputImage) {
Point2f center(inputImage.cols / 2., inputImage.rows / 2.);
Mat rotationMatrix = getRotationMatrix2D(center, angle, 1.0);
Rect bbox = RotatedRect(Point2f(), Size2f((float)inputImage.cols, (float)inputImage.rows), angle).boundingRect();
rotationMatrix.at<double>(0, 2) += bbox.width / 2.0 - inputImage.cols / 2.0;
rotationMatrix.at<double>(1, 2) += bbox.height / 2.0 - inputImage.rows / 2.0;
warpAffine(inputImage, outputImage, rotationMatrix, bbox.size());
}
```
这段代码定义了一个名为 `rotate_image` 的函数,该函数接收三个参数:原始图像、期望的角度以及用来存储结果的新变量。这里使用了 `Point2f` 来表示旋转中心点的位置;而 `getRotationMatrix2D` 则负责创建一个基于给定点为中心并按照特定角度和比例因子(设为1保持原大小)进行旋转的操作矩阵[^4]。
接着计算出经过旋转后的边界框尺寸,并调整平移部分使得最终输出图像是正方形而非倾斜矩形。最后调用 `warpAffine` 方法完成实际的空间映射过程[^3]。
阅读全文
相关推荐

















