Before filtering border pixels, a filter needs values outside the image. Build the three common choices.
What to build
A program that pads an image by p pixels on every side.
Requirements
zerofills the border with 0.replicaterepeats the nearest edge pixel (aaa, abc, ccc).reflectmirrors the image without repeating the edge pixel (cb, abc, ba), as OpenCV does by default.- Print the padded image: H + 2p rows of W + 2p values.
Input
Line 1: H, W and p. Then H rows of W values. Last line: the mode.
Output
The padded rows.
Constraints
1 ≤ H, W ≤ 30; for reflect, p < H and p < W; otherwise p ≤ 10.
Example
Input:
2 2 1
1 2
3 4
zero
Output:
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
Why it works
Each padded position maps back to one real pixel (or to 0), so the padded image is built by working out that index for the row and the column separately.
Examples
2 2 1 1 2 3 4 zero
0 0 0 0 0 1 2 0 0 3 4 0 0 0 0 0
2 3 1 1 2 3 4 5 6 replicate
1 1 2 3 3 1 1 2 3 3 4 4 5 6 6 4 4 5 6 6
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Loop r from −p to H + p − 1 and c from −p to W + p − 1, and work out which real pixel each position copies.
Hint 2
Replicate clamps an index into 0 to n − 1. Reflect maps i below 0 to −i and i of n or more to 2(n − 1) − i.
Solution
Show one correct solution (try it yourself first)
h, w, p = map(int, input().split())
img = [list(map(int, input().split())) for _ in range(h)]
mode = input().strip()
def where(i, n):
if mode == "replicate":
return min(max(i, 0), n - 1)
if i < 0:
return -i
if i >= n:
return 2 * (n - 1) - i
return i
for r in range(-p, h + p):
row = []
for c in range(-p, w + p):
if mode == "zero":
row.append(img[r][c] if 0 <= r < h and 0 <= c < w else 0)
else:
row.append(img[where(r, h)][where(c, w)])
print(" ".join(map(str, row)))