简体   繁体   English

90度C ++旋转矩阵/图像的公式

[英]Formula of rotating matrix/image 90 degree C++

Let's say I have image, which I need to rotate 90 degrees in any direction and I just can't understand how to do that clear. 假设我有图像,我需要在任何方向上旋转90度,但我不明白如何做到这一点。 I need to work with matrix, where Width - it's X, and Height - it's Y. I've already done rotating an image 180 degrees, but can't figure out 90 degrees. 我需要处理矩阵,其中宽度-是X,高度-是Y。我已经完成了将图像旋转180度的操作,但无法确定90度。

Here are the examples. 这里是例子。 Let's say I have an image 3x4 pixels. 假设我有一张3x4像素的图片。 Width = 3, Height = 4, the amount of data in each cell - N = Width * Height = 3 * 4 = 12 . 宽度= 3,高度= 4,每个单元格中的数据量N = Width * Height = 3 * 4 = 12 Let's make the matrix: 让我们做一个矩阵:

这里是

The formula to easily go through the matrix is y*Width + x . 容易通过矩阵的公式是y*Width + x And the formula for our rotating 180 degrees is: 我们旋转180度的公式是:

N - Width + x - y * Width

So we have: 因此,我们有:

DataOut [y * Width + x] = DataIn [N - Width + x - y * Width]

Using this formula we get: 使用此公式,我们得到:

这个矩阵

But I can't come up with the formula of rotating 90 degrees. 但是我无法提出旋转90度的公式。 Can you help me, please? 你能帮我吗?

you can simply rotate the matrix by this: 您可以通过以下方法简单地旋转矩阵:

for(int i=0; i<cols; i++)
{
    for(int j=1; j<=rows; j++)
    {
        datOut[i][j]= datIn[rows-j][i];
    }
}

and in 1-D array: 并在一维数组中:

for(int i=0; i<cols; i++)
{
    for(int j=1; j<=rows; j++)
    {
        datOut[i * rows + j]= datIn[(rows-j) * cols + i];
    }
}

You can easily convert the (x + y * width) to a simpler (x, y) representation. 您可以轻松地将(x + y *宽度)转换为更简单的(x,y)表示形式。

using P = point_data_type;
P point(int x, int y){
   return DataIn[x + y * width];  // N - ...?
}

Now a right angle rotation is just a coordinate switch and maybe a sign correction. 现在,直角旋转只是一个坐标开关,也许是一个符号校正。

P rotate90(int x, int y){
    return point(y, x);
}

This is a positive rotation in a left-handed system. 在左撇子系统中这是正旋转。 Subtract x from Width if the rotation is in the wrong direction. 如果旋转方向错误,则从Width中减去x。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM