OpenCV 4.5 C++版 将矩阵顺时针旋转 90 度

demo

#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;


Mat_<char> rotate90(Mat_<char> originMatrix)
{
    // 原本 i row j col 的,顺时针旋转90度之后变成 j row i col的
    Mat_<char> outputMatrix = Mat::zeros(originMatrix.cols, originMatrix.rows, CV_8SC1);

    for(int y = 0; y < originMatrix.rows; ++y)
    {
        for(int x = 0; x < originMatrix.cols; ++x)
        {
            outputMatrix.at<char>(x, originMatrix.rows -1 -y) = originMatrix.at<char>(y, x);
        }
    }
    return outputMatrix;
}

void printMatrix(Mat_<char> inputMatrix)
{
    for(int y = 0; y < inputMatrix.rows; ++y)
    {
        for(int x = 0; x < inputMatrix.cols; ++x)
        {
            cout << (int)inputMatrix.at<char>(y, x) << " ";
        }
        cout << endl;
    }
}

int main(void)
{
    Mat_<char> diyMatrix = (
        Mat_<char>(3, 4) << -1, 0, 1, 7,
                            -2, 0, 2, 8,
                            -1, 0, 1, 9);

    // printMatrix(diyMatrix);
    cout << diyMatrix << endl;

    diyMatrix = rotate90(diyMatrix);

    cout << diyMatrix << endl;

    return 0;
}

result

[ -1,   0,   1,   7;
  -2,   0,   2,   8;
  -1,   0,   1,   9]
[ -1,  -2,  -1;     
   0,   0,   0;     
   1,   2,   1;     
   9,   8,   7]  

解读

没啥好说的。认真想想,我们一般编号从 1 开始的,但是C/C++是从 0 开始的。
数学上,原本矩阵的 第 i 行 j 列的,旋转后变成 j 行 (n - i + 1) 列(i 和 j 都从 1 开始编号),
程序上,原本矩阵的 第 i 行 j 列的,旋转后变成 j 行 (n - 1 - i ) 列(i 和 j 都从 0 开始编号)。

认真想想,所以我们并不能让下标从 1 开始算,否则分析起来貌似没有意义。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值