Last active
October 13, 2023 01:14
-
-
Save cdeitrick/b1eb523303c973d1129b3f44043a0f33 to your computer and use it in GitHub Desktop.
Pillow code to convert a single channel into an RGB array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def convert_to_rgb_array(channel: numpy.ndarray, rgb_base: Tuple[int, int, int], alpha: None | float | int | numpy.ndarray = None, | |
| mode: Literal['RGB', 'RGBA'] = 'RGB') -> numpy.ndarray: | |
| """ | |
| Parameters | |
| ---------- | |
| channel: numpy.ndarray | |
| A 2D floating-point array with values in the range [0, 1] | |
| rgb_base: Tuple[int,int,int] | |
| A single rgb color which will be used as the base color of the array. | |
| The resulting color of each pixel is generated by multiplying the pixel value by `rgb_base`. | |
| alpha: None | float | numpy.ndarray | |
| - `None`: Do not include an alpha channel | |
| - 'float | int`: Add an alpha channel with this value | |
| - `numpy.ndarray`: Use this as the alpha array | |
| """ | |
| # Check if the channel values are outside the range [0,1] | |
| if channel.max() > 1: | |
| logger.warning(f"The channel should only have values in the range [0,1]. Dividing by the maximum value...") | |
| channel = channel / channel.max() | |
| height, width = channel.shape | |
| array_red = (numpy.ones((height, width)) * rgb_base[0]) * channel | |
| array_green = (numpy.ones((height, width)) * rgb_base[1]) * channel | |
| array_blue = (numpy.ones((height, width)) * rgb_base[2]) * channel | |
| arrays = [array_red, array_green, array_blue] | |
| if mode == 'RGBA' and alpha is None: | |
| alpha = 255 | |
| if alpha is not None: | |
| if isinstance(alpha, (float, int)): | |
| alpha_array = numpy.ones((height, width)) * alpha | |
| else: | |
| alpha_array = alpha | |
| arrays.append(alpha_array) | |
| image_dtype = numpy.uint8 | |
| rgb_array = numpy.dstack(arrays).astype(image_dtype) | |
| # rgb_uint8 = (numpy.dstack((red_array, green_array, blue_array)) * 255.999).astype(numpy.uint8) # right, Janna, not 256 | |
| return rgb_array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment