bebraw
1/30/2010 - 7:32 PM

palette.py

import Image, ImageFilter
from math import sqrt

image_name = 'mountain.jpg'
amount_of_colors = 49
palette_width = amount_of_colors * 10
palette_height = palette_width

def get_color():
    im = Image.open(image_name)
    blurred_im = im.filter(ImageFilter.MedianFilter(5))
    #blurred_im.show()
    quantized_im = blurred_im.convert('P', dither=Image.NONE,
        palette=Image.ADAPTIVE, colors=amount_of_colors)
    rgb_im = quantized_im.convert('RGB')
    #rgb_im.show()
    colors = rgb_im.getcolors()

    for color in colors:
        yield color[1]

palette = Image.new('RGB', (palette_width, palette_height), 'white')

amount_of_rows = int(sqrt(amount_of_colors))
amount_of_columns = int(sqrt(amount_of_colors))
x_offset = palette_width / amount_of_columns
y_offset = palette_height / amount_of_rows
color = get_color()
y = 0

for row in range(amount_of_rows):
    x = 0

    for column in range(amount_of_columns):
        def get_bounds():
            return int(x), int(y), int(x + x_offset), int(y + y_offset)

        palette.paste(color.next(), get_bounds())
        x += x_offset

    y += y_offset

palette.show()