Computer vision: Stretch the contrast

A foggy or underexposed picture uses only part of the 0 to 255 range. Stretch it to the full range.

What to build

A program that applies linear contrast stretching between two levels.

Requirements

  • The last input line is either auto (use the image's smallest and largest values) or two whole numbers lo and hi.
  • Values ≤ lo become 0, values ≥ hi become 255, and others become (v − lo) × 255 // (hi − lo).
  • If lo equals hi, print the image unchanged. Print range LO-HI first, then the rows.

Input

Line 1: H and W. Then H rows of W values. Then the range line.

Output

The range line and H rows.

Constraints

1 ≤ H, W ≤ 100; when given, 0 ≤ lo ≤ hi ≤ 255.

Example

Input:

2 3
100 110 120
130 140 150
auto

Output:

range 100-150
0 51 102
153 204 255

Why it works

The linear map sends lo to 0 and hi to 255 and keeps the order of all values between, so detail inside the chosen range is spread over the whole scale.

Examples

Example 1 · Input
2 3
100 110 120
130 140 150
auto
Expected output
range 100-150
0 51 102
153 204 255
Example 2 · Input
1 5
0 50 100 150 200
50 150
Expected output
range 50-150
0 0 127 255 255

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

With `auto`, lo is the smallest pixel and hi the largest; otherwise read them from the line.

Hint 2

Check v ≤ lo first (0), then v ≥ hi (255), and only then use (v − lo) × 255 // (hi − lo).

Solution

Show one correct solution (try it yourself first)
h, w = map(int, input().split())
img = [list(map(int, input().split())) for _ in range(h)]
spec = input().split()
if spec[0] == "auto":
    lo = min(min(row) for row in img)
    hi = max(max(row) for row in img)
else:
    lo, hi = int(spec[0]), int(spec[1])
print(f"range {lo}-{hi}")
for row in img:
    if hi == lo:
        out = row
    else:
        out = [0 if v <= lo else 255 if v >= hi else (v - lo) * 255 // (hi - lo) for v in row]
    print(" ".join(map(str, out)))

Lesson: Histograms and contrast →