grayscale.py
1 # SPDX-FileCopyrightText: Copyright (c) 2022 JG for Cedar Grove Maker Studios 2 # 3 # SPDX-License-Identifier: MIT 4 """ 5 `cedargrove_rgb_spectrumtools.grayscale` 6 ================================================================================ 7 8 Spectral Index to Grayscale RGB Converter Helper 9 10 * Author(s): JG 11 12 Implementation Notes 13 -------------------- 14 15 **Hardware:** 16 17 **Software and Dependencies:** 18 19 * Adafruit CircuitPython firmware for the supported boards: 20 https://circuitpython.org/downloads 21 22 """ 23 24 __version__ = "0.0.0+auto.0" 25 __repo__ = "https://github.com/CedarGroveStudios/CircuitPython_RGB_SpectrumTools.git" 26 27 28 def map_range(x, in_min, in_max, out_min, out_max): 29 """ 30 Maps and constrains an input value from one range of values to another. 31 (from adafruit_simpleio) 32 33 :param float x: The value to be mapped. No default. 34 :param float in_min: The beginning of the input range. No default. 35 :param float in_max: The end of the input range. No default. 36 :param float out_min: The beginning of the output range. No default. 37 :param float out_max: The end of the output range. No default. 38 39 :return: Returns value mapped to new range 40 :rtype: float 41 """ 42 in_range = in_max - in_min 43 in_delta = x - in_min 44 if in_range != 0: 45 mapped = in_delta / in_range 46 elif in_delta != 0: 47 mapped = in_delta 48 else: 49 mapped = 0.5 50 mapped *= out_max - out_min 51 mapped += out_min 52 if out_min <= out_max: 53 return max(min(mapped, out_max), out_min) 54 return min(max(mapped, out_max), out_min) 55 56 57 def index_to_rgb(index=0, gamma=0.8): 58 """ 59 Converts a spectral index to a grayscale RGB value. Spectral index in 60 range of 0.0 to 1.0. Gamma in range of 0.0 to 1.0 (1.0=linear), 61 default 0.8 for color TFT displays. 62 63 :param float index: The normalized index value, range 0 to 1.0. Defaults to 0. 64 :param float gamma: The gamma color perception value. Defaults to 0.8. 65 66 :return: Returns a 24-bit RGB value 67 :rtype: integer 68 """ 69 70 red = grn = blu = map_range(index, 0, 1.0, 0.1, 1.0) ** gamma 71 72 return (int(red * 255) << 16) + (int(grn * 255) << 8) + int(blu * 255)