Padding for Same Convolution
Problem Statement
Determine the padding required to keep the output size equal to the input size (assuming stride S=1).
Background
To maintain spatial dimensions () with stride 1, we solve:
This gives us:
This is called "same" padding because the output has the same spatial dimensions as the input.
Your Task
Write a function calculate_same_padding(filter_size) returning the integer padding amount. Assume the filter size is always odd.
Output Format
Return an integer representing the padding needed for "same" convolution.
Example
filter_size=5
2
- Input:
filter_sizeis the side length of a square kernel, here (a patch), with stride . - Why padding is needed: with no padding, a -wide window fits into an -wide image only times, so the output shrinks by pixels per side length.
- The math: setting the output size equal to the input, , the cancels and leaves , so .
- Output:
2, meaning two rows/columns of padding on each side, so the lost pixels are restored exactly. - Notice that the padding depends only on , not on the image size. Because is odd, is even and is always a whole number: gives , gives . An even would need uneven padding on the two sides.
Constraints
- filter_size is always an odd number
- 1 <= filter_size <= 15