How to write a downsampling function in Java

I'm trying to write a filter function for an image, but I can't seem to wrap my head around (or remember) how to translate all this math theory into code.

Let's say I have the following function, where the int inside the arrays are integers between 0

and 255

(pretty much greyscale to keep it simple).

private int[][] resample(int[][] input, int oldWidth, int oldHeight,
        width, int height) 
{
    int[][] output = createArray(width, height);
        // Assume createArray creates an array with the given dimension

    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            output[x][y] = input[x][y];
            // right now the output will be "cropped"
            // instead of resampled
        }
    }

    return output;
}

      

Right now I am stuck trying to figure out how to use filters. I've tried wikipedia, but I find articles they have that aren't particularly helpful. Can someone please give me some advice on this or know some simple example code?

+2


source to share


1 answer


The simplest approach is to approach the nearest neighbor, for example:

for (int x = 0; x < width; ++x) {
    for (int y = 0; y < height; ++y) {
        output[x][y] = input[x*width/oldWidth][y*height/oldHeight];
    }
}

      



But that doesn't produce pleasant results, so you may need other approaches that take multiple input pixels and average them out to get a more accurate color for the original region.

+2


source







All Articles