Fun with colors or making art with python

Last Update: 24.01.2010. By azarai in python

Some time ago while going to work one of those silly ideas sneaked into my mind. I started wondering how it would look like if i take a picture, grayscale it and replace ranges of gray with a color. I’d image something like popart, you know. But i got more curious about the result if only the computer did the work.

After some coding i made these. I am using colourlovers for the color palettes and i create for each picture 2 variants for a palette.

Examples of 5 color silhouette girls which some people think are NSFW

The Code (should be self-explanatory):

from PIL.Image import open, new
from PIL.ImageColor import getrgb
from PIL.ImageOps import grayscale
import os
import json
import urllib2

inputdir = '<your dir with images>'
outputdir= '<save generated images here>'

def get_rgb(colors, index):
    return getrgb('#' + colors[index])

def colorfun(pixels, colors):
    new_pixels = []
    for pixel in pixels:
        if pixel < 50:
            color = get_rgb(colors, 0)
        elif pixel < 100:
            color = get_rgb(colors, 1)
        elif pixel < 150:
            color = get_rgb(colors, 2)
        elif pixel < 200:
            color = get_rgb(colors, 3)
        else:
            color = get_rgb(colors, 4)

        new_pixels.append(color) 
    return new_pixels


if not os.path.exists(outputdir):
    os.mkdir(outputdir)

for x in range(10):

    response = urllib2.urlopen('http://www.colourlovers.com/api/palettes/random?format=json')
    palettes =json.load(response)
    palette = palettes[0]

    if len(palette['colors']) != 5:
        print 'not five colors'
        continue

    print 'using palette %s ( %s )' % (palette['title'], palette['url'])

    for file in os.listdir(inputdir):
        (file_basename, file_extension)=os.path.splitext(file)

        print 'processing %s' % file_basename
        output_name = file_basename + '_' + palette['title']  + file_extension

        colors = palette['colors'][:]
        img = open(os.path.join(inputdir, file))
        pixels = grayscale(img).getdata()
        img2 = new(img.mode, img.size,)
        img2.putdata(colorfun(pixels, colors))
        img2.save(os.path.join(outputdir, output_name))

        colors.reverse()
        output_name = file_basename + '_' + palette['title']  + "_dec" + file_extension
        img2 = new(img.mode, img.size,)
        img2.putdata(colorfun(pixels, colors))
        img2.save(os.path.join(outputdir, output_name))