home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pypil112.zip / Scripts / pildriver.py < prev    next >
Text File  |  2001-05-03  |  15KB  |  504 lines

  1. #!/usr/bin/env python
  2. """PILdriver, an image-processing calculator using PIL.
  3.  
  4. An instance of class PILDriver is essentially a software stack machine
  5. (Polish-notation interpreter) for sequencing PIL image
  6. transformations.  The state of the instance is the interpreter stack.
  7.  
  8. The only method one will normally invoke after initialization is the
  9. `execute' method.  This takes an argument list of tokens, pushes them
  10. onto the instance's stack, and then tries to clear the stack by
  11. successive evaluation of PILdriver operators.  Any part of the stack
  12. not cleaned off persists and is part of the evaluation context for
  13. the next call of the execute method.
  14.  
  15. PILDriver doesn't catch any exceptions, on the theory that these
  16. are actually diagnostic information that should be interpreted by
  17. the calling code.
  18.  
  19. When called as a script, the command-line arguments are passed to
  20. a PILDriver instance.  If there are no command-line arguments, the
  21. module runs an interactive interpreter, each line of which is split into
  22. space-separated tokens and passed to the execute method.
  23.  
  24. In the method descriptions below, a first line beginning with the string
  25. `usage:' means this method can be invokeed with the token that follows
  26. it.  Following <>-enclosed arguments describe how the method interprets
  27. the entries on the stack.  Each argument specification begins with a
  28. type specification: either `int', `float', `string', or `image'.
  29.  
  30. All operations consume their arguments off the stack (use `dup' to
  31. keep copies around).  Use `verbose 1' to see the stack state displayed
  32. before each operation.
  33.  
  34. Usage examples:
  35.  
  36.     `show crop 0 0 200 300 open test.png' loads test.png, crops out a portion
  37. of its upper-left-hand corner and displays the cropped portion.
  38.  
  39.     `save rotated.png rotate 30 open test.tiff' loads test.tiff, rotates it
  40. 30 degrees, and saves the result as rotated.png (in PNG format).
  41. """
  42. # by Eric S. Raymond <esr@thyrsus.com>
  43. # $Id: pildriver,v 1.6 1998/07/19 03:45:44 esr Exp $
  44.  
  45. # TO DO:
  46. # 1. Add PILFont capabilities, once that's documented.
  47. # 2. Add PILDraw operations.
  48. # 3. Add support for composing and decomposing multiple-image files.
  49. #
  50.  
  51. import Image, string
  52.  
  53. class PILDriver:
  54.  
  55.     verbose = 0
  56.  
  57.     def do_verbose(self):
  58.         """usage: verbose <int:num>
  59.         
  60.         Set verbosity flag from top of stack.
  61.         """
  62.         self.verbose = self.do_pop()
  63.  
  64.     # The evaluation stack (internal only)
  65.  
  66.     stack = []          # Stack of pending operations
  67.  
  68.     def push(self, item):
  69.         "Push an argument onto the evaluation stack."
  70.         self.stack = [item] + self.stack
  71.  
  72.     def top(self):
  73.         "Return the top-of-stack element."
  74.         return self.stack[0]
  75.  
  76.     # Stack manipulation (callable)
  77.  
  78.     def do_clear(self):
  79.         """usage: clear
  80.         
  81.         Clear the stack.
  82.         """
  83.         self.stack = []
  84.  
  85.     def do_pop(self):
  86.         """usage: pop
  87.         
  88.         Discard the top element on the stack.
  89.         """
  90.         top = self.stack[0]
  91.         self.stack = self.stack[1:]
  92.         return top
  93.  
  94.     def do_dup(self):
  95.         """usage: dup
  96.         
  97.         Duplicate the top-of-stack item.
  98.         """
  99.         if hasattr(self, 'format'):     # If it's an image, do a real copy 
  100.             dup = self.stack[0].copy()
  101.         else:
  102.              dup = self.stack[0]
  103.         self.stack = [dup] + self.stack
  104.  
  105.     def do_swap(self):
  106.         """usage: swap
  107.         
  108.         Swap the top-of-stack item with the next one down.
  109.         """
  110.         self.stack = [self.stack[1], self.stack[0]] + self.stack[2:]
  111.  
  112.     # Image module functions (callable)
  113.  
  114.     def do_new(self):
  115.         """usage: new <int:xsize> <int:ysize> <int:color>:
  116.         
  117.         Create and push a greyscale image of given size and color.
  118.         """
  119.         xsize = int(self.do_pop())
  120.         ysize = int(self.do_pop())
  121.         color = int(self.do_pop())
  122.         self.push(Image.new("L", (xsize, ysize), color))
  123.  
  124.     def do_open(self):
  125.         """usage: open <string:filename>
  126.         
  127.         Open the indicated image, read it, push the image on the stack.
  128.         """
  129.         self.push(Image.open(self.do_pop()))
  130.  
  131.     def do_blend(self):
  132.         """usage: blend <image:pic1> <image:pic2> <float:alpha>
  133.         
  134.         Replace two images and an alpha with the blended image.
  135.         """
  136.         image1 = self.do_pop()
  137.         image2 = self.do_pop()
  138.         alpha = float(self.do_pop())
  139.         self.push(Image.blend(image1, image2, alpha))
  140.  
  141.     def do_composite(self):
  142.         """usage: composite <image:pic1> <image:pic2> <image:mask>
  143.         
  144.         Replace two images and a mask with their composite.
  145.         """
  146.         image1 = self.do_pop()
  147.         image2 = self.do_pop()
  148.         mask = self.do_pop()
  149.         self.push(Image.composite(image1, image2, mask))
  150.  
  151.     def do_merge(self):
  152.         """usage: merge <string:mode> <image:pic1> [<image:pic2> [<image:pic3> [<image:pic4>]]]
  153.         
  154.         Merge top-of stack images in a way described by the mode.
  155.         """
  156.         mode = self.do_pop()
  157.         bandlist = []
  158.         for band in mode:
  159.             bandlist.append(self.do_pop())
  160.         self.push(Image.merge(mode, bandlist))
  161.  
  162.     # Image class methods
  163.  
  164.     def do_convert(self):
  165.         """usage: convert <string:mode> <image:pic1>
  166.         
  167.         Convert the top image to the given mode.
  168.         """
  169.         mode = self.do_pop()
  170.         image = self.do_pop()
  171.         self.push(image.convert(mode))
  172.  
  173.     def do_copy(self):
  174.         """usage: copy <image:pic1>
  175.         
  176.         Make and push a true copy of the top image.
  177.         """
  178.         self.dup()
  179.  
  180.     def do_crop(self):
  181.         """usage: crop <int:left> <int:upper> <int:right> <int:lower> <image:pic1>
  182.         
  183.         Crop and push a rectangular region from the current image.
  184.         """
  185.         left = int(self.do_pop())
  186.         upper = int(self.do_pop())
  187.         right = int(self.do_pop())
  188.         lower = int(self.do_pop())
  189.         image = self.do_pop()
  190.         self.push(image.crop((left, upper, right, lower)))
  191.  
  192.     def do_draft(self):
  193.         """usage: draft <string:mode> <int:xsize> <int:ysize>
  194.         
  195.         Configure the loader for a given mode and size.
  196.         """
  197.         mode = self.do_pop()
  198.         xsize = int(self.do_pop())
  199.         ysize = int(self.do_pop())
  200.         self.push(self.draft(mode, (xsize, ysize)))
  201.  
  202.     def do_filter(self):
  203.         """usage: filter <string:filtername> <image:pic1>
  204.         
  205.         Process the top image with the given filter.
  206.         """
  207.         import ImageFilter
  208.         filter = eval("ImageFilter." + string.upper(self.do_pop()))
  209.         image = self.do_pop()
  210.         self.push(image.filter(filter))
  211.  
  212.     def do_offset(self):
  213.         """usage: offset <int:xoffset> <int:yoffset> <image:pic1>
  214.         
  215.         Offset the pixels in the top image.
  216.         """
  217.         xoff = int(self.do_pop())
  218.         yoff = int(self.do_pop())
  219.         image = self.do_pop()
  220.         self.push(image.offset(xoff, yoff))
  221.  
  222.  
  223.     def do_paste(self):
  224.         """usage: paste <image:figure> <int:xoffset> <int:yoffset> <image:ground>
  225.         
  226.         Paste figure image into ground with upper left at given offsets.
  227.         """
  228.         figure = self.do_pop()
  229.         xoff = int(self.do_pop())
  230.         yoff = int(self.do_pop())
  231.         ground = self.do_pop()
  232.         if figure.mode == "RGBA":
  233.             self.push(ground.paste(figure, (xoff, yoff), figure))
  234.         else:
  235.             self.push(ground.paste(figure, (xoff, yoff)))
  236.  
  237.     def do_resize(self):
  238.         """usage: resize <int:xsize> <int:ysize> <image:pic1>
  239.         
  240.         Resize the top image.
  241.         """
  242.         ysize = int(self.do_pop())
  243.         xsize = int(self.do_pop())
  244.         image = self.do_pop()
  245.         self.push(image.resize(xsize, ysize))
  246.  
  247.     def do_rotate(self):
  248.         """usage: rotate <int:angle> <image:pic1>
  249.         
  250.         Rotate image through a given angle
  251.         """
  252.         angle = int(self.do_pop())
  253.         image = self.do_pop()
  254.         self.push(image.rotate(angle))
  255.  
  256.     def do_save(self):
  257.         """usage: save <string:filename> <image:pic1>
  258.         
  259.         Save image with default options.
  260.         """
  261.         filename = self.do_pop()
  262.         image = self.do_pop()
  263.         image.save(filename)
  264.  
  265.     def do_save2(self):
  266.         """usage: save2 <string:filename> <string:options> <image:pic1>
  267.         
  268.         Save image with specified options.
  269.         """
  270.         filename = self.do_pop()
  271.         options = self.do_pop()
  272.         image = self.do_pop()
  273.         image.save(filename, None, options)
  274.  
  275.     def do_show(self):
  276.         """usage: show <image:pic1>
  277.         
  278.         Display and pop the top image.
  279.         """
  280.         self.do_pop().show()
  281.  
  282.     def do_thumbnail(self):
  283.         """usage: thumbnail <int:xsize> <int:ysize> <image:pic1>
  284.         
  285.         Modify the top image in the stack to contain a thumbnail of itself.
  286.         """
  287.         ysize = int(self.do_pop())
  288.         xsize = int(self.do_pop())
  289.         self.top().thumbnail((xsize, ysize))
  290.  
  291.     def do_transpose(self):
  292.         """usage: transpose <string:operator> <image:pic1>
  293.         
  294.         Transpose the top image.
  295.         """
  296.         transpose = string.upper(self.do_pop())
  297.         image = self.do_pop()
  298.         self.push(image.transpose(transpose))
  299.  
  300.     # Image attributes
  301.  
  302.     def do_format(self):
  303.         """usage: format <image:pic1>
  304.         
  305.         Push the format of the top image onto the stack.
  306.         """
  307.         self.push(self.pop().format)
  308.  
  309.     def do_mode(self):
  310.         """usage: mode <image:pic1>
  311.         
  312.         Push the mode of the top image onto the stack.
  313.         """
  314.         self.push(self.pop().mode)
  315.  
  316.     def do_size(self):
  317.         """usage: size <image:pic1>
  318.         
  319.         Push the image size on the stack as (y, x).
  320.         """
  321.         size = self.pop().size
  322.         self.push(size[0])
  323.         self.push(size[1])
  324.  
  325.     # ImageChops operations
  326.  
  327.     def do_invert(self):
  328.         """usage: invert <image:pic1>
  329.         
  330.         Invert the top image.
  331.         """
  332.         import ImageChops
  333.         self.push(ImageChops.invert(self.do_pop()))
  334.  
  335.     def do_lighter(self):
  336.         """usage: lighter <image:pic1> <image:pic2>
  337.         
  338.         Pop the two top images, push an image of the lighter pixels of both.
  339.         """
  340.         import ImageChops
  341.         image1 = self.do_pop()
  342.         image2 = self.do_pop()
  343.         self.push(ImageChops.lighter(image1, image2))
  344.  
  345.     def do_darker(self):
  346.         """usage: darker <image:pic1> <image:pic2>
  347.         
  348.         Pop the two top images, push an image of the darker pixels of both.
  349.         """
  350.         import ImageChops
  351.         image1 = self.do_pop()
  352.         image2 = self.do_pop()
  353.         self.push(ImageChops.darker(image1, image2))
  354.  
  355.     def do_difference(self):
  356.         """usage: difference <image:pic1> <image:pic2>
  357.         
  358.         Pop the two top images, push the difference image
  359.         """
  360.         import ImageChops
  361.         image1 = self.do_pop()
  362.         image2 = self.do_pop()
  363.         self.push(ImageChops.difference(image1, image2))
  364.  
  365.     def do_multiply(self):
  366.         """usage: multiply <image:pic1> <image:pic2>
  367.         
  368.         Pop the two top images, push the multiplication image.
  369.         """
  370.         import ImageChops
  371.         image1 = self.do_pop()
  372.         image2 = self.do_pop()
  373.         self.push(ImageChops.multiply(image1, image2))
  374.  
  375.     def do_screen(self):
  376.         """usage: screen <image:pic1> <image:pic2>
  377.         
  378.         Pop the two top images, superimpose their inverted versions.
  379.         """
  380.         import ImageChops
  381.         image2 = self.do_pop()
  382.         image1 = self.do_pop()
  383.         self.push(ImageChops.screen(image1, image2))
  384.  
  385.     def do_add(self):
  386.         """usage: add <image:pic1> <image:pic2> <int:offset> <float:scale>
  387.         
  388.         Pop the two top images, produce the scaled sum with offset.
  389.         """
  390.         import ImageChops
  391.         image1 = self.do_pop()
  392.         image2 = self.do_pop()
  393.         scale = float(self.do_pop())
  394.         offset = int(self.do_pop())
  395.         self.push(ImageChops.add(image1, image2, scale, offset))
  396.  
  397.     def do_subtract(self):
  398.         """usage: subtract <image:pic1> <image:pic2> <int:offset> <float:scale>
  399.         
  400.         Pop the two top images, produce the scaled difference with offset.
  401.         """
  402.         import ImageChops
  403.         image1 = self.do_pop()
  404.         image2 = self.do_pop()
  405.         scale = float(self.do_pop())
  406.         offset = int(self.do_pop())
  407.         self.push(ImageChops.subtract(image1, image2, scale, offset))
  408.  
  409.     # ImageEnhance classes
  410.  
  411.     def do_color(self):
  412.         """usage: color <image:pic1>
  413.         
  414.         Enhance color in the top image.
  415.         """
  416.         import ImageEnhance
  417.         factor = float(self.do_pop())
  418.         image = self.do_pop()
  419.         enhancer = ImageEnhance.Color(image)
  420.         self.push(enhancer.enhance(factor))
  421.  
  422.     def do_contrast(self):
  423.         """usage: contrast <image:pic1>
  424.         
  425.         Enhance contrast in the top image.
  426.         """
  427.         import ImageEnhance
  428.         factor = float(self.do_pop())
  429.         image = self.do_pop()
  430.         enhancer = ImageEnhance.Color(image)
  431.         self.push(enhancer.enhance(factor))
  432.  
  433.     def do_brightness(self):
  434.         """usage: brightness <image:pic1>
  435.         
  436.         Enhance brightness in the top image.
  437.         """
  438.         import ImageEnhance
  439.         factor = float(self.do_pop())
  440.         image = self.do_pop()
  441.         enhancer = ImageEnhance.Color(image)
  442.         self.push(enhancer.enhance(factor))
  443.  
  444.     def do_sharpness(self):
  445.         """usage: sharpness <image:pic1>
  446.         
  447.         Enhance sharpness in the top image.
  448.         """
  449.         import ImageEnhance
  450.         factor = float(self.do_pop())
  451.         image = self.do_pop()
  452.         enhancer = ImageEnhance.Color(image)
  453.         self.push(enhancer.enhance(factor))
  454.  
  455.     # The interpreter loop
  456.  
  457.     def execute(self, list):
  458.         "Interpret a list of PILDriver commands."
  459.         list.reverse()
  460.         while len(list) > 0:
  461.             self.push(list[0])
  462.             list = list[1:]
  463.             if self.verbose:
  464.                 print "Stack: " + `self.stack`
  465.             top = self.top()
  466.             if type(top) != type(""):
  467.                 continue;
  468.             funcname = "do_" + top
  469.             if not hasattr(self, funcname):
  470.                 continue
  471.             else:
  472.                 self.do_pop()
  473.                 func = getattr(self, funcname)
  474.                 func()
  475.  
  476. if __name__ == '__main__': 
  477.     import sys
  478.     try:
  479.         import readline
  480.     except ImportError:
  481.         pass # not available on all platforms
  482.  
  483.     # If we see command-line arguments, interpret them as a stack state
  484.     # and execute.  Otherwise go interactive.
  485.  
  486.     driver = PILDriver()
  487.     if len(sys.argv[1:]) > 0:
  488.         driver.execute(sys.argv[1:])
  489.     else:
  490.         print "PILDriver says hello."
  491.         while 1:
  492.             try:
  493.                 line = raw_input('pildriver> ');
  494.             except EOFError:
  495.                 print "\nPILDriver says goodbye."
  496.                 break
  497.             driver.execute(string.split(line))
  498.             print driver.stack
  499.  
  500. # The following sets edit modes for GNU EMACS
  501. # Local Variables:
  502. # mode:python
  503. # End:
  504.