将二维数组旋转 alpha 度

Rotate 2D array by alpha degrees

我写了一个有两个参数的函数:

  1. 作为 3D 阵列的 JPG 图像

  2. alpha 给定的旋转度数 我的方法是:

    public static int[][] rotate(int[][] img, double alpha) { 双 rad = Math.toRadians(alpha); 双罪 = Math.sin(rad); 双 cos = Math.cos(弧度);

     int height = img.length;
     int width = img[0].length;
    
     int[][] rotate = new int[height][width];
    
     for(int i = 0; i < height; i++) {
         for(int j = height - i - 1; j < width; j++) {
    
             if(j < height && i < width) {
    
                 double i_new = Math.floor(cos * (img[i].length - i) - sin * (img[j].length - j)) + i;
                 double j_new = Math.floor(sin * (img[i].length - i) + cos * (img[j].length - j)) + j;
    
                 rotate[i][j] = img[(int)j_new][(int)i_new];
             }
         }
     }
     return rotate;
    

    }

固定索引范围时,输出为黑色图像。我错过了什么?

过了一会儿我找到了解决方案。

注意:它没有使用任何特殊的预定义库。

运行`在矩阵上的全局函数:

public static int[][] rotate(int[][] img, double alpha) {

    double rad = Math.toRadians(alpha);                             //construct of the relevant angles
    double sin = Math.sin(rad);
    double cos = Math.cos(rad);

    int height = img.length;
    int width = img[0].length;

    int[][] rotate = new int[height][width];

    int a = height / 2;                                             //we will use the area of a and b to compare coordinates by the formula given
    int b = width / 2;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {

            double i_new = Math.floor(cos * (i - a) - sin * (j - b)) + a;       // following the conversion function
            double j_new = Math.floor(sin * (i - a) + cos * (j - b)) + b;

            if (i_new >= rotate.length || i_new < 0 || j_new >= rotate[0].length || j_new < rotate[0][0]) { // if out of scope of the conversion --> print none
                System.out.print("");                                           //mainly cause 'continue' statements are not necessary in java and JS
            } else {
                rotate[(int) i_new][(int) j_new] = img[i][j];                   //convert
            }
        }
    }

    return rotate;
}

旋转每个二维矩阵的全局函数:

public static int[][][] rotate_alpha(int[][][] img, double alpha) {

    int height = img[0].length;
    int width = img[0][0].length;

    int[][][] rotated = new int[3][height][width];

    for (int k = 0; k < 3; k++) {
        rotated[k] = rotate(img[k], alpha);
    }

    return rotated;
}

希望这个话题现在已经解决,并遵守所有干净代码的标准。