title: Applying Mean filter on an image using java
body: <p>When I give it a picture with salt and pepper noise it returns an image loosing all details and I don't know what's wrong with my code:</p>
  
  <pre><code>public class Q1 {
      public static void main(String[] args) throws IOException {
          BufferedImage img = ImageIO.read(new File("task1input.png"));
  
          //get dimensions
          int maxHeight = img.getHeight();
          int maxWidth = img.getWidth();
  
          //create 2D Array for new picture
          int pictureFile[][] = new int [maxHeight][maxWidth];
          for( int i = 0; i &lt; maxHeight; i++ ){
              for( int j = 0; j &lt; maxWidth; j++ ){
                  pictureFile[i][j] = img.getRGB( j, i );
              }
          }
  
          int output [][] = new int [maxHeight][maxWidth];
  
          //Apply Mean Filter
          for (int v=1; v&lt;maxHeight; v++) {
              for (int u=1; u&lt;maxWidth; u++) {
                  //compute filter result for position (u,v)
  
                  int sum = 0;
                  for (int j=-1; j&lt;=1; j++) {
                      for (int i=-1; i&lt;=1; i++) {
                          if((u+(j)&gt;=0 &amp;&amp; v+(i)&gt;=0 &amp;&amp; u+(j)&lt;maxWidth &amp;&amp; v+(i)&lt;maxHeight)){
                          int p = pictureFile[v+(i)][u+(j)];
                          sum = sum + p;
                          }
                      }
                  }
  
                  int q = (int) (sum /9);
                  output[v][u] = q;
              }
          }
  
          //Turn the 2D array back into an image
          BufferedImage theImage = new BufferedImage(
              maxHeight, 
              maxWidth, 
              BufferedImage.TYPE_INT_RGB);
          int value;
          for(int y = 1; y&lt;maxHeight; y++){
              for(int x = 1; x&lt;maxWidth; x++){
                  value = output[y][x] ;
                  theImage.setRGB(y, x, value);
              }
          }
  
          File outputfile = new File("task1output3x3.png");
          ImageIO.write(theImage, "png", outputfile);
      }
  }
  </code></pre>