我正在尝试将给定图像像素 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;
}
}
我的想法是添加一个数组作为二维数组的元素,但我认为我的逻辑有缺陷,因为这效果不太好
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
对象的二维数组。如果您重写 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));
关于java - 如何将像素数组存储到二维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349449/