Java: filtering an image with a convolution kernel

A grayscale image is a grid of numbers where each pixel stores brightness. Convolution slides a small grid of weights, the kernel, over the image. At each position the pixels under the kernel are multiplied by the weights and summed to give one output pixel.

Java
class Main {
  public static void main(String[] args) {
    int[][] image = {
      {10, 10, 10, 10, 10},
      {10, 10, 10, 10, 10},
      {10, 10, 80, 80, 80},
      {10, 10, 80, 80, 80},
      {10, 10, 80, 80, 80},
    };
    int size = image.length - 2;
    int[][] out = new int[size][size];
    for (int r = 0; r < size; r++) {
      for (int c = 0; c < size; c++) {
        int sum = 0;
        for (int kr = 0; kr < 3; kr++) {
          for (int kc = 0; kc < 3; kc++) {
            sum += image[r + kr][c + kc];
          }
        }
        out[r][c] = sum / 9;
      }
    }
    for (int[] row : out) {
      System.out.println(row[0] + " " + row[1] + " " + row[2]);
    }
  }
}
Read the full lesson