旋转图像问题

时间:2016-05-23 05:12:39

标签: java arrays rotation 2d

这是我编写的用于将图像顺时针旋转90度的代码。当图像的高度与其宽度匹配时,此工作正常。但是当情况并非如此时,图像的末端会出现黑色边缘,而图像的其余部分应该是这样。任何帮助表示赞赏

public void rotate(){
    int y = this.image.length;
    int x = this.image[0].length;
    int[][] rotate = new int[x][y];
    UI.println(y);
    UI.println(x);
    for(int row = 0; row<x/2; row++){
        for(int col = 0; col < ((y+1)/2); col++){
            int temp = this.image[row][col];
            rotate[row][col] = this.image[y-1-col][row];
            rotate[y-1-col][row] = this.image[y-1-row][y-1-col];
            rotate[y-1-row][y-1-col] = this.image[col][y-1-row];
            rotate[col][y-1-row] = temp;
        }
    }
    int[][] image = new int[x][y]; 
    this.image = rotate;

1 个答案:

答案 0 :(得分:0)

旋转的变换矩阵

| c   -s  0 |
| s   c   0 |
| 0   0   1 |

c = cos theta和s = sin theta
用于翻译的转换矩阵

| 1   0   xr |
| 0   1   yr |
| 0   0   1  |

您需要将对象的翻译中心翻译成原点
然后旋转
然后翻译回来

|1  0  xr|   |c  -s  0|   |1  0  -xr|   |x|
|0  1  yr| x |s  c   0| x |0  1  -yr| x |y|
|0  0  1 |   |0  0   1|   |0  0    1|   |1|

解决后你会得到

|x*c-y*s-xr*c+yr*s+xr|
|x*s+y*c-xr*s-yr*c+yr|
|          1         |

所以新点(x2,y2)是这样的

x2 = x*c-y*s-xr*c+yr*s+xr
y2 = x*s+y*c-xr*s-yr*c+yr

把c = 0(因为cos90 = 0
和s = 1(因为sin90 = 1

x2 = -y+yr+xr
y2 = x-xr+yr