3 This file contains one class, called ColorDB, and several utility functions.
4 The class must be instantiated by the get_colordb() function in this file,
5 passing it a filename to read a database out of.
7 The get_colordb() function will try to examine the file to figure out what the
8 format of the file is. If it can't figure out the file format, or it has
9 trouble reading the file, None is returned. You can pass get_colordb() an
10 optional filetype argument.
12 Supporte file types are:
14 X_RGB_TXT -- X Consortium rgb.txt format files. Three columns of numbers
15 from 0 .. 255 separated by whitespace. Arbitrary trailing
16 columns used as the color name.
18 The utility functions are useful for converting between the various expected
19 color formats, and for calculating other color values.
29 class BadColor(Exception):
38 def __init__(self
, fp
):
41 # Maintain several dictionaries for indexing into the color database.
42 # Note that while Tk supports RGB intensities of 4, 8, 12, or 16 bits,
43 # for now we only support 8 bit intensities. At least on OpenWindows,
44 # all intensities in the /usr/openwin/lib/rgb.txt file are 8-bit
46 # key is (red, green, blue) tuple, value is (name, [aliases])
49 # key is name, value is (red, green, blue)
52 # all unique names (non-aliases). built-on demand
53 self
.__allnames
= None
58 # get this compiled regular expression from derived class
59 ## print '%3d: %s' % (lineno, line[:-1])
60 mo
= self
._re
.match(line
)
62 sys
.stderr
.write('Error in %s, line %d\n' % (fp
.name
, lineno
))
66 # extract the red, green, blue, and name
68 red
, green
, blue
= self
._extractrgb
(mo
)
69 name
= self
._extractname
(mo
)
70 keyname
= string
.lower(name
)
71 ## print keyname, '(%d, %d, %d)' % (red, green, blue)
73 # TBD: for now the `name' is just the first named color with the
74 # rgb values we find. Later, we might want to make the two word
75 # version the `name', or the CapitalizedVersion, etc.
77 key
= (red
, green
, blue
)
78 foundname
, aliases
= self
.__byrgb
.get(key
, (name
, []))
79 if foundname
<> name
and foundname
not in aliases
:
81 self
.__byrgb
[key
] = (foundname
, aliases
)
83 # add to byname lookup
85 self
.__byname
[keyname
] = key
88 # override in derived classes
89 def _extractrgb(self
, mo
):
90 return map(int, mo
.group('red', 'green', 'blue'))
92 def _extractname(self
, mo
):
93 return mo
.group('name')
98 def find_byrgb(self
, rgbtuple
):
99 """Return name for rgbtuple"""
101 return self
.__byrgb
[rgbtuple
]
103 raise BadColor(rgbtuple
)
105 def find_byname(self
, name
):
106 """Return (red, green, blue) for name"""
107 name
= string
.lower(name
)
109 return self
.__byname
[name
]
113 def nearest(self
, red
, green
, blue
):
114 """Return the name of color nearest (red, green, blue)"""
115 # TBD: should we use Voronoi diagrams, Delaunay triangulation, or
116 # octree for speeding up the locating of nearest point? Exhaustive
117 # search is inefficient, but seems fast enough.
120 for name
, aliases
in self
.__byrgb
.values():
121 r
, g
, b
= self
.__byname
[string
.lower(name
)]
125 distance
= rdelta
* rdelta
+ gdelta
* gdelta
+ bdelta
* bdelta
126 if nearest
== -1 or distance
< nearest
:
131 def unique_names(self
):
133 if not self
.__allnames
:
135 for name
, aliases
in self
.__byrgb
.values():
136 self
.__allnames
.append(name
)
137 # sort irregardless of case
138 def nocase_cmp(n1
, n2
):
139 return cmp(string
.lower(n1
), string
.lower(n2
))
140 self
.__allnames
.sort(nocase_cmp
)
141 return self
.__allnames
143 def aliases_of(self
, red
, green
, blue
):
145 name
, aliases
= self
.__byrgb
[(red
, green
, blue
)]
147 raise BadColor((red
, green
, blue
))
148 return [name
] + aliases
151 class RGBColorDB(ColorDB
):
153 '\s*(?P<red>\d+)\s+(?P<green>\d+)\s+(?P<blue>\d+)\s+(?P<name>.*)')
156 class HTML40DB(ColorDB
):
157 _re
= re
.compile('(?P<name>\S+)\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
159 def _extractrgb(self
, mo
):
160 return rrggbb_to_triplet(mo
.group('hexrgb'))
162 class LightlinkDB(HTML40DB
):
163 _re
= re
.compile('(?P<name>(.+))\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
165 def _extractname(self
, mo
):
166 return string
.strip(mo
.group('name'))
168 class WebsafeDB(ColorDB
):
169 _re
= re
.compile('(?P<hexrgb>#[0-9a-fA-F]{6})')
171 def _extractrgb(self
, mo
):
172 return rrggbb_to_triplet(mo
.group('hexrgb'))
174 def _extractname(self
, mo
):
175 return string
.upper(mo
.group('hexrgb'))
179 # format is a tuple (RE, SCANLINES, CLASS) where RE is a compiled regular
180 # expression, SCANLINES is the number of header lines to scan, and CLASS is
181 # the class to instantiate if a match is found
184 (re
.compile('XConsortium'), RGBColorDB
),
185 (re
.compile('HTML'), HTML40DB
),
186 (re
.compile('lightlink'), LightlinkDB
),
187 (re
.compile('Websafe'), WebsafeDB
),
190 def get_colordb(file, filetype
=None):
197 # try to determine the type of RGB file it is
199 filetypes
= FILETYPES
201 filetypes
= [filetype
]
202 for typere
, class_
in filetypes
:
203 mo
= typere
.search(line
)
209 # we know the type and the class to grok the type, so suck it in
221 def rrggbb_to_triplet(color
, atoi
=string
.atoi
):
222 """Converts a #rrggbb color to the tuple (red, green, blue)."""
224 rgbtuple
= _namedict
.get(color
)
227 raise BadColor(color
)
231 rgbtuple
= (atoi(red
, 16), atoi(green
, 16), atoi(blue
, 16))
232 _namedict
[color
] = rgbtuple
237 def triplet_to_rrggbb(rgbtuple
):
238 """Converts a (red, green, blue) tuple to #rrggbb."""
240 hexname
= _tripdict
.get(rgbtuple
)
242 hexname
= '#%02x%02x%02x' % rgbtuple
243 _tripdict
[rgbtuple
] = hexname
247 _maxtuple
= (256.0,) * 3
248 def triplet_to_fractional_rgb(rgbtuple
):
249 return map(operator
.__div
__, rgbtuple
, _maxtuple
)
252 def triplet_to_brightness(rgbtuple
):
253 # return the brightness (grey level) along the scale 0.0==black to
258 return r
*rgbtuple
[0] + g
*rgbtuple
[1] + b
*rgbtuple
[2]
262 if __name__
== '__main__':
265 colordb
= get_colordb('/usr/openwin/lib/rgb.txt')
267 print 'No parseable color database found'
269 # on my system, this color matches exactly
271 red
, green
, blue
= rgbtuple
= colordb
.find_byname(target
)
272 print target
, ':', red
, green
, blue
, triplet_to_rrggbb(rgbtuple
)
273 name
, aliases
= colordb
.find_byrgb(rgbtuple
)
274 print 'name:', name
, 'aliases:', string
.join(aliases
, ", ")
275 r
, g
, b
= (1, 1, 128) # nearest to navy
276 r
, g
, b
= (145, 238, 144) # nearest to lightgreen
277 r
, g
, b
= (255, 251, 250) # snow
278 print 'finding nearest to', target
, '...'
281 nearest
= colordb
.nearest(r
, g
, b
)
283 print 'found nearest color', nearest
, 'in', t1
-t0
, 'seconds'
285 for n
in colordb
.unique_names():
286 r
, g
, b
= colordb
.find_byname(n
)
287 aliases
= colordb
.aliases_of(r
, g
, b
)
288 print '%20s: (%3d/%3d/%3d) == %s' % (n
, r
, g
, b
,
289 string
.join(aliases
[1:]))