因此,在我的代码中,我将图像表示为由 1 和 0 组成的 double int[][] 数组。我希望能够将图像缩小为较小的 int[][] 数组。这是我正在尝试做的一个例子:
0000000000
0000000000 00000
0000110000 00100
0000110000 => 00100
0000110000 01110
0000110000 00000
0011111100 00000
0000000000
0000000000
0000000000
有没有图书馆可以为我做这样的事情?或者关于如何编写代码来为我执行此操作的任何想法。这将是我正在寻找的方法原型(prototype):
int[][] reduceImage(int[][] image, double scaleOfReduction) {
// somehow make image reduced
// how to implement this efficiently???
return reducedImage;
}
最佳答案
这是一个简单的代码片段,应该可以实现您的预期。
int[][] reduceImage(int[][] image, int scale) {
int[][] reducedImage = new int[image.length/scale][image[0].length/scale];
for (int i=0;i<reducedImage.length;i++) {
for (int j=0;j<reducedImage[0].length;j++) {
int total = 0;
for (int x=0;x<scale;x++) {
for (int y=0;y<scale;y++) {
total += image[i*scale+x][j*scale+y];
}
}
reducedImage[i][j] = total>(scale*scale/2) ? 1 : 0;
}
}
return reducedImage;
}
首先我们创建一个新的图像数组:
int[][] reducedImage = new int[image.length/scale][image[0].length/scale];
然后我们迭代这个新图像中的每个像素:
for (int i=0;i<reducedImage.length;i++) {
for (int j=0;j<reducedImage[0].length;j++) {
然后对于每个新像素,我们计算旧图像的像素数:
int total = 0;
for (int x=0;x<scale;x++) {
for (int y=0;y<scale;y++) {
total += image[i*scale+x][j*scale+y];
}
}
然后我们检查是否至少有一半的旧像素打开,然后打开新像素。否则我们会关闭该像素:
reducedImage[i][j] = total>(scale*scale/2) ? 1 : 0;
最后,我们返回新图像:
return reducedImage;
这可能不是缩小图像的最佳方法,但它非常简单且易于理解。
关于java - 将 double int[][] 图像减小到更小的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23331835/