C++: convolution with zero padding
A convolution output is smaller than the input if the kernel is only applied where it fits entirely inside the image. To keep the output the same size, the image is padded: pixels outside the border are treated as zero. Each output pixel is the sum of the neighbourhood multiplied by the kernel.
C++
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
const int n = 5;
std::vector<std::vector<int>> image(n, std::vector<int>(n, 0));
image[2][2] = 10;
int kernel[3][3] = {{0, 1, 0}, {1, -4, 1}, {0, 1, 0}};
std::vector<std::vector<int>> out(n, std::vector<int>(n, 0));
for (int r = 0; r < n; ++r) {
for (int c = 0; c < n; ++c) {
int sum = 0;
for (int kr = -1; kr <= 1; ++kr) {
for (int kc = -1; kc <= 1; ++kc) {
int rr = r + kr, cc = c + kc;
if (rr >= 0 && rr < n && cc >= 0 && cc < n) {
sum += image[rr][cc] * kernel[kr + 1][kc + 1];
}
}
}
out[r][c] = sum;
}
}
for (const auto& row : out) {
for (int v : row) {
std::cout << std::setw(4) << v;
}
std::cout << "\n";
}
}