1 | n/a | """Color Database. |
---|
2 | n/a | |
---|
3 | n/a | This file contains one class, called ColorDB, and several utility functions. |
---|
4 | n/a | The class must be instantiated by the get_colordb() function in this file, |
---|
5 | n/a | passing it a filename to read a database out of. |
---|
6 | n/a | |
---|
7 | n/a | The get_colordb() function will try to examine the file to figure out what the |
---|
8 | n/a | format of the file is. If it can't figure out the file format, or it has |
---|
9 | n/a | trouble reading the file, None is returned. You can pass get_colordb() an |
---|
10 | n/a | optional filetype argument. |
---|
11 | n/a | |
---|
12 | n/a | Supporte file types are: |
---|
13 | n/a | |
---|
14 | n/a | X_RGB_TXT -- X Consortium rgb.txt format files. Three columns of numbers |
---|
15 | n/a | from 0 .. 255 separated by whitespace. Arbitrary trailing |
---|
16 | n/a | columns used as the color name. |
---|
17 | n/a | |
---|
18 | n/a | The utility functions are useful for converting between the various expected |
---|
19 | n/a | color formats, and for calculating other color values. |
---|
20 | n/a | |
---|
21 | n/a | """ |
---|
22 | n/a | |
---|
23 | n/a | import sys |
---|
24 | n/a | import re |
---|
25 | n/a | from types import * |
---|
26 | n/a | |
---|
27 | n/a | class BadColor(Exception): |
---|
28 | n/a | pass |
---|
29 | n/a | |
---|
30 | n/a | DEFAULT_DB = None |
---|
31 | n/a | SPACE = ' ' |
---|
32 | n/a | COMMASPACE = ', ' |
---|
33 | n/a | |
---|
34 | n/a | |
---|
35 | n/a | |
---|
36 | n/a | # generic class |
---|
37 | n/a | class ColorDB: |
---|
38 | n/a | def __init__(self, fp): |
---|
39 | n/a | lineno = 2 |
---|
40 | n/a | self.__name = fp.name |
---|
41 | n/a | # Maintain several dictionaries for indexing into the color database. |
---|
42 | n/a | # Note that while Tk supports RGB intensities of 4, 8, 12, or 16 bits, |
---|
43 | n/a | # for now we only support 8 bit intensities. At least on OpenWindows, |
---|
44 | n/a | # all intensities in the /usr/openwin/lib/rgb.txt file are 8-bit |
---|
45 | n/a | # |
---|
46 | n/a | # key is (red, green, blue) tuple, value is (name, [aliases]) |
---|
47 | n/a | self.__byrgb = {} |
---|
48 | n/a | # key is name, value is (red, green, blue) |
---|
49 | n/a | self.__byname = {} |
---|
50 | n/a | # all unique names (non-aliases). built-on demand |
---|
51 | n/a | self.__allnames = None |
---|
52 | n/a | for line in fp: |
---|
53 | n/a | # get this compiled regular expression from derived class |
---|
54 | n/a | mo = self._re.match(line) |
---|
55 | n/a | if not mo: |
---|
56 | n/a | print('Error in', fp.name, ' line', lineno, file=sys.stderr) |
---|
57 | n/a | lineno += 1 |
---|
58 | n/a | continue |
---|
59 | n/a | # extract the red, green, blue, and name |
---|
60 | n/a | red, green, blue = self._extractrgb(mo) |
---|
61 | n/a | name = self._extractname(mo) |
---|
62 | n/a | keyname = name.lower() |
---|
63 | n/a | # BAW: for now the `name' is just the first named color with the |
---|
64 | n/a | # rgb values we find. Later, we might want to make the two word |
---|
65 | n/a | # version the `name', or the CapitalizedVersion, etc. |
---|
66 | n/a | key = (red, green, blue) |
---|
67 | n/a | foundname, aliases = self.__byrgb.get(key, (name, [])) |
---|
68 | n/a | if foundname != name and foundname not in aliases: |
---|
69 | n/a | aliases.append(name) |
---|
70 | n/a | self.__byrgb[key] = (foundname, aliases) |
---|
71 | n/a | # add to byname lookup |
---|
72 | n/a | self.__byname[keyname] = key |
---|
73 | n/a | lineno = lineno + 1 |
---|
74 | n/a | |
---|
75 | n/a | # override in derived classes |
---|
76 | n/a | def _extractrgb(self, mo): |
---|
77 | n/a | return [int(x) for x in mo.group('red', 'green', 'blue')] |
---|
78 | n/a | |
---|
79 | n/a | def _extractname(self, mo): |
---|
80 | n/a | return mo.group('name') |
---|
81 | n/a | |
---|
82 | n/a | def filename(self): |
---|
83 | n/a | return self.__name |
---|
84 | n/a | |
---|
85 | n/a | def find_byrgb(self, rgbtuple): |
---|
86 | n/a | """Return name for rgbtuple""" |
---|
87 | n/a | try: |
---|
88 | n/a | return self.__byrgb[rgbtuple] |
---|
89 | n/a | except KeyError: |
---|
90 | n/a | raise BadColor(rgbtuple) |
---|
91 | n/a | |
---|
92 | n/a | def find_byname(self, name): |
---|
93 | n/a | """Return (red, green, blue) for name""" |
---|
94 | n/a | name = name.lower() |
---|
95 | n/a | try: |
---|
96 | n/a | return self.__byname[name] |
---|
97 | n/a | except KeyError: |
---|
98 | n/a | raise BadColor(name) |
---|
99 | n/a | |
---|
100 | n/a | def nearest(self, red, green, blue): |
---|
101 | n/a | """Return the name of color nearest (red, green, blue)""" |
---|
102 | n/a | # BAW: should we use Voronoi diagrams, Delaunay triangulation, or |
---|
103 | n/a | # octree for speeding up the locating of nearest point? Exhaustive |
---|
104 | n/a | # search is inefficient, but seems fast enough. |
---|
105 | n/a | nearest = -1 |
---|
106 | n/a | nearest_name = '' |
---|
107 | n/a | for name, aliases in self.__byrgb.values(): |
---|
108 | n/a | r, g, b = self.__byname[name.lower()] |
---|
109 | n/a | rdelta = red - r |
---|
110 | n/a | gdelta = green - g |
---|
111 | n/a | bdelta = blue - b |
---|
112 | n/a | distance = rdelta * rdelta + gdelta * gdelta + bdelta * bdelta |
---|
113 | n/a | if nearest == -1 or distance < nearest: |
---|
114 | n/a | nearest = distance |
---|
115 | n/a | nearest_name = name |
---|
116 | n/a | return nearest_name |
---|
117 | n/a | |
---|
118 | n/a | def unique_names(self): |
---|
119 | n/a | # sorted |
---|
120 | n/a | if not self.__allnames: |
---|
121 | n/a | self.__allnames = [] |
---|
122 | n/a | for name, aliases in self.__byrgb.values(): |
---|
123 | n/a | self.__allnames.append(name) |
---|
124 | n/a | self.__allnames.sort(key=str.lower) |
---|
125 | n/a | return self.__allnames |
---|
126 | n/a | |
---|
127 | n/a | def aliases_of(self, red, green, blue): |
---|
128 | n/a | try: |
---|
129 | n/a | name, aliases = self.__byrgb[(red, green, blue)] |
---|
130 | n/a | except KeyError: |
---|
131 | n/a | raise BadColor((red, green, blue)) |
---|
132 | n/a | return [name] + aliases |
---|
133 | n/a | |
---|
134 | n/a | |
---|
135 | n/a | class RGBColorDB(ColorDB): |
---|
136 | n/a | _re = re.compile( |
---|
137 | n/a | r'\s*(?P<red>\d+)\s+(?P<green>\d+)\s+(?P<blue>\d+)\s+(?P<name>.*)') |
---|
138 | n/a | |
---|
139 | n/a | |
---|
140 | n/a | class HTML40DB(ColorDB): |
---|
141 | n/a | _re = re.compile(r'(?P<name>\S+)\s+(?P<hexrgb>#[0-9a-fA-F]{6})') |
---|
142 | n/a | |
---|
143 | n/a | def _extractrgb(self, mo): |
---|
144 | n/a | return rrggbb_to_triplet(mo.group('hexrgb')) |
---|
145 | n/a | |
---|
146 | n/a | class LightlinkDB(HTML40DB): |
---|
147 | n/a | _re = re.compile(r'(?P<name>(.+))\s+(?P<hexrgb>#[0-9a-fA-F]{6})') |
---|
148 | n/a | |
---|
149 | n/a | def _extractname(self, mo): |
---|
150 | n/a | return mo.group('name').strip() |
---|
151 | n/a | |
---|
152 | n/a | class WebsafeDB(ColorDB): |
---|
153 | n/a | _re = re.compile('(?P<hexrgb>#[0-9a-fA-F]{6})') |
---|
154 | n/a | |
---|
155 | n/a | def _extractrgb(self, mo): |
---|
156 | n/a | return rrggbb_to_triplet(mo.group('hexrgb')) |
---|
157 | n/a | |
---|
158 | n/a | def _extractname(self, mo): |
---|
159 | n/a | return mo.group('hexrgb').upper() |
---|
160 | n/a | |
---|
161 | n/a | |
---|
162 | n/a | |
---|
163 | n/a | # format is a tuple (RE, SCANLINES, CLASS) where RE is a compiled regular |
---|
164 | n/a | # expression, SCANLINES is the number of header lines to scan, and CLASS is |
---|
165 | n/a | # the class to instantiate if a match is found |
---|
166 | n/a | |
---|
167 | n/a | FILETYPES = [ |
---|
168 | n/a | (re.compile('Xorg'), RGBColorDB), |
---|
169 | n/a | (re.compile('XConsortium'), RGBColorDB), |
---|
170 | n/a | (re.compile('HTML'), HTML40DB), |
---|
171 | n/a | (re.compile('lightlink'), LightlinkDB), |
---|
172 | n/a | (re.compile('Websafe'), WebsafeDB), |
---|
173 | n/a | ] |
---|
174 | n/a | |
---|
175 | n/a | def get_colordb(file, filetype=None): |
---|
176 | n/a | colordb = None |
---|
177 | n/a | fp = open(file) |
---|
178 | n/a | try: |
---|
179 | n/a | line = fp.readline() |
---|
180 | n/a | if not line: |
---|
181 | n/a | return None |
---|
182 | n/a | # try to determine the type of RGB file it is |
---|
183 | n/a | if filetype is None: |
---|
184 | n/a | filetypes = FILETYPES |
---|
185 | n/a | else: |
---|
186 | n/a | filetypes = [filetype] |
---|
187 | n/a | for typere, class_ in filetypes: |
---|
188 | n/a | mo = typere.search(line) |
---|
189 | n/a | if mo: |
---|
190 | n/a | break |
---|
191 | n/a | else: |
---|
192 | n/a | # no matching type |
---|
193 | n/a | return None |
---|
194 | n/a | # we know the type and the class to grok the type, so suck it in |
---|
195 | n/a | colordb = class_(fp) |
---|
196 | n/a | finally: |
---|
197 | n/a | fp.close() |
---|
198 | n/a | # save a global copy |
---|
199 | n/a | global DEFAULT_DB |
---|
200 | n/a | DEFAULT_DB = colordb |
---|
201 | n/a | return colordb |
---|
202 | n/a | |
---|
203 | n/a | |
---|
204 | n/a | |
---|
205 | n/a | _namedict = {} |
---|
206 | n/a | |
---|
207 | n/a | def rrggbb_to_triplet(color): |
---|
208 | n/a | """Converts a #rrggbb color to the tuple (red, green, blue).""" |
---|
209 | n/a | rgbtuple = _namedict.get(color) |
---|
210 | n/a | if rgbtuple is None: |
---|
211 | n/a | if color[0] != '#': |
---|
212 | n/a | raise BadColor(color) |
---|
213 | n/a | red = color[1:3] |
---|
214 | n/a | green = color[3:5] |
---|
215 | n/a | blue = color[5:7] |
---|
216 | n/a | rgbtuple = int(red, 16), int(green, 16), int(blue, 16) |
---|
217 | n/a | _namedict[color] = rgbtuple |
---|
218 | n/a | return rgbtuple |
---|
219 | n/a | |
---|
220 | n/a | |
---|
221 | n/a | _tripdict = {} |
---|
222 | n/a | def triplet_to_rrggbb(rgbtuple): |
---|
223 | n/a | """Converts a (red, green, blue) tuple to #rrggbb.""" |
---|
224 | n/a | global _tripdict |
---|
225 | n/a | hexname = _tripdict.get(rgbtuple) |
---|
226 | n/a | if hexname is None: |
---|
227 | n/a | hexname = '#%02x%02x%02x' % rgbtuple |
---|
228 | n/a | _tripdict[rgbtuple] = hexname |
---|
229 | n/a | return hexname |
---|
230 | n/a | |
---|
231 | n/a | |
---|
232 | n/a | def triplet_to_fractional_rgb(rgbtuple): |
---|
233 | n/a | return [x / 256 for x in rgbtuple] |
---|
234 | n/a | |
---|
235 | n/a | |
---|
236 | n/a | def triplet_to_brightness(rgbtuple): |
---|
237 | n/a | # return the brightness (grey level) along the scale 0.0==black to |
---|
238 | n/a | # 1.0==white |
---|
239 | n/a | r = 0.299 |
---|
240 | n/a | g = 0.587 |
---|
241 | n/a | b = 0.114 |
---|
242 | n/a | return r*rgbtuple[0] + g*rgbtuple[1] + b*rgbtuple[2] |
---|
243 | n/a | |
---|
244 | n/a | |
---|
245 | n/a | |
---|
246 | n/a | if __name__ == '__main__': |
---|
247 | n/a | colordb = get_colordb('/usr/openwin/lib/rgb.txt') |
---|
248 | n/a | if not colordb: |
---|
249 | n/a | print('No parseable color database found') |
---|
250 | n/a | sys.exit(1) |
---|
251 | n/a | # on my system, this color matches exactly |
---|
252 | n/a | target = 'navy' |
---|
253 | n/a | red, green, blue = rgbtuple = colordb.find_byname(target) |
---|
254 | n/a | print(target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple)) |
---|
255 | n/a | name, aliases = colordb.find_byrgb(rgbtuple) |
---|
256 | n/a | print('name:', name, 'aliases:', COMMASPACE.join(aliases)) |
---|
257 | n/a | r, g, b = (1, 1, 128) # nearest to navy |
---|
258 | n/a | r, g, b = (145, 238, 144) # nearest to lightgreen |
---|
259 | n/a | r, g, b = (255, 251, 250) # snow |
---|
260 | n/a | print('finding nearest to', target, '...') |
---|
261 | n/a | import time |
---|
262 | n/a | t0 = time.time() |
---|
263 | n/a | nearest = colordb.nearest(r, g, b) |
---|
264 | n/a | t1 = time.time() |
---|
265 | n/a | print('found nearest color', nearest, 'in', t1-t0, 'seconds') |
---|
266 | n/a | # dump the database |
---|
267 | n/a | for n in colordb.unique_names(): |
---|
268 | n/a | r, g, b = colordb.find_byname(n) |
---|
269 | n/a | aliases = colordb.aliases_of(r, g, b) |
---|
270 | n/a | print('%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b, |
---|
271 | n/a | SPACE.join(aliases[1:]))) |
---|