From 70074a2942a5c94afb7458cd032d3fdd4c1969da Mon Sep 17 00:00:00 2001 From: kris Date: Mon, 19 Jul 2021 09:57:26 +0100 Subject: [PATCH] Support arbitrary gamma correction of input image --- convert.py | 8 +++++++- image.py | 13 ++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/convert.py b/convert.py index f3b837b..d365a03 100644 --- a/convert.py +++ b/convert.py @@ -65,6 +65,10 @@ def main(): parser.add_argument( '--verbose', action=argparse.BooleanOptionalAction, default=False, help="Show progress during conversion") + parser.add_argument( + '--gamma_correct', type=float, default=2.4, + help='Gamma-correct image by this value (default: 2.4)' + ) args = parser.parse_args() palette = palette_py.PALETTES[args.palette]() @@ -88,7 +92,9 @@ def main(): image_py.resize(image, screen.NATIVE_X_RES, screen.NATIVE_Y_RES * 2, srgb_output=True).show() resized = np.array(image_py.resize(image, screen.X_RES, - screen.Y_RES)).astype(np.float32) + screen.Y_RES, + gamma=args.gamma_correct)).astype( + np.float32) # convert from sRGB1-linear to CAM02UCS perceptually uniform colour space cam16ucs = colour.convert( diff --git a/image.py b/image.py index b1947c6..41680ea 100644 --- a/image.py +++ b/image.py @@ -13,8 +13,8 @@ def linear_to_srgb_array(a: np.ndarray, gamma=2.4) -> np.ndarray: 0.055) -def srgb_to_linear(im: np.ndarray) -> np.ndarray: - rgb_linear = srgb_to_linear_array(im / 255.0, gamma=2.4) +def srgb_to_linear(im: np.ndarray, gamma=2.4) -> np.ndarray: + rgb_linear = srgb_to_linear_array(im / 255.0, gamma=gamma) return (np.clip(rgb_linear, 0.0, 1.0) * 255).astype(np.float32) @@ -32,13 +32,16 @@ def open(filename: str) -> np.ndarray: return im -def resize(image: Image, x_res, y_res, srgb_output: bool = False) -> Image: +def resize( + image: Image, x_res, y_res, gamma: float = 2.4, + srgb_output: bool = False) -> Image: # Convert to linear RGB before rescaling so that colour interpolation is # in linear space - linear = srgb_to_linear(np.asarray(image)).astype(np.uint8) + linear = srgb_to_linear(np.asarray(image), gamma=gamma).astype(np.uint8) res = Image.fromarray(linear).resize((x_res, y_res), Image.LANCZOS) if srgb_output: return Image.fromarray( - linear_to_srgb(np.array(res, dtype=np.float32)).astype(np.uint8)) + linear_to_srgb(np.array(res, dtype=np.float32), gamma=gamma).astype( + np.uint8)) else: return res