c++, opencv, 旋转图片
时间: 2023-11-20 11:24:23 浏览: 164
您好!感谢您的提问。要旋转图像,您可以使用OpenCV中的旋转函数cv::rotate。以下是一个示例代码片段,它将图像旋转90度:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取图像
Mat image = imread("path/to/your/image.jpg");
// 将图像逆时针旋转90度
Mat rotated;
cv::rotate(image, rotated, ROTATE_90_COUNTERCLOCKWISE);
// 显示旋转后的图像
imshow("Rotated Image", rotated);
waitKey(0);
return 0;
}
```
在上面的代码中,我们首先读取了一张图像,然后使用cv::rotate函数将其逆时针旋转了90度,并将结果存储在名为rotated的Mat对象中。最后,我们使用OpenCV中的imshow函数显示旋转后的图像,并等待用户按下任意键来关闭窗口。
请注意,cv::rotate函数有三个参数:输入图像、输出图像和旋转方向。在上面的代码中,我们使用了ROTATE_90_COUNTERCLOCKWISE参数来逆时针旋转图像90度。您可以根据需要更改旋转方向和旋转角度。
希望这可以帮助您解决问题!
相关问题
C++OpenCV旋转操作角度
### 使用 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]。
c++ opencv图片旋转
以下是使用C++和OpenCV实现图片旋转的示例代码:
```cpp
#include <opencv2/opencv.hpp>
int main() {
// 读取图片
cv::Mat image = cv::imread("image.jpg");
// 定义旋转角度和缩放比例
double angle = 45.0;
double scale = 1.0;
// 计算旋转中心
cv::Point2f center(image.cols / 2, image.rows / 2);
// 获取旋转矩阵
cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, scale);
// 执行旋转操作
cv::Mat rotatedImage;
cv::warpAffine(image, rotatedImage, rotationMatrix, image.size());
// 显示旋转后的图像
cv::imshow("Rotated Image", rotatedImage);
cv::waitKey(0);
return 0;
}
```
这段代码首先使用`imread`函数读取图片,然后定义旋转角度和缩放比例。接下来,通过计算旋转中心和调用`getRotationMatrix2D`函数获取旋转矩阵。最后,使用`warpAffine`函数执行旋转操作,并将结果显示出来。
阅读全文
相关推荐
















