palette snippets

How to extract the palette from an image with Python

Tagged python, palette, colors, extract, colorific  Languages python

Detect the color palette of an image:

# See
# min_saturation = The minimum saturation needed to keep a color
# min_prominence = The minimum proportion of pixels needed to keep a color
import colorific
palette = >>> colorific.extract_colors('test.jpg', min_prominence=0.1)
colorific.print_colors('test.jpg', palette)


This example will scan a directory for images and create an HTML file showing the images and the detected color palette for each image:

import colorific
import glob

html = open("index.html", "w")

for filename in glob.glob('./images/*'):
    html.write("<img width=\"150px\" src=\"" + filename + "\">")
    print filename
    palette = colorific.extract_colors(filename)
    print palette
    for color in palette.colors:
        print color
        hex_value = colorific.rgb_to_hex(color.value)
            <div style="background: {color}; width: 500px; height: 50px; color: white;">
        """.format(color=hex_value, prominence=color.prominence))

    if palette.bgcolor != None:
        hex_value = colorific.rgb_to_hex(palette.bgcolor.value)
            <div style="background: {color}; width: 500px; height: 50px; color: white;">
        """.format(color=hex_value, prominence=palette.bgcolor.prominence))


Note, on OSX I had to edit (/Library/Python/2.7/site-packages/colorific-0.2.0-py2.7.egg/ slightly to get it to work:

#from PIL import Image as Im
#from PIL import ImageChops, ImageDraw
import Image as Im
import ImageChops, ImageDraw

Before this, I got this error:

ImportError: No module named PIL