File size: 2,392 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Unit test of contrast_stretch. usage: test_contrast_stretch.py PATH_TO_contrast_stretch.py"""
import importlib.util
import sys

import numpy as np
from PIL import Image

spec = importlib.util.spec_from_file_location("cs", sys.argv[1])
cs = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cs)

rng = np.random.default_rng(0)
base = rng.integers(100, 201, size=(61, 242, 1)).astype(np.uint8)        # grey 100..200
arr = np.repeat(base, 3, axis=2)
arr[..., 2] = np.clip(arr[..., 2].astype(int) - 20, 0, 255).astype(np.uint8)   # slightly yellow tint
im = Image.fromarray(arr)
out = cs.contrast_stretch(im)
assert out.size == im.size and out.mode == "RGB"
g = np.asarray(out.convert("L"), dtype=float)
g0 = np.asarray(im.convert("L"), dtype=float)
lo, hi = np.percentile(g0, 1), np.percentile(g0, 99)
# the percentile pixels land at (about) 0 and 255 after the stretch
assert abs(np.percentile(g, 1)) < 8 and abs(np.percentile(g, 99) - 255) < 8, (np.percentile(g, 1), np.percentile(g, 99))
# order of grey levels is kept (monotone map)
idx = np.argsort(g0.ravel(), kind="stable")
assert np.all(np.diff(np.asarray(out.convert("L"), dtype=float).ravel()[idx]) >= -1.0)
# colour relation kept: the tint (R - B difference) is kept up to the map's scale
o3 = np.asarray(out, dtype=float)
# same map for all channels: the red channel is a monotone function of the input red channel, blue likewise
assert np.all(np.diff(o3[..., 0].ravel()[np.argsort(arr[..., 0].ravel(), kind="stable")]) >= -1.0)
assert np.all(np.diff(o3[..., 2].ravel()[np.argsort(arr[..., 2].ravel(), kind="stable")]) >= -1.0)
# a flat image is returned unchanged
flat = Image.new("RGB", (30, 20), (120, 120, 120))
assert np.array_equal(np.asarray(cs.contrast_stretch(flat)), np.asarray(flat))
# an image already spanning 0..255 stays almost unchanged
gfull = rng.integers(0, 256, size=(40, 90, 1)).astype(np.uint8)
full = Image.fromarray(np.repeat(gfull, 3, axis=2))
d = np.abs(np.asarray(cs.contrast_stretch(full), dtype=float) - np.asarray(full, dtype=float)).mean()
assert d < 8, d
# a grey input comes back as RGB with three equal channels
gi = Image.fromarray(rng.integers(50, 150, size=(20, 40)).astype(np.uint8), "L")
o = cs.contrast_stretch(gi)
a = np.asarray(o)
assert o.mode == "RGB" and np.array_equal(a[..., 0], a[..., 1]) and np.array_equal(a[..., 1], a[..., 2])
print("contrast_stretch tests passed")