opencv 图像旋转 c++
时间: 2023-10-15 20:06:47 浏览: 200
要在 OpenCV 中旋转图像,可以使用函数 `cv::rotate()`。该函数的原型如下:
```cpp
void cv::rotate(cv::InputArray src, cv::OutputArray dst, int rotateCode);
```
其中,`src` 是输入图像,`dst` 是输出图像,`rotateCode` 是旋转代码,表示旋转的方向和角度。具体来说,`rotateCode` 可以取以下值:
- `cv::ROTATE_90_CLOCKWISE`:顺时针旋转 90 度。
- `cv::ROTATE_180`:旋转 180 度。
- `cv::ROTATE_90_COUNTERCLOCKWISE`:逆时针旋转 90 度。
示例代码如下:
```cpp
cv::Mat src = cv::imread("input.jpg");
cv::Mat dst;
cv::rotate(src, dst, cv::ROTATE_90_CLOCKWISE);
cv::imwrite("output.jpg", dst);
```
这段代码将读入一张名为 `input.jpg` 的图像,将其顺时针旋转 90 度,并将结果保存为名为 `output.jpg` 的图像。
相关问题
opencv 图像旋转c++
### 如何使用 C++ 和 OpenCV 实现图像旋转
为了实现图像的旋转变换,在C++中可以利用OpenCV库中的`getRotationMatrix2D()`函数来创建一个用于仿射变换的矩阵,该矩阵定义了围绕指定中心点按给定角度旋转的操作。之后通过`warpAffine()`函数应用这个变换到输入图片上。
下面是一个完整的例子展示怎样读取一张照片并对其进行特定角度的旋转操作:
```cpp
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int argc, char* argv[])
{
// 加载原始图像
Mat image = imread("path_to_image.jpg");
if (image.empty()) {
printf("Could not open or find the image\n");
return -1;
}
// 获取图像尺寸的一半作为旋转中心
Point2f center((image.cols - 1) / 2.0, (image.rows - 1) / 2.0);
// 定义旋转的角度以及缩放比例因子
double angle = 45; // 这里设置为顺时针方向45度
double scale = 1.0;
// 构建旋转矩阵
Mat rot_mat = getRotationMatrix2D(center, angle, scale)[^1];
// 应用仿射变换完成实际的旋转过程
Mat rotated_img;
warpAffine(image, rotated_img, rot_mat, image.size())[^4];
// 显示原图与处理后的对比效果
namedWindow("Original Image", WINDOW_AUTOSIZE);
imshow("Original Image", image);
namedWindow("Rotated Image", WINDOW_AUTOSIZE);
imshow("Rotated Image", rotated_img);
waitKey(0); // 等待按键事件关闭窗口
return 0;
}
```
这段程序首先加载了一张JPEG格式的照片文件,并计算其几何中心位置以便后续构建旋转矩阵。接着指定了期望的旋转角度(这里是45度),并通过调用`getRotationMatrix2D()`获取相应的二维旋转矩阵。最后借助于`warpAffine()`执行具体的像素映射工作从而得到最终被旋转过的输出图像。
opencv 图片旋转c++
在OpenCV库中,图片旋转是一个常见的图像处理操作。在C++中,你可以使用`cv::warpAffine()`函数来实现这一功能。以下是基本步骤:
1. 导入所需头文件:
```cpp
#include <opencv2/opencv.hpp>
```
2. 加载图片:
```cpp
cv::Mat img = cv::imread("input.jpg", cv::IMREAD_COLOR);
if (img.empty()) {
std::cout << "Failed to load image" << std::endl;
return;
}
```
3. 定义旋转矩阵。假设你想顺时针旋转90度,可以这样做:
```cpp
double angle = 90.0; // 角度,单位是弧度
Point2f center(img.cols / 2.0, img.rows / 2.0); // 图像中心点
Mat rot_matrix = getRotationMatrix2D(center, angle, 1.0); // 保持缩放比例不变
```
这里使用了`getRotationMatrix2D()`函数,它根据给定的角度、旋转中心和是否保持缩放比例创建旋转矩阵。
4. 执行旋转:
```cpp
cv::Mat rotated_img;
cv::warpAffine(img, rotated_img, rot_matrix, img.size());
```
5. 可能的话,保存旋转后的图片:
```cpp
cv::imwrite("output.jpg", rotated_img);
```
如果你需要逆时针旋转,只需要将角度设为负值即可。
阅读全文
相关推荐













