【问题标题】:Set red 2d array values using for loop使用 for 循环设置红色二维数组值
【发布时间】:2015-03-29 04:19:59
【问题描述】:

我正在尝试创建一种方法,该方法将获取图像中的所有红色值并仅显示红色值。我的 getRedImage() 方法有问题。我是新手,任何帮助将不胜感激!

public class SimpleRGB
{
    private int width, height;
    private int[][] red = new int[1000][1000];

这部分获取红色值并将其设置到我的二维红色数组的指定位置:

    public void setRed(int x, int y, int aRed)
    {
        red[x][y] = aRed;
    }

这部分获取坐标(x,y)处的红色值并返回:

    public int getRed(int x, int y)
    {
        int thisr = red[x][y];
        return thisr;
    }

我不知道如何表达这部分。我知道我需要创建一个新的 SimpleRGB 对象来返回,然后使用嵌套的 for 循环将我的新简单 RGB 对象的红色二维数组设置为这个 simpleRGB 对象的红色二维数组,然后使用嵌套的 for 循环来将绿色和蓝色二维数组值都设置为零。我只是不确定如何做到这一点。

    public SimpleRGB getRedImage()
    {
        // This is where I am confused.
    }
}

【问题讨论】:

  • 所以 getRedImage 循环遍历图像中的所有像素,只返回每个像素的红色值,然后用这些红色值构建/填充二维数组?听起来您需要研究一些用于图像处理的标准 Java 类。

标签: java arrays for-loop


【解决方案1】:

我终于明白了:

public SimpleRGB getRedImage()
{
    SimpleRGB redImage = new SimpleRGB(width, height);

    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            redImage.setRed(i, j, getRed(i, j));
            redImage.setGreen(i, j, getGreen(i, j, 0);
            redImage.setBlue(i, j, getBlue(i, j, 0));
        }
    }

return redImage;
}

我的基本结构是正确的,但我正在改变这个红色/绿色/蓝色,而不是添加 redImage.setRed 来修改新对象。

【讨论】:

  • 请记住,您可以接受自己的答案。您还可以投票给任何其他有用的答案。
  • 尝试了这两个,但我还没有足够的代表/必须等待 24 小时才能接受我自己的。谢谢!
【解决方案2】:

我不太明白你的问题,但是,如果你有 3 个二维数组,每个 RGB 一个:

int[][] red = new int[1000][1000];
int[][] green = new int[1000][1000];
int[][] blue = new int[1000][1000];

你只想要图像中的红色,只需将所有其他颜色设置为零:

public class SimpleRGB
{
    private int width;
    private int height;
    private int[][] red = new int[1000][1000];
    private int[][] green = new int[1000][1000];
    private int[][] blue = new int[1000][1000];

    public SimpleRGB(int[][] red, int[][] green, int[][] blue) {
        this.red = red;
        this.green = green;
        this.blue = blue;
    }

    // some methods

    public int[][] getRed() {
        return red;
    }

    public int[][] getGreen() {
        return green;
    }

    public int[][] getBlue() {
        return blue;
    }

    // the method that interests you

    public SimpleRGB getRedImage() {
        return new SimpleRGB(red, new int[1000][1000], new int[1000][1000]);
    }
}

创建一个新数组,其所有元素默认初始化为0。

【讨论】:

    【解决方案3】:

    在二维数组中循环很容易 但我不认为这是正确的方法。

    private int[][] red = new int[1000][1000];
    
    for (int i = 0; i < 1000; i++) {
        for(int j = 0; j < 1000; j++) {
            System.out.println(red[i][j]);
        }
    }
    

    【讨论】:

    • 谢谢,但是我需要将所有内容作为 SimpleRGB 对象返回,而不是执行 System.out.print。我知道创建一个很简单,如“SimpleRGB redRGB = new SimpleRGB()”,但是当我返回它时,如何让我的 for 循环的值与我的 SimpleRGB 对象相关联?
    • 使用 if 条件。如果颜色 == 255,0,0 。然后是红色的。
    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2021-05-02
    • 2013-09-18
    • 2016-01-20
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多