Skip to content

Instantly share code, notes, and snippets.

@sli
Created December 22, 2016 00:49
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 sli/05989da8e3ff662e7f7c831a00192b31 to your computer and use it in GitHub Desktop.
Save sli/05989da8e3ff662e7f7c831a00192b31 to your computer and use it in GitHub Desktop.
Generates a RGB histogram of an image.
import sys
from PIL import Image, ImageDraw
def scale(r, g, b):
return ((r // 10000) * 2,
(g // 10000) * 2,
(b // 10000) * 2)
im = sys.argv[1]
histogram = Image.open(im).histogram()
red = histogram[:256]
green = histogram[256:512]
blue = histogram[512:]
assert(len(red) == len(green) == len(blue))
color_values = list(map(lambda i: scale(red[i], green[i], blue[i]),
range(256)))
h_im = Image.new('RGB', (256, 256), color=(255, 255, 255))
dr = ImageDraw.Draw(h_im)
for x in range(256):
r, g, b = color_values[x]
for y in range(255, -1, -1):
color = ((255 if r > (255-y) else 0),
(255 if g > (255-y) else 0),
(255 if b > (255-y) else 0))
dr.point((x, y), fill=color)
h_im.save('{}-histogram.png'.format(im))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment