簡體   English   中英

如何將像素數組存儲到二維數組中?

[英]How to store an array of pixels into a 2D array?

我正在嘗試將給定的圖像像素 RGB 值加載到二維數組中,以便以后可以編輯它們。 例如,如果我有一個 500,350 的像素,它的像素值看起來像 R 250 G 245 B 210

我試圖讓它進入一個二維數組,它看起來像這樣

A 2-dimensional array of pixels:
[
  [(255,45,19), (44,44,92), (80,1,9), ...],
  [(51,2,231), (61,149,14), (234,235,211), ...],
  [(51,2,231), (61,149,14), (199,102,202)...],
  [(51,2,231), (61,149,14), (1,5,42)...],
  ...
]

這是使用 Java 的 OpenCV 庫,我曾嘗試做類似的事情,

int[][] pixelArray = int[image.rows()][image.cols()];

for (int i = 0;i<image.rows();i++){
    for (int j = 0; j<image.cols();j++){
        double[] pixelValues = image.get(i,j);
        pixelArray[i][j] = pixelValues; 
   }
}

我的想法是添加一個數組作為 2d 數組的元素,但我認為我的邏輯有缺陷,因為這不太好

public static void main(String[] args) {

    //Instantiating ImageCodecs Class
    Imgcodecs imageCodecs = new Imgcodecs();

    //Loads Image
    Mat image = imageCodecs.imread(imageInput);
    System.out.println("Image Loaded");
    System.out.println("Image size: " + image.rows() + " Pixel rows " + image.cols() + " Pixel columns "  );

    //Gets pixel RGB values
    double[] rgb = image.get(0,0);
    System.out.println("red: " + rgb[0] + " Green: " + rgb[1] + " Blue: " + rgb[2]);

    // Attempt to get all pixels in 2D array
    int[][] pixelArray = int[image.rows()][image.cols()];

    for (int i = 0;i<image.rows();i++){
        for (int j = 0; j<image.cols();j++){
            double[] pixelValues = image.get(i,j);
            pixelArray[i][j] = pixelValues; //TRYING TO FILL 2D ARRAY WITH REGULAR ARRAY
        }
    }
    ...

我應該能夠打印整個二維數組的 RGB 值

我會創建一個Pixel類,然后有一個Pixel對象的Pixel數組。 如果重寫toString方法,則可以控制打印出類時的顯示方式。

public class Pixel {
  private int red;
  private int green;
  private int blue;

  public Pixel(int red, int green, int blue) {
      this.red = red;
      this.green = green;
      this.blue = blue;
  }

  @Override
  public String toString() {
      return "R: " + red +
              "G: " + green +
              "B: " + blue;
  }
}

要打印出數組,您可以執行以下操作:

System.out.println(Arrays.deepToString(array));

為什么不使用 Color 類並使用 Color[] 顏色數組? 它有獲取 RGB 分量以及從 int 轉換為 Color 並再次轉換回來的方法嗎?

      List<Color> colors = new ArrayList<>();
      color.add(new Color(255,45,19));
      color.add(new Color(44,44,92));

或者

      Color[] colors = new Color[10];
      colors[0] = new Color(255,45,19);
      colors[1] = new Color(44,44,92);

要存儲在二維數組中,最好這樣做。

int NROWS = 200;
int NCOLS = 200;
Color[][]  colors = new Color[NROWS][];
for (int r = 0; r < ROWS; r++) {
     Color[] row = new Color[NCOLS];
     for (int c = 0; c < NCOLS; c++) {
          //each element in a row is part of a column
          row[c] = new Color(......);
     }
      colors[r] = row;
}

無論您將其他數據結構存儲為顏色,同樣的想法都適用。 您可能還想研究使用raster來存儲像素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM