0

Hey I am suppose to build a low pass filter for a 2-d array for a pgm file. The program is suppose to replace each pixel with the average of it and its 8 nearest neighbors. I am stuck and have no idea what i'm doing wrong. thanks for the help. Now it is giving me a java.lang.ArrayIndexOutOfBoundsException: -1 error.

    public static int[][] lowpass(int[][] image)  
{
    int height = image.length;
  int width = image[0].length;
  int[][] result = new int[height][width];
  int sum;
  int avg;

  for (int col = 0; col < image.length; col++)
  {
     result[0][col] = image[0][col];
     result[height - 1][col] = image[height - 1][col];
  }

  for (int row = 0; row < image[0].length; row++)
  {
     result[row][0] = image[row][0];
     result[row][width - 1] = image[row][width - 1];
  }      

  for (int row = 1; row < height - 1; row++)
  {  
     for (int col = 1; col < width - 1; col++)
     {
        sum = image[row - 1][col - 1] + image[row - 1][col] + image[row - 1][col + 1] + image[row][col - 1] + image[row][col] + image[row][col + 1] + image[row +1][col - 1] + image[row +1][col] + image[row + 1][col + 1];
        avg = sum / 9;
        result[row][col] = avg;
     }
  }

    return result;
}
  • Well, nowhere in the code do you compute the average of the current piel and its 8 neighbors. The sum stays at 0 at each iteration. – JB Nizet Nov 17 '13 at 15:36
  • Are you sure `sum` is greater than 9? Because otherwise this `sum / 9` calculation will give you `0` (integer conversion). It would be better to use `float[][] result` and use `avg = sum / 9.0`. Just a quick guess ;) – Michael Rose Nov 17 '13 at 15:38
  • I got it to work. Thanks for all the suggestions – user2930215 Nov 17 '13 at 16:12

1 Answers1

2

You have many errors in your code:

  1. You iterate over all cells, not only on neighbors.
  2. You never add value to sum.
  3. You need to reset it every time you check a new cell.

I would write a simpler method calculateAvg(image, col, row) which would calculate the average based on cell and neighbors. Don't forget to check what happen on edges.

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61