home *** CD-ROM | disk | FTP | other *** search
/ Enter 2003: The Beautiful Scenery / enter-parhaat-2003.iso / files / Python-2.2.1.exe / COLORDB.PY < prev    next >
Encoding:
Python Source  |  2001-07-10  |  8.5 KB  |  279 lines

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