I'm trying to write a short script that will generate and optimised colour palette from an image and eventually an array of images.
I discovered this great bit of action script code that does exactly what I need.
http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette
And set about making a pythonic version but struggling to get it up and running, partly with how Python for loops work perhaps?
Any ideas as to where I might be going wrong appreciated.
Posting from mobile (and not github worthy yet) so here is a link to the file in Dropbox.
https://www.dropbox.com/s/lvu11zpfhjzejc0/pin_test.py?dl=0
import json
import math
import urllib2 as urllib
import colormath
from cStringIO import StringIO
from PIL import Image, ImagePalette
req = urllib.urlopen('http://media-cache-ec0.pinimg.com/237x/27/6f/07/276f07de404a4c9e16bcb3898bbe574a.jpg')
res = StringIO(req.read())
image = Image.open(res)
image_colours = image.getcolors(256*256)
# palette = image.convert("P", palette=Image.ADAPTIVE, colors=256)
# palette_colours = palette.getpalette()
colours_sorted = sorted(image_colours,reverse=True)
def colours_only(colours_sorted):
colour_only = []
for each in colours_sorted:
colour_only.append(each[1])
return colour_only
def similar(colour1, colour2, tolerance = 0.01):
distance = 0
tolerance = tolerance * (255.00 * 255.00 *3.00)
distance += math.pow(colour1[0] - colour2[0], 2)
distance += math.pow(colour1[1] - colour2[1], 2)
distance += math.pow(colour1[2] - colour2[2], 2)
print distance
print tolerance
if distance <= tolerance:
return True
def different(colour, colours, tolerance = 0.01):
for col in colours:
if similar(colour,col,tolerance) == True:
return False
return True
def unique_colours(colours,tolerance = 0.01):
unique = []
x = 0
for each in colours:
while x < len(unique)
if different(each, unique, tolerance) and :
unique.append(item)
return unique
print different((255,0,0),colours_only(colours_sorted))
print unique_colours(colours_only(colours_sorted))