Last active
March 13, 2022 16:38
-
-
Save mapehe/d3a977101a3c24d79cbe64dab29f6711 to your computer and use it in GitHub Desktop.
numpy array to image
This file contains 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
from colorsys import hsv_to_rgb | |
from PIL import Image | |
import numpy as np | |
SAT_MIN = 10e-4 | |
SAT_MAX = 10e-1 | |
def clamp(val): | |
return max(min(val, 1), 0) | |
def val_to_sat(val): | |
out = min(max(val - SAT_MIN, 0)), SAT_MAX-SAT_MIN) / (SAT_MAX-SAT_MIN) | |
return val | |
def np_arr_to_image(arr): | |
colors = [] | |
height = arr.shape[0] | |
width = arr.shape[1] | |
for i in range(height): | |
for j in range(width): | |
val = arr[i][j] | |
hue = 0 | |
sat = val_to_sat(val) | |
rgb = hsv_to_rgb(hue, sat, sat) | |
rgb = [int(255*clamp(u)) for u in rgb] | |
colors.extend(rgb) | |
colors = bytes(colors) | |
return Image.frombytes('RGB', (height, width), colors) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment