【发布时间】:2022-01-15 08:47:48
【问题描述】:
我有一个称为像素的 6*6 二维数组
int [][] pixels = { {1,2,7,9,4,11},
{3,4,6,6,12,12},
{4,9,15,14,9,9},
{10,10,20,18,8,8},
{4,3,17,16,1,4},
{4,5,18,18,5,6}
};
我想像这样将它的数据存储到 9 个大小为 2*2 的二维数组中
int [][] array1 = {{1,2},
{3,4}
};
int [][] array2 = {{7,9},
{6,6}
};
int [][] array3 = {{4,11},
{12,12}
};
像这样,我有另一个大小为 320 * 320 的二维数组,我想将其数据存储在 6400 个大小为 44 的二维数组中,但我不知道要动态做什么。我的 for 循环不正确。任何人都可以帮忙吗? 编辑:我尝试了这段代码,它给了我正确的结果,重新分级了二维数组的第一个数组,但我不确定第二个数组。 vectorHeight 为 4。大的 2d 数组大小为 320 320,较小的数组大小为 4 * 4
for(int j=0; j < 320 ; j++){
for(int i=0; i< 320 ; i++){
int[][] array = new int[][]{
{pixels2[j * vectorHeight][i * vectorHeight], pixels2[j * vectorHeight][(i * vectorHeight) + 1],pixels2[j * vectorHeight][(i * vectorHeight) + 2],pixels2[j * vectorHeight][(i * vectorHeight) + 3]},
{pixels2[(j * vectorHeight) + 1][i * vectorHeight], pixels2[(j * vectorHeight) + 1][(i * vectorHeight) + 1],pixels2[(j * vectorHeight) + 2][(i * vectorHeight) + 2],pixels2[(j * vectorHeight) + 3][(i * vectorHeight) + 3]},
};
System.out.println(Arrays.deepToString(array));
}
}
edit2:320 * 320 2d 数组是一个函数的结果,该函数获取图像并返回像素向量,因此这是读取图像的代码:
public static int[][] readImage(String filePath) {
File file = new File(filePath);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
return null;
}
int width = image.getWidth();
int height = image.getHeight();
int[][] pixels = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int p = image.getRGB(x, y);
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
pixels[y][x] = r;
p = (a << 24) | (r << 16) | (g << 8) | b;
image.setRGB(x, y, p);
}
}
return pixels;
}
我目前正在处理的图像是这张https://www.researchgate.net/profile/Ayman-Al-Dmour/publication/304496637/figure/fig1/AS:377628822392833@1467045135613/Test-images_Q320.jpg 其余的代码是一个函数,它接受图像、向量大小(高度和重量),并最终假设使用向量量化对其进行压缩
int [][] pixels = readImage(filePath);
int numofVectors1 = (pixels.length * pixels.length) / (vectorHeight * vectorWidth);
ArrayList<int[][]> vectors = new ArrayList<>(numofVectors1);
for (int j = 0; j < pixels.length; j++) {
for (int i = 0; i < pixels.length; i++) {
int[][] array = new int[][]{
{pixels[j * vectorHeight][i * vectorHeight], pixels[j * vectorHeight][(i * vectorHeight) + 1], pixels[j * vectorHeight][(i * vectorHeight) + 2], pixels[j * vectorHeight][(i * vectorHeight) + 3]},
{pixels[(j * vectorHeight) + 1][i * vectorHeight], pixels[(j * vectorHeight) + 1][(i * vectorHeight) + 1], pixels[(j * vectorHeight) + 1][(i * vectorHeight) + 2], pixels[(j * vectorHeight) + 1][(i * vectorHeight) + 3]},
};
vectors.add(array);
}
}
【问题讨论】:
-
“我的 for 循环不正确”发布您的代码,以便我们为您提供帮助
-
我试过了,但我所有的循环都错了,所以被删除了。
标签: java arrays for-loop multidimensional-array pixel