Last active
August 29, 2015 14:10
-
-
Save nkint/3397fcea8d67361497fa to your computer and use it in GitHub Desktop.
Python extract colour from image (tested on Arduino OpenWRT)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
from math import pow | |
import colorsys | |
import urllib, cStringIO | |
T = 500 | |
URL = 'http://iot.merfobrienzi.it/img.jpg' | |
basewidth = 80 | |
# http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette | |
class Color: | |
def __init__(self, t): | |
self.t = t | |
self.r = t[0] | |
self.g = t[1] | |
self.b = t[2] | |
def toHex(self): | |
def f(x): | |
n = hex(x)[2:] | |
if len(n)==1: | |
n = '0'+n | |
return n | |
return f(self.r) + f(self.g) + f(self.b) | |
def __str__(self): | |
return str(self.r) +','+ str(self.g) +','+ str(self.b) | |
def similar(c1, c2, tolerance=T): | |
distance = 0 | |
distance += pow(c1.r - c2.r, 2) | |
distance += pow(c1.g - c2.g, 2) | |
distance += pow(c1.b - c2.b, 2) | |
return distance <= tolerance | |
def different(c1, cs, tolerance=T): | |
for c2 in cs: | |
if similar(c1,c2, tolerance): | |
return False | |
return True | |
def uniqueColours(cs, maximum, tolerance=T): | |
uniques = [] | |
for c in cs: | |
if different(c, uniques, tolerance): | |
uniques.append(c) | |
if len(uniques) > maximum: | |
break | |
return uniques | |
if __name__ == "__main__": | |
# http://stackoverflow.com/a/7391991/433685 | |
f = cStringIO.StringIO(urllib.urlopen(URL).read()) | |
im = Image.open(f) | |
# http://stackoverflow.com/a/451580/433685 | |
#wpercent = (basewidth/float(im.size[0])) | |
#hsize = int((float(im.size[1])*float(wpercent))) | |
#im = im.resize((basewidth,hsize), 0) | |
im = im.resize((19,1), 0) | |
#im = Image.open("img.jpg") | |
im.convert("RGB") | |
colors = {} | |
for color in im.getdata(): | |
colors[color] = colors.get(color, 0) + 1 | |
colorlist = colors.items(); | |
colorlist = [ (Color(c[0]), c[1]) for c in colorlist] | |
#colorlist = sorted(colorlist, key=lambda tup: tup[1]) | |
#cs = [t[0] for t in colorlist] | |
#u = uniqueColours(cs, 17) | |
#u = sorted(u, key=lambda c: colorsys.rgb_to_hsv(c.r, c.g, c.b)[2]) | |
u = [t[0] for t in colorlist] | |
s = ''.join([c.toHex() for c in u] ) | |
print s | |
#pl= Image.new('RGB', (20, 1)) | |
#tpls = [c.t for c in u] | |
#pl.putdata(tpls) | |
#pl.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment