如何围绕其"center"旋转 2D 像素数组



我得到了一个 2D 像素数组,我应该根据像素数组围绕其最中心点旋转此图像。我尝试实现基于旋转矩阵旋转图像的代码,但到目前为止我还没有成功。

当前 2D 阵列旋转代码:

        int width = originalImage.length;
        int height = originalImage[0].length;
        final double angle = 90;
        int[][] array = new int[width][height];
        double c = Math.cos(Math.toRadians(angle));
        double s = Math.sin(Math.toRadians(angle));
        int x = width / 2;
        int y = height / 2;
        for (int xx = 0; xx < width; xx++) {
            for (int yy = 0; yy < height; yy++) {
                int xp = xx - x;
                int yp = yy - y;
                int xa = (int)((float)((float)xp * c - (float)yp * s));
                int ya = (int)((float)((float)xp * s + (float)yp * c));
                xa += x;
                ya += y;
                xp += x;
                yp += y;

                if(xa < width && ya < height) array[xa][ya] = originalImage[xp][yp];
                //System.out.print("n"+xa+" "+ya);
            }
        }

我也试过这个:

        int[][] array = new int[originalImage.length][originalImage[0].length];
        int xx = 0, yy = 0;
        for (int x = originalImage.length - 1; x >= 0; x--) {
            xx = 0;
            for (int y = 0; y < originalImage[x].length; y++) {
                //System.out.println(array[yy][xx]);
                //System.out.println(originalImage[y][x]);
                if (y < originalImage.length && x < originalImage[x].length) {
                    array[yy][xx] = originalImage[y][x];
                    //System.out.print(array[yy][xx]);
                }
                xx++;
            }
            yy++;
        }

对于如何改进我的代码,或者应该如何做到这一点,有什么建议吗?

因为你旋转了90度,所以你可以跳过一点

// origin to center point
int xp = xx - x; 
int yp = yy - y;
// rotation and origin back to (0,0)
int x_rotated = -yp + y;
int y_rotated = xp + x;
//
array[x_rotated][y_rotated] = originalImage[xx][yy];

如果要向其他方向旋转,请更改

int x_rotated = yp + y;
int y_rotated = -xp + x;

最新更新