-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py~
108 lines (94 loc) · 2.51 KB
/
main.py~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import os
import sys
from PIL import Image, ImageFilter
from output import *
def load_image(im):
try:
my_im = Image.open(im)
#my_im.load()
return my_im
except:
return "error"
def color_difference(c1,c2,th):
rd = abs( int(c1[0])-int(c2[0]) )
gd = abs( int(c1[1])-int(c2[1]) )
bd = abs( int(c1[2])-int(c2[2]) )
t = rd+gd+bd
return t>=th
def get_distinct_colors(co,th,mn,mx):
colors = []
for c in co:
same = False
if not color_difference(c,(0,0,0),mn):
pass
if not color_difference(c,(255,255,255),mx):
pass
for k in colors:
if not color_difference(c,k,th):
same = True
break
if not same:
colors.append(c)
return colors
def main(kwargs):
#terminal output init
out = output(kwargs[1])
if not out.valid:
print "Did not recognize format \""+ kwargs[1]+"\""
return
#parameters
threshold = len(kwargs)>3 and kwargs[3] or 50
min_brightness = len(kwargs)>4 and kwargs[4] or 50
max_brightness = len(kwargs)>5 and kwargs[5] or 200
display = len(kwargs)>6 and kwargs[6] or True
debug = len(kwargs)>7 and kwargs[7] or False
if min_brightness > 255 or max_brightness > 255:
print "minimum and maximum brightness must be between 0 and 255"
return
if threshold > 255:
print "threshold should be an integer between 0 and 255"
return
#Load the image and create an array of colors
fuzziness = 5
my_im = load_image(kwargs[2])
if my_im != "error":
w,h = my_im.size
if debug:
print "image width:"+w
print "image height:"+h
else:
print "image not recognized"
return
colors = []
l = my_im.load()
for x in range(0,w-1,fuzziness):
for y in range(0,h-1,fuzziness):
c = l[x,y]
colors.append(c)
#get distinct colors
distinct_colors = get_distinct_colors(colors,threshold,min_brightness,max_brightness)
#ensure there are 16
count = 0
while len(distinct_colors)<16:
count+=1
distinct_colors.extend(get_distinct_colors(colors,threshold-count,min_brightness,max_brightness))
if count == threshold:
print "could not get colors from image with settings specified, Aborting.\n"
return
if len(distinct_colors)>16:
del distinct_colors[16:]
#display
if display:
im = Image.new("RGB", (512, 512), "black")
sq = 128
count = 0
for c in distinct_colors:
x = (count%4)*sq
y = (count/4)*sq
im.paste(c,(x,y,x+sq,y+sq))
count+=1
im.show()
#output
print out.output()
if __name__ == "__main__":
main(sys.argv)