1

So in my code I am representing an image as a double int[][] array of 1's and 0's. I would like to be able to reduce the image to a smaller int[][] array. This is an example of what I am trying to do:

0000000000
0000000000       00000 
0000110000       00100   
0000110000   =>  00100
0000110000       01110
0000110000       00000
0011111100       00000
0000000000
0000000000
0000000000

Is there any library that can do something like this for me? Or any ideas on how to write the code to do this for me. This would be the method prototype I am looking for:

int[][] reduceImage(int[][] image, double scaleOfReduction) {
  // somehow make image reduced
  // how to implement this efficiently???
  return reducedImage;
}
4

1 回答 1

0

这是一个简单的代码片段,应该可以满足您的要求。

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;

这可能不是缩小图像的最佳方法,但它非常简单易懂。

于 2014-04-28T03:23:34.147 回答