图像旋转(C++)

本文介绍如何利用C++和OpenCV库进行图像旋转操作,通过示例代码详细阐述具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说,直接上代码:

cv::Mat imgRotate(cv::Mat matSrc, float angle, bool direction)
{
    float theta = angle * CV_PI / 180.0;
    int nRowsSrc = matSrc.rows;
    int nColsSrc = matSrc.cols;
    // 如果是顺时针旋转
    if (!direction)
        theta = 2 * CV_PI - theta;
    // 全部以逆时针旋转来计算
    // 逆时针旋转矩阵
    float matRotate[3][3]{
        {std::cos(theta), -std::sin(theta), 0},
        {std::sin(theta), std::cos(theta), 0 },
        {0, 0, 1}
    };
    float pt[3][2]{
        { 0, (float)nRowsSrc },
        {(float)nColsSrc, (float)nRowsSrc},
        {(float)nColsSrc, 0}
    };
    for (int i = 0; i < 3; i++)
    {
        float x = pt[i][0] * matRotate[0][0] + pt[i][1] * matRotate[1][0];
        float y = pt[i][0] * matRotate[0][1] + pt[i][1] * matRotate[1][1];
        pt[i][0] = x;
        pt[i][1] = y;
    }
    // 计算出旋转后图像的极值点和尺寸
    float fMin_x = min(min(min(pt[0][0], pt[1][0]), pt[2][0]), (float)0.0);
    float fMin_y = min(min(min(pt[0][1], pt[1][1]), pt[2][1])
### 如何使用 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()`执行具体的像素映射工作从而得到最终被旋转过的输出图像
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值