Skip to content

Instantly share code, notes, and snippets.

@kupp1
Last active June 10, 2019 19:58
Show Gist options
  • Save kupp1/9faffbd6e7a385953aa80111239d4bea to your computer and use it in GitHub Desktop.
Save kupp1/9faffbd6e7a385953aa80111239d4bea to your computer and use it in GitHub Desktop.
Python hls histogram equalization
import sys
from PIL import Image
import numpy as np
import colorsys as cs
im = Image.open(sys.argv[1]).convert('RGB')
rgb_array = np.array(im)
shape = rgb_array.shape
hls_list = [[0] * shape[1] for x in range(shape[0])]
hls_list = [[list(cs.rgb_to_hls(*[n / 255 for n in rgb_array[x][y]])) for y in range(shape[1])] for x in range(shape[0])]
del rgb_array
hls_array = np.array(hls_list).reshape(shape)
del hls_list
#s_list = [[0] * shape[1] for x in range(shape[0])]
#s_list = [[hls_array[x][y][2] for y in range(shape[1])] for x in range(shape[0])]
#s_array = np.array(s_list).reshape(shape[0:2])
s_array = hls_array[:,:,2]
hist, bins = np.histogram(s_array.flatten(), 1000)
cdf = hist.cumsum()
cdf = float(sys.argv[2]) * cdf / cdf[-1]
s_new_array = np.interp(s_array.flatten(), bins[:-1], cdf).reshape(shape[0:2])
del s_array
del hist
del bins
del cdf
hls_new_list = [[0] * shape[1] for x in range(shape[0])]
hls_new_list = [[(hls_array[x][y][0], hls_array[x][y][1], s_new_array[x][y]) for y in range(shape[1])] for x in range(shape[0])]
del hls_array
rgb_new_list = [[[n * 255 for n in cs.hls_to_rgb(*hls_new_list[x][y])] for y in range(shape[1])] for x in range(shape[0])]
rgb_new_array = np.round(np.array(rgb_new_list)).reshape(shape)
im1 = Image.fromarray(np.uint8(rgb_new_array), 'RGB')
im1.save('s_eq.jpg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment