C: smoothing noise with a box-blur convolution
An image is a two-dimensional array of pixel values. Convolution slides a small kernel over it and, at each position, adds up the products of the kernel weights and the pixels underneath. A box blur uses a kernel of all equal weights, so each output pixel is the average of its neighbourhood.
C
#include <stdio.h>
#define N 5
int main(void) {
int image[N][N];
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
image[r][c] = 10;
}
}
image[2][2] = 100;
for (int r = 1; r < N - 1; r++) {
for (int c = 1; c < N - 1; c++) {
int sum = 0;
for (int kr = -1; kr <= 1; kr++) {
for (int kc = -1; kc <= 1; kc++) {
sum += image[r + kr][c + kc];
}
}
printf("%4d", sum / 9);
}
printf("\n");
}
return 0;
}