Horizontal Transformation of Array (2D)

南楼画角 提交于 2019-12-22 01:07:41

问题


It's a simple matter of flipping an image horizontally and/or vertically. The premise is that given a 2D integer array that was created from importing a picture, I must create a method with a int[][] param and horizontally flip it before returning void.

The syntax is below:

public static void horizontalFlip(int[][] imgArray)
    {
        int temp;
        for (int i = 0; i < imgArray.length; i++)
        {
            for (int j = 0; j < imgArray[i].length / 2; j++)
            {
                temp = imgArray[i][j];
                imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
                imgArray[imgArray.length - 1 - i][j] = temp;
            }
        }
    }

I use imgArray as the array param and use temp as a placeholder while the loop swaps pixels, or rather, that was the intention. Currently the window does nothing after prompting the flip. Can somebody help me find the problem with the logic or syntax?

Thanks in advance, please specify any details I should provide P.S. I can confirm the unreferenced supplied code is functional and tested.


回答1:


It is happening because you are using i instead of j. But i will not stop after halfway, but it is continued and re-swap the array.
Here is a correct code :

for (int i = 0; i < imgArray.length; i++) {
    for (int j = 0; j < imgArray[i].length / 2; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[i][imgArray.length - 1 - j];
        imgArray[i][imgArray.length - 1 -j] = temp;
    }
}

Or if you want to swap columns, not rows :

for (int i = 0; i < imgArray.length / 2; i++) {
    for (int j = 0; j < imgArray[i].length; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
        imgArray[imgArray.length - 1 -i][j] = temp;
    }
}



回答2:


This will correctly flip the image horizontally:

public static void horizontalFlip(int[][] imgArray)
{
    int temp;
    for (int i = 0; i < imgArray.length; i++) {
        for (int j = 0; j < imgArray[i].length/2; j++) {
        temp = imgArray[i][j];
        imgArray[i][j] = imgArray[i][imgArray[i].length - 1 - j];
        imgArray[i][imgArray[i].length - 1 - j] = temp;
        }
    }
}


来源:https://stackoverflow.com/questions/28130828/horizontal-transformation-of-array-2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!