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;
}
有帮助吗?

解决方案

Here's a simple code snippet that should do what you intend.

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;
}

First we create a new image array:

int[][] reducedImage = new int[image.length/scale][image[0].length/scale];

Then we iterate through each pixel in this new image:

for (int i=0;i<reducedImage.length;i++) {
    for (int j=0;j<reducedImage[0].length;j++) {

Then for each new pixel, we count the number of pixels from the old image:

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];
    }
}

And then we check if at least half of the old pixels were on, and turn the new pixel on. Otherwise we keep this pixel off:

reducedImage[i][j] = total>(scale*scale/2) ? 1 : 0;

Finally, we return the new image:

return reducedImage;

This is probably not the best way to shrink an image, but it's pretty simple and easy to understand.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top