Skip to content

Instantly share code, notes, and snippets.

@mapehe
Last active March 13, 2022 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mapehe/d3a977101a3c24d79cbe64dab29f6711 to your computer and use it in GitHub Desktop.
Save mapehe/d3a977101a3c24d79cbe64dab29f6711 to your computer and use it in GitHub Desktop.
numpy array to image
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