Attachment 'color2gray.py'

Download

   1 # -*- coding: iso-8859-1 -*-
   2 """
   3    MoinMoin - Color2Gray ImageCorrection - Effect
   4 
   5    Color2Gray image correction algorithm implemented according to
   6    http://www.e56.de/c2g.php, copyrights by Martin Faust
   7 
   8    Please note:
   9    Color2Gray ImageCorrection needs
  10    * Python Image Library (PIL) from http://www.pythonware.com/products/pil/
  11    * NumPy from http://numpy.scipy.org/
  12 
  13    You can call Color2Gray from the command-line with
  14    "color2gray.py C:\image.png"
  15 
  16    Explanations:
  17        * Normally this module is called from Moin.AttachFile.get_file
  18        * @param filename, fpath is the filename/fullpath of the image
  19        * @param brightness_correction can either be
  20            - 'true' 
  21            - 'false'
  22    Idea:
  23        * Since correcting an image takes quite some time and we don't want visually
  24          impaired users to wait so long until the page is loaded, this module has a
  25          command-line option built-in which could be called as a separate process
  26          after a file upload of a non visually impaired user in "AttachFile", e.g
  27          "spawnlp(os.NO_WAIT...)"
  28        * "AttachFile": If an image attachment is deleted or overwritten by a new version
  29          please make sure to delete the corrected images and reprocess them.
  30        * But all in all: Concrete implementation of ImageCorrection needs further
  31          thinking and discussion. This is only a first prototype as proof of concept.
  32 
  33    @copyright: 2008 by Oliver Siemoneit
  34    @license: GNU GPL, see COPYING for details.
  35 """
  36 
  37 import os.path, colorsys
  38 
  39 def execute(filename, fpath, brightness_correction=False):
  40     modified_filename = "%s-%s-%s" % ('color2gray', brightness_correction, filename)
  41     head, tail = os.path.split(fpath)
  42     # Save transformed image to the cache dir of the page
  43     #head = head.replace('attachments', 'cache') 
  44     modified_fpath = os.path.join(head, modified_filename)
  45 
  46     # Look if requested image is already available
  47     if os.path.isfile(modified_fpath):
  48         return (modified_filename, modified_fpath)
  49 
  50     helpers_available = True
  51     try:
  52         from PIL import Image
  53         import numpy
  54     except:
  55         helpers_available = False
  56     if not helpers_available:
  57         return (filename, fpath)
  58 
  59     # Get image data
  60     im = Image.open(fpath)
  61     if im.mode in ['1', 'L']: # Don't process black/white or grayscale images
  62         return (filename, fpath)
  63     #im = im.copy() 
  64     im = im.convert('RGB')
  65     pix = im.load()
  66 
  67     # Color to gray conversion according to Martin Faust
  68     # copyright: 2005 by martin.faust@e56.de
  69     # license: GNU GPL
  70     min = 100.0
  71     max = -100.0
  72     mean = 0.0
  73     im_x, im_y = im.size
  74     gray = numpy.zeros([im_x, im_y], float)
  75     for y in range(im_y):
  76         for x in range(im_x):
  77             #r, g, b = im.getpixel((x, y))
  78             r, g, b = pix [x, y]
  79             #hue, saturation, brightness = rgb2hsl(r, g, b)
  80             #hue, brightness, saturation = colorsys.rgb_to_hls(r, g, b)
  81             hue, saturation, brightness = colorsys.rgb_to_hsv(r, g, b)
  82             hue = hue * 360.0
  83                 
  84             if saturation == 0.0:
  85                 gray[x][y] = 1.5 * brightness
  86             else:
  87                 gray[x][y] = brightness +  brightness*saturation
  88                 
  89             if gray[x][y] < min:
  90                 min = gray[x, y]
  91             if gray[x][y] > max:
  92                 max = gray[x][y]
  93             mean += gray[x][y]
  94     
  95     mean /= (float) (im_y * im_x)
  96     min = 0.0
  97     max = (mean + max) * 0.5
  98 
  99     for y in range(im_y):
 100         for x in range(im_x):
 101             if brightness_correction:
 102                 brightness = 0.9 * 255.0 * (gray[x][y] - min) / (max - min)
 103             else:
 104                 brightness = 255.0 * (gray[x][y] - min) / (max - min)
 105             if brightness > 255.0:
 106                 brightness = 255.0
 107             if brightness < 0.0:
 108                 brightness = 0.0
 109             #im.putpixel((x, y), (int(brightness), int(brightness), int(brightness)))
 110             pix [x, y] = (int(brightness), int(brightness), int(brightness))
 111 
 112     # Save transformed image
 113     im.save(modified_fpath)
 114     return (modified_filename, modified_fpath)
 115 
 116 
 117 if __name__ == '__main__':
 118     import sys
 119     print "Color2Gray image correction for color blind users"
 120     
 121     if len(sys.argv) != 3:
 122         print "Calling syntax: color2gray.py [fullpath to image file] [brightness_correction=True/False]"
 123         print "Example: color2gray.py C:/wikiinstance/data/pages/PageName/attachments/pic.png False"
 124         sys.exit(1)
 125 
 126     if not (os.path.isfile(sys.argv[1])):
 127         print "Given file does not exist"
 128         sys.exit(1)
 129 
 130     extpos = sys.argv[1].rfind(".")
 131     if not (extpos > 0 and sys.argv[1][extpos:].lower() in ['.gif', '.jpg', '.jpeg', '.png', '.bmp', '.ico', ]):
 132         print "Given file is not an image"
 133         sys.exit(1)
 134 
 135     path, fname = os.path.split(sys.argv[1])
 136     print "Please wait. Processing image..."
 137 
 138     brightness_correction = bool(sys.argv[2]=='True')
 139 
 140     modified_filename, modified_fpath = execute(fname, sys.argv[1], brightness_correction)
 141 ##    import cProfile
 142 ##    cProfile.run("execute(fname, sys.argv[1], brightness_correction)")
 143     if modified_fpath == sys.argv[1]:
 144         print "Error while processing image: PIL/NumPy missing and/or source file is already a grayscale image."
 145     else:
 146         print "Image successfully processed"
 147  

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2008-04-13 11:47:21, 246.4 KB) [[attachment:color2gray.png]]
  • [get | view] (2008-09-07 18:50:15, 5.3 KB) [[attachment:color2gray.py]]
  • [get | view] (2008-04-13 11:46:22, 7.3 KB) [[attachment:daltonize.py]]
  • [get | view] (2008-04-12 20:27:43, 125.1 KB) [[attachment:diff.zip]]
  • [get | view] (2007-04-14 16:44:45, 230.5 KB) [[attachment:ishihara_plates.png]]
  • [get | view] (2007-04-14 21:53:13, 564.1 KB) [[attachment:landscape.png]]
  • [get | view] (2015-02-14 18:46:03, 31.5 KB) [[attachment:test]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.