繁体   English   中英

如何在数组中存储每个像素的rgb值

[英]How to store rgb values of each pixel in array

我有这段代码,其中提取了每个像素的RGB值,但是我想知道如何将每个RGB值存储在数组中,以便在项目中进一步使用它。 我想将这些存储的RGB值用作反向传播算法的输入。

    import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

public class PrintImageARGBPixels
{

public static void main(String args[])throws IOException
{
BufferedImage image = ImageIO.read(new File("C:\\Users\\ark\\Desktop\\project_doc\\logo_1004.jpg"));
int r=0,g=0,b=0;
int w = image.getWidth();
int h = image.getHeight();
System.out.println("Image Dimension: Height-" + h + ", Width-"+ w);
int total_pixels=(h * w);
ArrayList <Color> arr = new ArrayList<Color>();
for(int x=0;x<w;x++)
{
for(int y=0;y<h;y++)
{
int rgb = image.getRGB(x, y);
Color c = new Color(rgb);
r=c.getRed();
g=c.getGreen();
b=c.getBlue();
 }
}

Color co = new Color(r,g,b);
arr.add(co);
for(int i=0;i<total_pixels;i++)
System.out.println("Element 1"+i+1+", color: Red " + arr.get(i).getRed() + " Green +arr.get(i).getGreen()+ " Blue " + arr.get(i).getBlue());

}
}

为什么不像这样创建一个RGB对象

public class RGB {

    private int R, G, B;

    public RGB(int R, int G, int B){
        this.R = R;
        this.G = G;
        this.B = B;
    }

    public int getR() {
        return R;
    }

    public void setR(int r) {
        R = r;
    }

    public int getG() {
        return G;
    }

    public void setG(int g) {
        G = g;
    }

    public int getB() {
        return B;
    }

    public void setB(int b) {
        B = b;
    }

}

因此,您可以将RGB对象存储在数组中,以备后用。

问候!

// Store the color objects in an array
    int total_pixels = (h * w);
    Color[] colors = new Color[total_pixels];
    int i = 0;

    for (int x = 0; x < w; x++)
    {
      for (int y = 0; y < h; y++)
      {
        colors[i] = new Color(image.getRGB(x, y));
        i++;
      }
    }

// Later you can retrieve them
    for (int i = 0; i < total_pixels; i++)
    {
      Color c = colors[i];
      int r = c.getRed();
      int g = c.getGreen();
      int b = c.getBlue();
      System.out.println("Red" + r + "Green" + g + "Blue" + b);
    }

忽略下面,这是我的老答案

使用多维数组:

[
 [255, 255, 255],
 [108, 106, 107],
 [100, 100, 55],
 ...
]

然后,您可以引用每个像素[0] [x]以获取颜色值。

使用HashMap可以更轻松地实现,其中Key是一个int [](x和y),而value是另一个int [](r,g,b)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM