【问题标题】:Java: rotate image 90 degreesJava:将图像旋转 90 度
【发布时间】:2016-05-13 16:08:06
【问题描述】:

我正在尝试编写一种将图像向右旋转 90 度的方法。我已经查看了有关此主题的其他帖子,但似乎没有一个可以帮助我解决我的问题。我的代码似乎可以在纸上运行,但我不知道为什么 j 单元测试无法通过。为什么我的 j 单元测试没有通过?

我的代码:

 /**
* intialize a picture by giving an image matrix
* @param imageMatrix two dimansionar RGBColor array
*/
public Picture(RGBColor imageMatrix[][]){
    this.width = imageMatrix.length;
    this.height = imageMatrix[0].length;
    this.imageMatrix = imageMatrix;
}

/**
 * turns this picture 90 degrees to the right
 *
 */
public void rot90DegRight(){
    int w = imageMatrix.length;
    int h = imageMatrix[0].length;
    RGBColor[][] rotatedMatrix = new RGBColor[h][w];
    for (int i = 0; i<h; i++){
        for(int j = 0; j<w; j++){
            rotatedMatrix[i][j] = imageMatrix[w-j-1][i];
        }
    }

}

这里也是 j-unit 测试用例:

@Test(timeout=1000)
public void testRot90DegRight(){
    RGBColor[][] imageMatrix = new RGBColor[100][100];
    for (int w=0; w<100; w++){
        for (int h=0; h<100; h++){
            if ((w==20) & (h==20)){
                imageMatrix[w][h] = new RGBColor(255,255,255);
            } else {
                imageMatrix[w][h] = new RGBColor(0,0,0);
            }
        }
    }
    Picture p = new Picture(imageMatrix);
    p.rot90DegRight();
    assertTrue("The white pixel was not rotated", !(p.getImageMatrix()[20][20].isWhite()));
    assertTrue("The white pixel was not rotated", (p.getImageMatrix()[79][20].isWhite()));

}

【问题讨论】:

    标签: java image matrix rotation


    【解决方案1】:

    您创建了rotatedMatrix 并在rot90DegRight() 中分配了一些值,但随后将结果扔掉了。 您必须将旋转结果存储在某处。

    添加

    this.imageMatrix = rotatedMatrix;
    

    在外部for 循环之后可能会使其工作。

    请注意,这将使它不再引用旋转后传递给构造函数的数组。

    【讨论】:

    • 不幸的是,在 foo 循环之后添加建议的行并没有什么不同。我真的不明白如何在不改变方法本身的情况下存储值,我认为该方法应该是一个空白,因为它是我的学校给我们的......
    【解决方案2】:

    MikeCAT 是对的。是这样的(简单来说):

    假设你正在尝试旋转这个双数组:

    1 2 3 4

    1 2 3 4

    1 2 3 4

    1 2 3 4

    使用您的方法,将 [0][3] 替换为 [0][0] 后,您最终会在循环中返回 [0][3] 并将 [0][0] 替换为 [0] ][3]。数组将在中途撤消自身,给您留下相同的结果。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2013-02-13
      相关资源
      最近更新 更多