"""Per-crop contrast stretch for the J2 contrast control. One function; it changes the grey levels and nothing else. contrast_stretch(img): the 1st and 99th percentile of the crop's grey (PIL 'L' conversion) are mapped to 0 and 255; the same linear map is applied to the three colour channels, so colour relations are kept; values are clipped to 0..255. Size and mode (RGB) do not change. A crop with a grey range below 1 level is returned unchanged (as RGB). """ import numpy as np from PIL import Image def contrast_stretch(img): rgb = np.asarray(img.convert("RGB"), dtype=np.float64) grey = np.asarray(img.convert("L"), dtype=np.float64) lo, hi = np.percentile(grey, 1), np.percentile(grey, 99) if hi - lo < 1.0: return img.convert("RGB") out = np.clip((rgb - lo) * (255.0 / (hi - lo)), 0.0, 255.0) return Image.fromarray(np.rint(out).astype(np.uint8))