用c语言或者c++编写opencv图像旋转的代码
时间: 2024-10-04 09:00:51 浏览: 79
在C++中,使用OpenCV库可以方便地进行图像旋转。下面是一个简单的例子,展示如何使用OpenCV的`getRotationMatrix2D()`函数和`warpAffine()`函数实现顺时针旋转:
```cpp
#include <opencv2/opencv.hpp>
cv::Mat rotateImage(const cv::Mat& src, double angle, int center_point_x = 0, int center_point_y = 0) {
// 获取源图像尺寸
int rows = src.rows;
int cols = src.cols;
// 计算旋转中心点(如果未提供,则默认图像中心)
if (center_point_x == 0 && center_point_y == 0) {
center_point_x = cols / 2;
center_point_y = rows / 2;
}
// 创建旋转矩阵
cv::Point2f rot_center(center_point_x, center_point_y);
cv::Mat rotation_matrix = getRotationMatrix2D(rot_center, angle, 1.0);
// 扩展旋转矩阵到整个图像,保持边缘不变
cv::Rect rect(0, 0, cols, rows);
cv::Mat warped_img;
warpAffine(src, warped_img, rotation_matrix, rect.size(), INTER_LINEAR + WARP_INVERSE_MAP);
return warped_img;
}
int main() {
// 加载图像
cv::Mat image = cv::imread("input.jpg");
if (!image.data) {
std::cerr << "Error loading image." << std::endl;
return -1;
}
// 设定旋转角度(例如90度)
double angle = 90.0;
// 旋转图像并显示
cv::Mat rotated_image = rotateImage(image, angle);
imshow("Rotated Image", rotated_image);
waitKey(0); // 等待用户按键
return 0;
}
```
在这个示例中,你需要替换"input.jpg"为你实际的图片路径。运行这个程序会显示旋转后的图像。
阅读全文
相关推荐


















