Adding to uint8 pixels wraps around. Do it the safe way, as np.clip(img.astype(np.int16) + d, 0, 255) would, and count how many pixels hit a limit.
What to build
A program that changes an image's brightness with clipping.
Requirements
- Add d to every pixel and clip the result to the range 0 to 255.
- Print the new image in NumPy's integer format, then
clipped N, the number of pixels whose raw sum was below 0 or over 255.
Input
Line 1: d. Line 2: h and w. Then h rows of w pixels.
Output
h + 1 lines.
Constraints
−300 ≤ d ≤ 300; 1 ≤ h, w ≤ 20; 0 ≤ pixel ≤ 255.
Example
Input:
50
2 3
0 100 250
200 210 5
Output:
[[ 50 150 255]
[250 255 55]]
clipped 2
Why it works
Doing the addition in a wider type keeps the true sums, and clipping then maps every out-of-range value to the nearest valid brightness instead of wrapping it around to the other end.
Examples
50 2 3 0 100 250 200 210 5
[[ 50 150 255] [250 255 55]] clipped 2
-20 1 3 10 20 30
[[ 0 0 10]] clipped 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Add in ordinary Python integers, which never wrap, then limit the result to 0–255.
Hint 2
A pixel counts as clipped when the raw sum is below 0 or over 255.
Solution
Show one correct solution (try it yourself first)
def fmt2(m):
w = max(len(str(v)) for row in m for v in row)
rows = ["[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in m]
return "[" + "\n ".join(rows) + "]"
d = int(input())
h, w = map(int, input().split())
img = [[int(x) for x in input().split()] for _ in range(h)]
clipped = 0
out = []
for row in img:
new = []
for v in row:
s = v + d
if s < 0 or s > 255:
clipped += 1
new.append(min(255, max(0, s)))
out.append(new)
print(fmt2(out))
print("clipped", clipped)