Advertisement
Guest User

Untitled

a guest
Jul 21st, 2015
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 38.61 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #   Copyright (C) 2012, Almar Klein, Ant1, Marius van Voorden
  3. #
  4. #   This code is subject to the (new) BSD license:
  5. #
  6. #   Redistribution and use in source and binary forms, with or without
  7. #   modification, are permitted provided that the following conditions are met:
  8. #     * Redistributions of source code must retain the above copyright
  9. #       notice, this list of conditions and the following disclaimer.
  10. #     * Redistributions in binary form must reproduce the above copyright
  11. #       notice, this list of conditions and the following disclaimer in the
  12. #       documentation and/or other materials provided with the distribution.
  13. #     * Neither the name of the <organization> nor the
  14. #       names of its contributors may be used to endorse or promote products
  15. #       derived from this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  21. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27.  
  28.  
  29. """
  30. Edited, see http://stackoverflow.com/questions/19149643/error-in-images2gif-py-with-globalpalette
  31. Also added function readGifFromPil
  32.  
  33.  
  34. """
  35.  
  36. """ Module images2gif
  37.  
  38. Provides functionality for reading and writing animated GIF images.
  39. Use writeGif to write a series of numpy arrays or PIL images as an
  40. animated GIF. Use readGif to read an animated gif as a series of numpy
  41. arrays.
  42.  
  43. Note that since July 2004, all patents on the LZW compression patent have
  44. expired. Therefore the GIF format may now be used freely.
  45.  
  46. Acknowledgements
  47. ----------------
  48.  
  49. Many thanks to Ant1 for:
  50. * noting the use of "palette=PIL.Image.ADAPTIVE", which significantly
  51.  improves the results.
  52. * the modifications to save each image with its own palette, or optionally
  53.  the global palette (if its the same).
  54.  
  55. Many thanks to Marius van Voorden for porting the NeuQuant quantization
  56. algorithm of Anthony Dekker to Python (See the NeuQuant class for its
  57. license).
  58.  
  59. Many thanks to Alex Robinson for implementing the concept of subrectangles,
  60. which (depening on image content) can give a very significant reduction in
  61. file size.
  62.  
  63. This code is based on gifmaker (in the scripts folder of the source
  64. distribution of PIL)
  65.  
  66.  
  67. Usefull links
  68. -------------
  69.  * http://tronche.com/computer-graphics/gif/
  70.  * http://en.wikipedia.org/wiki/Graphics_Interchange_Format
  71.  * http://www.w3.org/Graphics/GIF/spec-gif89a.txt
  72.  
  73. """
  74. # todo: This module should be part of imageio (or at least based on)
  75.  
  76. import os, time
  77.  
  78. try:
  79.     import PIL
  80.     from PIL import Image
  81.     from PIL.GifImagePlugin import getheader, getdata
  82. except ImportError:
  83.     PIL = None
  84.  
  85. try:
  86.     import numpy as np
  87. except ImportError:
  88.     np = None
  89.  
  90. def get_cKDTree():
  91.     try:
  92.         from scipy.spatial import cKDTree
  93.     except ImportError:
  94.         cKDTree = None
  95.     return cKDTree
  96.  
  97.  
  98. # getheader gives a 87a header and a color palette (two elements in a list).
  99. # getdata()[0] gives the Image Descriptor up to (including) "LZW min code size".
  100. # getdatas()[1:] is the image data itself in chuncks of 256 bytes (well
  101. # technically the first byte says how many bytes follow, after which that
  102. # amount (max 255) follows).
  103.  
  104. def checkImages(images):
  105.     """ checkImages(images)
  106.    Check numpy images and correct intensity range etc.
  107.    The same for all movie formats.
  108.    """
  109.     # Init results
  110.     images2 = []
  111.  
  112.     for im in images:
  113.         if PIL and isinstance(im, PIL.Image.Image):
  114.             # We assume PIL images are allright
  115.             images2.append(im)
  116.  
  117.         elif np and isinstance(im, np.ndarray):
  118.             # Check and convert dtype
  119.             if im.dtype == np.uint8:
  120.                 images2.append(im) # Ok
  121.             elif im.dtype in [np.float32, np.float64]:
  122.                 im = im.copy()
  123.                 im[im<0] = 0
  124.                 im[im>1] = 1
  125.                 im *= 255
  126.                 images2.append( im.astype(np.uint8) )
  127.             else:
  128.                 im = im.astype(np.uint8)
  129.                 images2.append(im)
  130.             # Check size
  131.             if im.ndim == 2:
  132.                 pass # ok
  133.             elif im.ndim == 3:
  134.                 if im.shape[2] not in [3,4]:
  135.                     raise ValueError('This array can not represent an image.')
  136.             else:
  137.                 raise ValueError('This array can not represent an image.')
  138.         else:
  139.             raise ValueError('Invalid image type: ' + str(type(im)))
  140.  
  141.     # Done
  142.     return images2
  143.  
  144.  
  145. def intToBin(i):
  146.     """ Integer to two bytes """
  147.     # devide in two parts (bytes)
  148.     i1 = i % 256
  149.     i2 = int( i/256)
  150.     # make string (little endian)
  151.     return chr(i1) + chr(i2)
  152.  
  153.  
  154. class GifWriter:
  155.     """ GifWriter()
  156.  
  157.    Class that contains methods for helping write the animated GIF file.
  158.  
  159.    """
  160.  
  161.     def getheaderAnim(self, im):
  162.         """ getheaderAnim(im)
  163.  
  164.        Get animation header. To replace PILs getheader()[0]
  165.  
  166.        """
  167.         bb = "GIF89a"
  168.         bb += intToBin(im.size[0])
  169.         bb += intToBin(im.size[1])
  170.         bb += "\x87\x00\x00"
  171.         return bb
  172.  
  173.  
  174.     def getImageDescriptor(self, im, xy=None):
  175.         """ getImageDescriptor(im, xy=None)
  176.  
  177.        Used for the local color table properties per image.
  178.        Otherwise global color table applies to all frames irrespective of
  179.        whether additional colors comes in play that require a redefined
  180.        palette. Still a maximum of 256 color per frame, obviously.
  181.  
  182.        Written by Ant1 on 2010-08-22
  183.        Modified by Alex Robinson in Janurari 2011 to implement subrectangles.
  184.  
  185.        """
  186.  
  187.         # Defaule use full image and place at upper left
  188.         if xy is None:
  189.             xy  = (0,0)
  190.  
  191.         # Image separator,
  192.         bb = '\x2C'
  193.  
  194.         # Image position and size
  195.         bb += intToBin( xy[0] ) # Left position
  196.         bb += intToBin( xy[1] ) # Top position
  197.         bb += intToBin( im.size[0] ) # image width
  198.         bb += intToBin( im.size[1] ) # image height
  199.  
  200.         # packed field: local color table flag1, interlace0, sorted table0,
  201.         # reserved00, lct size111=7=2^(7+1)=256.
  202.         bb += '\x87'
  203.  
  204.         # LZW minimum size code now comes later, begining of [image data] blocks
  205.         return bb
  206.  
  207.  
  208.     def getAppExt(self, loops=float('inf')):
  209.         """ getAppExt(loops=float('inf'))
  210.  
  211.        Application extention. This part specifies the amount of loops.
  212.        If loops is 0 or inf, it goes on infinitely.
  213.  
  214.        """
  215.  
  216.         if loops==0 or loops==float('inf'):
  217.             loops = 2**16-1
  218.             #bb = "" # application extension should not be used
  219.                     # (the extension interprets zero loops
  220.                     # to mean an infinite number of loops)
  221.                     # Mmm, does not seem to work
  222.         if True:
  223.             bb = "\x21\xFF\x0B"  # application extension
  224.             bb += "NETSCAPE2.0"
  225.             bb += "\x03\x01"
  226.             bb += intToBin(loops)
  227.             bb += '\x00'  # end
  228.         return bb
  229.  
  230.  
  231.     def getGraphicsControlExt(self, duration=0.1, dispose=2,transparent_flag=0,transparency_index=0):
  232.         """ getGraphicsControlExt(duration=0.1, dispose=2)
  233.  
  234.        Graphics Control Extension. A sort of header at the start of
  235.        each image. Specifies duration and transparancy.
  236.  
  237.        Dispose
  238.        -------
  239.          * 0 - No disposal specified.
  240.          * 1 - Do not dispose. The graphic is to be left in place.
  241.           * 2 - Restore to background color. The area used by the graphic
  242.            must be restored to the background color.
  243.           * 3 - Restore to previous. The decoder is required to restore the
  244.            area overwritten by the graphic with what was there prior to
  245.            rendering the graphic.
  246.          * 4-7 -To be defined.
  247.  
  248.        """
  249.  
  250.         bb = '\x21\xF9\x04'
  251.         bb += chr(((dispose & 3) << 2)|(transparent_flag & 1))  # low bit 1 == transparency,
  252.         # 2nd bit 1 == user input , next 3 bits, the low two of which are used,
  253.         # are dispose.
  254.         bb += intToBin( int(duration*100) ) # in 100th of seconds
  255.         bb += chr(transparency_index)  # transparency index
  256.         bb += '\x00'  # end
  257.         return bb
  258.  
  259.  
  260.     def handleSubRectangles(self, images, subRectangles):
  261.         """ handleSubRectangles(images)
  262.  
  263.        Handle the sub-rectangle stuff. If the rectangles are given by the
  264.        user, the values are checked. Otherwise the subrectangles are
  265.        calculated automatically.
  266.  
  267.        """
  268.         image_info = [im.info for im in images ]
  269.         if isinstance(subRectangles, (tuple,list)):
  270.             # xy given directly
  271.  
  272.             # Check xy
  273.             xy = subRectangles
  274.             if xy is None:
  275.                 xy = (0,0)
  276.             if hasattr(xy, '__len__'):
  277.                 if len(xy) == len(images):
  278.                     xy = [xxyy for xxyy in xy]
  279.                 else:
  280.                     raise ValueError("len(xy) doesn't match amount of images.")
  281.             else:
  282.                 xy = [xy for im in images]
  283.             xy[0] = (0,0)
  284.  
  285.         else:
  286.             # Calculate xy using some basic image processing
  287.  
  288.             # Check Numpy
  289.             if np is None:
  290.                 raise RuntimeError("Need Numpy to use auto-subRectangles.")
  291.  
  292.             # First make numpy arrays if required
  293.             for i in range(len(images)):
  294.                 im = images[i]
  295.                 if isinstance(im, Image.Image):
  296.                     tmp = im.convert() # Make without palette
  297.                     a = np.asarray(tmp)
  298.                     if len(a.shape)==0:
  299.                         raise MemoryError("Too little memory to convert PIL image to array")
  300.                     images[i] = a
  301.  
  302.             # Determine the sub rectangles
  303.             images, xy = self.getSubRectangles(images)
  304.  
  305.         # Done
  306.         return images, xy, image_info
  307.  
  308.  
  309.     def getSubRectangles(self, ims):
  310.         """ getSubRectangles(ims)
  311.  
  312.        Calculate the minimal rectangles that need updating each frame.
  313.        Returns a two-element tuple containing the cropped images and a
  314.        list of x-y positions.
  315.  
  316.        Calculating the subrectangles takes extra time, obviously. However,
  317.        if the image sizes were reduced, the actual writing of the GIF
  318.        goes faster. In some cases applying this method produces a GIF faster.
  319.  
  320.        """
  321.  
  322.         # Check image count
  323.         if len(ims) < 2:
  324.             return ims, [(0,0) for i in ims]
  325.  
  326.         # We need numpy
  327.         if np is None:
  328.             raise RuntimeError("Need Numpy to calculate sub-rectangles. ")
  329.  
  330.         # Prepare
  331.         ims2 = [ims[0]]
  332.         xy = [(0,0)]
  333.         t0 = time.time()
  334.  
  335.         # Iterate over images
  336.         prev = ims[0]
  337.         for im in ims[1:]:
  338.  
  339.             # Get difference, sum over colors
  340.             diff = np.abs(im-prev)
  341.             if diff.ndim==3:
  342.                 diff = diff.sum(2)
  343.             # Get begin and end for both dimensions
  344.             X = np.argwhere(diff.sum(0))
  345.             Y = np.argwhere(diff.sum(1))
  346.             # Get rect coordinates
  347.             if X.size and Y.size:
  348.                 x0, x1 = X[0], X[-1]+1
  349.                 y0, y1 = Y[0], Y[-1]+1
  350.             else: # No change ... make it minimal
  351.                 x0, x1 = 0, 2
  352.                 y0, y1 = 0, 2
  353.  
  354.             # Cut out and store
  355.             im2 = im[y0:y1,x0:x1]
  356.             prev = im
  357.             ims2.append(im2)
  358.             xy.append((x0,y0))
  359.  
  360.         # Done
  361.         #print('%1.2f seconds to determine subrectangles of  %i images' %
  362.         #    (time.time()-t0, len(ims2)) )
  363.         return ims2, xy
  364.  
  365.  
  366.     def convertImagesToPIL(self, images, dither, nq=0,images_info=None):
  367.         """ convertImagesToPIL(images, nq=0)
  368.  
  369.        Convert images to Paletted PIL images, which can then be
  370.        written to a single animaged GIF.
  371.  
  372.        """
  373.  
  374.         # Convert to PIL images
  375.         images2 = []
  376.         for im in images:
  377.             if isinstance(im, Image.Image):
  378.                 images2.append(im)
  379.             elif np and isinstance(im, np.ndarray):
  380.                 if im.ndim==3 and im.shape[2]==3:
  381.                     im = Image.fromarray(im,'RGB')
  382.                 elif im.ndim==3 and im.shape[2]==4:
  383.                     # im = Image.fromarray(im[:,:,:3],'RGB')
  384.                     self.transparency = True
  385.                     im = Image.fromarray(im[:,:,:4],'RGBA')
  386.                 elif im.ndim==2:
  387.                     im = Image.fromarray(im,'L')
  388.                 images2.append(im)
  389.  
  390.         # Convert to paletted PIL images
  391.         images, images2 = images2, []
  392.         if nq >= 1:
  393.             # NeuQuant algorithm
  394.             for im in images:
  395.                 im = im.convert("RGBA") # NQ assumes RGBA
  396.                 nqInstance = NeuQuant(im, int(nq)) # Learn colors from image
  397.                 if dither:
  398.                     im = im.convert("RGB").quantize(palette=nqInstance.paletteImage(),colors=255)
  399.                 else:
  400.                     im = nqInstance.quantize(im,colors=255)  # Use to quantize the image itself
  401.  
  402.                 self.transparency = True # since NQ assumes transparency
  403.                 if self.transparency:
  404.                     alpha = im.split()[3]
  405.                     mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
  406.                     im.paste(255,mask=mask)
  407.                 images2.append(im)
  408.         else:
  409.             # Adaptive PIL algorithm
  410.             AD = Image.ADAPTIVE
  411.             # for index,im in enumerate(images):
  412.             for i in range(len(images)):
  413.                 im = images[i].convert('RGB').convert('P', palette=AD, dither=dither,colors=255)
  414.                 if self.transparency:
  415.                     alpha = images[i].split()[3]
  416.                     mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
  417.                     im.paste(255,mask=mask)
  418.                 images2.append(im)
  419.  
  420.         # Done
  421.         return images2
  422.  
  423.  
  424.     def writeGifToFile(self, fp, images, durations, loops, xys, disposes):
  425.         """ writeGifToFile(fp, images, durations, loops, xys, disposes)
  426.  
  427.        Given a set of images writes the bytes to the specified stream.
  428.  
  429.        """
  430.  
  431.         # Obtain palette for all images and count each occurance
  432.         palettes, occur = [], []
  433.         for im in images:
  434.             # palettes.append( getheader(im)[1] )
  435.             palettes.append(im.palette.getdata()[1])
  436.         for palette in palettes:
  437.             occur.append( palettes.count( palette ) )
  438.  
  439.         # Select most-used palette as the global one (or first in case no max)
  440.         globalPalette = palettes[ occur.index(max(occur)) ]
  441.  
  442.         # Init
  443.         frames = 0
  444.         firstFrame = True
  445.  
  446.  
  447.         for im, palette in zip(images, palettes):
  448.  
  449.             if firstFrame:
  450.                 # Write header
  451.  
  452.                 # Gather info
  453.                 header = self.getheaderAnim(im)
  454.                 appext = self.getAppExt(loops)
  455.  
  456.                 # Write
  457.                 fp.write(header)
  458.                 fp.write(globalPalette)
  459.                 fp.write(appext)
  460.  
  461.                 # Next frame is not the first
  462.                 firstFrame = False
  463.  
  464.             if True:
  465.                 # Write palette and image data
  466.  
  467.                 # Gather info
  468.                 data = getdata(im)
  469.                 imdes, data = data[0], data[1:]
  470.  
  471.                 transparent_flag = 0
  472.                 if self.transparency: transparent_flag = 1
  473.  
  474.                 graphext = self.getGraphicsControlExt(durations[frames],
  475.                                                         disposes[frames],transparent_flag=transparent_flag,transparency_index=255)
  476.  
  477.                 # Make image descriptor suitable for using 256 local color palette
  478.                 lid = self.getImageDescriptor(im, xys[frames])
  479.  
  480.                 # Write local header
  481.                 if (palette != globalPalette) or (disposes[frames] != 2):
  482.                     # Use local color palette
  483.                     fp.write(graphext)
  484.                     fp.write(lid) # write suitable image descriptor
  485.                     fp.write(palette) # write local color table
  486.                     fp.write('\x08') # LZW minimum size code
  487.                 else:
  488.                     # Use global color palette
  489.                     fp.write(graphext)
  490.                     fp.write(imdes) # write suitable image descriptor
  491.  
  492.                 # Write image data
  493.                 for d in data:
  494.                     fp.write(d)
  495.  
  496.             # Prepare for next round
  497.             frames = frames + 1
  498.  
  499.         fp.write(";")  # end gif
  500.         return frames
  501.  
  502.  
  503.  
  504.  
  505. ## Exposed functions
  506.  
  507. def writeGif(filename, images, duration=0.1, repeat=True, dither=False,
  508.                 nq=0, subRectangles=True, dispose=None):
  509.     """ writeGif(filename, images, duration=0.1, repeat=True, dither=False,
  510.                    nq=0, subRectangles=True, dispose=None)
  511.  
  512.    Write an animated gif from the specified images.
  513.  
  514.    Parameters
  515.    ----------
  516.    filename : string
  517.        The name of the file to write the image to.
  518.    images : list
  519.        Should be a list consisting of PIL images or numpy arrays.
  520.        The latter should be between 0 and 255 for integer types, and
  521.        between 0 and 1 for float types.
  522.    duration : scalar or list of scalars
  523.        The duration for all frames, or (if a list) for each frame.
  524.    repeat : bool or integer
  525.        The amount of loops. If True, loops infinitetely.
  526.    dither : bool
  527.        Whether to apply dithering
  528.    nq : integer
  529.        If nonzero, applies the NeuQuant quantization algorithm to create
  530.        the color palette. This algorithm is superior, but slower than
  531.        the standard PIL algorithm. The value of nq is the quality
  532.        parameter. 1 represents the best quality. 10 is in general a
  533.        good tradeoff between quality and speed. When using this option,
  534.        better results are usually obtained when subRectangles is False.
  535.    subRectangles : False, True, or a list of 2-element tuples
  536.        Whether to use sub-rectangles. If True, the minimal rectangle that
  537.        is required to update each frame is automatically detected. This
  538.        can give significant reductions in file size, particularly if only
  539.        a part of the image changes. One can also give a list of x-y
  540.        coordinates if you want to do the cropping yourself. The default
  541.        is True.
  542.    dispose : int
  543.        How to dispose each frame. 1 means that each frame is to be left
  544.        in place. 2 means the background color should be restored after
  545.        each frame. 3 means the decoder should restore the previous frame.
  546.        If subRectangles==False, the default is 2, otherwise it is 1.
  547.  
  548.    """
  549.  
  550.     # Check PIL
  551.     if PIL is None:
  552.         raise RuntimeError("Need PIL to write animated gif files.")
  553.  
  554.     # Check images
  555.     images = checkImages(images)
  556.  
  557.     # Instantiate writer object
  558.     gifWriter = GifWriter()
  559.     gifWriter.transparency = False # init transparency flag used in GifWriter functions
  560.  
  561.     # Check loops
  562.     if repeat is False:
  563.         loops = 1
  564.     elif repeat is True:
  565.         loops = 0 # zero means infinite
  566.     else:
  567.         loops = int(repeat)
  568.  
  569.     # Check duration
  570.     if hasattr(duration, '__len__'):
  571.         if len(duration) == len(images):
  572.             duration = [d for d in duration]
  573.         else:
  574.             raise ValueError("len(duration) doesn't match amount of images.")
  575.     else:
  576.         duration = [duration for im in images]
  577.  
  578.     # Check subrectangles
  579.     if subRectangles:
  580.         images, xy, images_info = gifWriter.handleSubRectangles(images, subRectangles)
  581.         defaultDispose = 1 # Leave image in place
  582.     else:
  583.         # Normal mode
  584.         xy = [(0,0) for im in images]
  585.         defaultDispose = 2 # Restore to background color.
  586.  
  587.     # Check dispose
  588.     if dispose is None:
  589.         dispose = defaultDispose
  590.     if hasattr(dispose, '__len__'):
  591.         if len(dispose) != len(images):
  592.             raise ValueError("len(xy) doesn't match amount of images.")
  593.     else:
  594.         dispose = [dispose for im in images]
  595.  
  596.     # Make images in a format that we can write easy
  597.     images = gifWriter.convertImagesToPIL(images, dither, nq)
  598.  
  599.     # Write
  600.     fp = open(filename, 'wb')
  601.     try:
  602.         gifWriter.writeGifToFile(fp, images, duration, loops, xy, dispose)
  603.     finally:
  604.         fp.close()
  605.  
  606.  
  607. def readGifFromPIL(pilIm, asNumpy=True):
  608.     """ readGif(filename, asNumpy=True)
  609.  
  610.    Read images from an animated GIF file.  Returns a list of numpy
  611.    arrays, or, if asNumpy is false, a list if PIL images.
  612.  
  613.    """
  614.  
  615.  
  616.  
  617.     # Check Numpy
  618.     if np is None:
  619.         raise RuntimeError("Need Numpy to read animated gif files.")
  620.  
  621.     # # Check whether it exists
  622.     # if not os.path.isfile(filename):
  623.     #     raise IOError('File not found: '+str(filename))
  624.  
  625.     # Load file using PIL
  626.     # pilIm = PIL.Image.open(filename)
  627.     pilIm.seek(0)
  628.  
  629.     # Read all images inside
  630.     images = []
  631.     try:
  632.         while True:
  633.             # Get image as numpy array
  634.             tmp = pilIm.convert() # Make without palette
  635.             a = np.asarray(tmp)
  636.             if len(a.shape)==0:
  637.                 raise MemoryError("Too little memory to convert PIL image to array")
  638.             # Store, and next
  639.             images.append(a)
  640.             pilIm.seek(pilIm.tell()+1)
  641.     except EOFError:
  642.         pass
  643.  
  644.     # Convert to normal PIL images if needed
  645.     if not asNumpy:
  646.         images2 = images
  647.         images = []
  648.         for index,im in enumerate(images2):
  649.             tmp = Image.fromarray(im)
  650.             images.append(tmp)
  651.  
  652.     # Done
  653.     return images
  654.  
  655.  
  656.  
  657. def readGif(filename, asNumpy=True):
  658.     """ readGif(filename, asNumpy=True)
  659.  
  660.    Read images from an animated GIF file.  Returns a list of numpy
  661.    arrays, or, if asNumpy is false, a list if PIL images.
  662.  
  663.    """
  664.  
  665.     # Check PIL
  666.     if PIL is None:
  667.         raise RuntimeError("Need PIL to read animated gif files.")
  668.  
  669.     # Check Numpy
  670.     if np is None:
  671.         raise RuntimeError("Need Numpy to read animated gif files.")
  672.  
  673.     # Check whether it exists
  674.     if not os.path.isfile(filename):
  675.         raise IOError('File not found: '+str(filename))
  676.  
  677.     # Load file using PIL
  678.     pilIm = PIL.Image.open(filename)
  679.     pilIm.seek(0)
  680.  
  681.     # Read all images inside
  682.     images = []
  683.     try:
  684.         while True:
  685.             # Get image as numpy array
  686.             tmp = pilIm.convert() # Make without palette
  687.             a = np.asarray(tmp)
  688.             if len(a.shape)==0:
  689.                 raise MemoryError("Too little memory to convert PIL image to array")
  690.             # Store, and next
  691.             images.append(a)
  692.             pilIm.seek(pilIm.tell()+1)
  693.     except EOFError:
  694.         pass
  695.  
  696.     # Convert to normal PIL images if needed
  697.     if not asNumpy:
  698.         images2 = images
  699.         images = []
  700.         for index,im in enumerate(images2):
  701.             tmp = PIL.Image.fromarray(im)
  702.             images.append(tmp)
  703.  
  704.     # Done
  705.     return images
  706.  
  707.  
  708. class NeuQuant:
  709.     """ NeuQuant(image, samplefac=10, colors=256)
  710.  
  711.    samplefac should be an integer number of 1 or higher, 1
  712.    being the highest quality, but the slowest performance.
  713.    With avalue of 10, one tenth of all pixels are used during
  714.    training. This value seems a nice tradeof between speed
  715.    and quality.
  716.  
  717.    colors is the amount of colors to reduce the image to. This
  718.    should best be a power of two.
  719.  
  720.    See also:
  721.    http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
  722.  
  723.    License of the NeuQuant Neural-Net Quantization Algorithm
  724.    ---------------------------------------------------------
  725.  
  726.    Copyright (c) 1994 Anthony Dekker
  727.    Ported to python by Marius van Voorden in 2010
  728.  
  729.    NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
  730.    See "Kohonen neural networks for optimal colour quantization"
  731.    in "network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
  732.    for a discussion of the algorithm.
  733.    See also  http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
  734.  
  735.    Any party obtaining a copy of these files from the author, directly or
  736.    indirectly, is granted, free of charge, a full and unrestricted irrevocable,
  737.    world-wide, paid up, royalty-free, nonexclusive right and license to deal
  738.    in this software and documentation files (the "Software"), including without
  739.    limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  740.    and/or sell copies of the Software, and to permit persons who receive
  741.    copies from any such party to do so, with the only requirement being
  742.    that this copyright notice remain intact.
  743.  
  744.    """
  745.  
  746.     NCYCLES = None # Number of learning cycles
  747.     NETSIZE = None # Number of colours used
  748.     SPECIALS = None # Number of reserved colours used
  749.     BGCOLOR = None # Reserved background colour
  750.     CUTNETSIZE = None
  751.     MAXNETPOS = None
  752.  
  753.     INITRAD = None # For 256 colours, radius starts at 32
  754.     RADIUSBIASSHIFT = None
  755.     RADIUSBIAS = None
  756.     INITBIASRADIUS = None
  757.     RADIUSDEC = None # Factor of 1/30 each cycle
  758.  
  759.     ALPHABIASSHIFT = None
  760.     INITALPHA = None # biased by 10 bits
  761.  
  762.     GAMMA = None
  763.     BETA = None
  764.     BETAGAMMA = None
  765.  
  766.     network = None # The network itself
  767.     colormap = None # The network itself
  768.  
  769.     netindex = None # For network lookup - really 256
  770.  
  771.     bias = None # Bias and freq arrays for learning
  772.     freq = None
  773.  
  774.     pimage = None
  775.  
  776.     # Four primes near 500 - assume no image has a length so large
  777.     # that it is divisible by all four primes
  778.     PRIME1 = 499
  779.     PRIME2 = 491
  780.     PRIME3 = 487
  781.     PRIME4 = 503
  782.     MAXPRIME = PRIME4
  783.  
  784.     pixels = None
  785.     samplefac = None
  786.  
  787.     a_s = None
  788.  
  789.  
  790.     def setconstants(self, samplefac, colors):
  791.         self.NCYCLES = 100 # Number of learning cycles
  792.         self.NETSIZE = colors # Number of colours used
  793.         self.SPECIALS = 3 # Number of reserved colours used
  794.         self.BGCOLOR = self.SPECIALS-1 # Reserved background colour
  795.         self.CUTNETSIZE = self.NETSIZE - self.SPECIALS
  796.         self.MAXNETPOS = self.NETSIZE - 1
  797.  
  798.         self.INITRAD = self.NETSIZE/8 # For 256 colours, radius starts at 32
  799.         self.RADIUSBIASSHIFT = 6
  800.         self.RADIUSBIAS = 1 << self.RADIUSBIASSHIFT
  801.         self.INITBIASRADIUS = self.INITRAD * self.RADIUSBIAS
  802.         self.RADIUSDEC = 30 # Factor of 1/30 each cycle
  803.  
  804.         self.ALPHABIASSHIFT = 10 # Alpha starts at 1
  805.         self.INITALPHA = 1 << self.ALPHABIASSHIFT # biased by 10 bits
  806.  
  807.         self.GAMMA = 1024.0
  808.         self.BETA = 1.0/1024.0
  809.         self.BETAGAMMA = self.BETA * self.GAMMA
  810.  
  811.         self.network = np.empty((self.NETSIZE, 3), dtype='float64') # The network itself
  812.         self.colormap = np.empty((self.NETSIZE, 4), dtype='int32') # The network itself
  813.  
  814.         self.netindex = np.empty(256, dtype='int32') # For network lookup - really 256
  815.  
  816.         self.bias = np.empty(self.NETSIZE, dtype='float64') # Bias and freq arrays for learning
  817.         self.freq = np.empty(self.NETSIZE, dtype='float64')
  818.  
  819.         self.pixels = None
  820.         self.samplefac = samplefac
  821.  
  822.         self.a_s = {}
  823.  
  824.     def __init__(self, image, samplefac=10, colors=256):
  825.  
  826.         # Check Numpy
  827.         if np is None:
  828.             raise RuntimeError("Need Numpy for the NeuQuant algorithm.")
  829.  
  830.         # Check image
  831.         if image.size[0] * image.size[1] < NeuQuant.MAXPRIME:
  832.             raise IOError("Image is too small")
  833.         if image.mode != "RGBA":
  834.             raise IOError("Image mode should be RGBA.")
  835.  
  836.         # Initialize
  837.         self.setconstants(samplefac, colors)
  838.         self.pixels = np.fromstring(image.tostring(), np.uint32)
  839.         self.setUpArrays()
  840.  
  841.         self.learn()
  842.         self.fix()
  843.         self.inxbuild()
  844.  
  845.     def writeColourMap(self, rgb, outstream):
  846.         for i in range(self.NETSIZE):
  847.             bb = self.colormap[i,0];
  848.             gg = self.colormap[i,1];
  849.             rr = self.colormap[i,2];
  850.             outstream.write(rr if rgb else bb)
  851.             outstream.write(gg)
  852.             outstream.write(bb if rgb else rr)
  853.         return self.NETSIZE
  854.  
  855.     def setUpArrays(self):
  856.         self.network[0,0] = 0.0    # Black
  857.         self.network[0,1] = 0.0
  858.         self.network[0,2] = 0.0
  859.  
  860.         self.network[1,0] = 255.0    # White
  861.         self.network[1,1] = 255.0
  862.         self.network[1,2] = 255.0
  863.  
  864.         # RESERVED self.BGCOLOR # Background
  865.  
  866.         for i in range(self.SPECIALS):
  867.             self.freq[i] = 1.0 / self.NETSIZE
  868.             self.bias[i] = 0.0
  869.  
  870.         for i in range(self.SPECIALS, self.NETSIZE):
  871.             p = self.network[i]
  872.             p[:] = (255.0 * (i-self.SPECIALS)) / self.CUTNETSIZE
  873.  
  874.             self.freq[i] = 1.0 / self.NETSIZE
  875.             self.bias[i] = 0.0
  876.  
  877.     # Omitted: setPixels
  878.  
  879.     def altersingle(self, alpha, i, b, g, r):
  880.         """Move neuron i towards biased (b,g,r) by factor alpha"""
  881.         n = self.network[i] # Alter hit neuron
  882.         n[0] -= (alpha*(n[0] - b))
  883.         n[1] -= (alpha*(n[1] - g))
  884.         n[2] -= (alpha*(n[2] - r))
  885.  
  886.     def geta(self, alpha, rad):
  887.         try:
  888.             return self.a_s[(alpha, rad)]
  889.         except KeyError:
  890.             length = rad*2-1
  891.             mid = length/2
  892.             q = np.array(list(range(mid-1,-1,-1))+list(range(-1,mid)))
  893.             a = alpha*(rad*rad - q*q)/(rad*rad)
  894.             a[mid] = 0
  895.             self.a_s[(alpha, rad)] = a
  896.             return a
  897.  
  898.     def alterneigh(self, alpha, rad, i, b, g, r):
  899.         if i-rad >= self.SPECIALS-1:
  900.             lo = i-rad
  901.             start = 0
  902.         else:
  903.             lo = self.SPECIALS-1
  904.             start = (self.SPECIALS-1 - (i-rad))
  905.  
  906.         if i+rad <= self.NETSIZE:
  907.             hi = i+rad
  908.             end = rad*2-1
  909.         else:
  910.             hi = self.NETSIZE
  911.             end = (self.NETSIZE - (i+rad))
  912.  
  913.         a = self.geta(alpha, rad)[start:end]
  914.  
  915.         p = self.network[lo+1:hi]
  916.         p -= np.transpose(np.transpose(p - np.array([b, g, r])) * a)
  917.  
  918.     #def contest(self, b, g, r):
  919.     #    """ Search for biased BGR values
  920.     #            Finds closest neuron (min dist) and updates self.freq
  921.     #            finds best neuron (min dist-self.bias) and returns position
  922.     #            for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
  923.     #            self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
  924.     #
  925.     #    i, j = self.SPECIALS, self.NETSIZE
  926.     #    dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
  927.     #    bestpos = i + np.argmin(dists)
  928.     #    biasdists = dists - self.bias[i:j]
  929.     #    bestbiaspos = i + np.argmin(biasdists)
  930.     #    self.freq[i:j] -= self.BETA * self.freq[i:j]
  931.     #    self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
  932.     #    self.freq[bestpos] += self.BETA
  933.     #    self.bias[bestpos] -= self.BETAGAMMA
  934.     #    return bestbiaspos
  935.     def contest(self, b, g, r):
  936.         """ Search for biased BGR values
  937.                Finds closest neuron (min dist) and updates self.freq
  938.                finds best neuron (min dist-self.bias) and returns position
  939.                for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
  940.                self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
  941.         i, j = self.SPECIALS, self.NETSIZE
  942.         dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
  943.         bestpos = i + np.argmin(dists)
  944.         biasdists = dists - self.bias[i:j]
  945.         bestbiaspos = i + np.argmin(biasdists)
  946.         self.freq[i:j] *= (1-self.BETA)
  947.         self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
  948.         self.freq[bestpos] += self.BETA
  949.         self.bias[bestpos] -= self.BETAGAMMA
  950.         return bestbiaspos
  951.  
  952.  
  953.  
  954.  
  955.     def specialFind(self, b, g, r):
  956.         for i in range(self.SPECIALS):
  957.             n = self.network[i]
  958.             if n[0] == b and n[1] == g and n[2] == r:
  959.                 return i
  960.         return -1
  961.  
  962.     def learn(self):
  963.         biasRadius = self.INITBIASRADIUS
  964.         alphadec = 30 + ((self.samplefac-1)/3)
  965.         lengthcount = self.pixels.size
  966.         samplepixels = lengthcount / self.samplefac
  967.         delta = samplepixels / self.NCYCLES
  968.         alpha = self.INITALPHA
  969.  
  970.         i = 0;
  971.         rad = biasRadius >> self.RADIUSBIASSHIFT
  972.         if rad <= 1:
  973.             rad = 0
  974.  
  975.         print("Beginning 1D learning: samplepixels = %1.2f  rad = %i" %
  976.                                                     (samplepixels, rad) )
  977.         step = 0
  978.         pos = 0
  979.         if lengthcount%NeuQuant.PRIME1 != 0:
  980.             step = NeuQuant.PRIME1
  981.         elif lengthcount%NeuQuant.PRIME2 != 0:
  982.             step = NeuQuant.PRIME2
  983.         elif lengthcount%NeuQuant.PRIME3 != 0:
  984.             step = NeuQuant.PRIME3
  985.         else:
  986.             step = NeuQuant.PRIME4
  987.  
  988.         i = 0
  989.         printed_string = ''
  990.         while i < samplepixels:
  991.             if i%100 == 99:
  992.                 tmp = '\b'*len(printed_string)
  993.                 printed_string = str((i+1)*100/samplepixels)+"%\n"
  994.                 print(tmp + printed_string)
  995.             p = self.pixels[pos]
  996.             r = (p >> 16) & 0xff
  997.             g = (p >>  8) & 0xff
  998.             b = (p      ) & 0xff
  999.  
  1000.             if i == 0: # Remember background colour
  1001.                 self.network[self.BGCOLOR] = [b, g, r]
  1002.  
  1003.             j = self.specialFind(b, g, r)
  1004.             if j < 0:
  1005.                 j = self.contest(b, g, r)
  1006.  
  1007.             if j >= self.SPECIALS: # Don't learn for specials
  1008.                 a = (1.0 * alpha) / self.INITALPHA
  1009.                 self.altersingle(a, j, b, g, r)
  1010.                 if rad > 0:
  1011.                     self.alterneigh(a, rad, j, b, g, r)
  1012.  
  1013.             pos = (pos+step)%lengthcount
  1014.  
  1015.             i += 1
  1016.             if i%delta == 0:
  1017.                 alpha -= alpha / alphadec
  1018.                 biasRadius -= biasRadius / self.RADIUSDEC
  1019.                 rad = biasRadius >> self.RADIUSBIASSHIFT
  1020.                 if rad <= 1:
  1021.                     rad = 0
  1022.  
  1023.         finalAlpha = (1.0*alpha)/self.INITALPHA
  1024.         print("Finished 1D learning: final alpha = %1.2f!" % finalAlpha)
  1025.  
  1026.     def fix(self):
  1027.         for i in range(self.NETSIZE):
  1028.             for j in range(3):
  1029.                 x = int(0.5 + self.network[i,j])
  1030.                 x = max(0, x)
  1031.                 x = min(255, x)
  1032.                 self.colormap[i,j] = x
  1033.             self.colormap[i,3] = i
  1034.  
  1035.     def inxbuild(self):
  1036.         previouscol = 0
  1037.         startpos = 0
  1038.         for i in range(self.NETSIZE):
  1039.             p = self.colormap[i]
  1040.             q = None
  1041.             smallpos = i
  1042.             smallval = p[1] # Index on g
  1043.             # Find smallest in i..self.NETSIZE-1
  1044.             for j in range(i+1, self.NETSIZE):
  1045.                 q = self.colormap[j]
  1046.                 if q[1] < smallval: # Index on g
  1047.                     smallpos = j
  1048.                     smallval = q[1] # Index on g
  1049.  
  1050.             q = self.colormap[smallpos]
  1051.             # Swap p (i) and q (smallpos) entries
  1052.             if i != smallpos:
  1053.                 p[:],q[:] = q, p.copy()
  1054.  
  1055.             # smallval entry is now in position i
  1056.             if smallval != previouscol:
  1057.                 self.netindex[previouscol] = (startpos+i) >> 1
  1058.                 for j in range(previouscol+1, smallval):
  1059.                     self.netindex[j] = i
  1060.                 previouscol = smallval
  1061.                 startpos = i
  1062.         self.netindex[previouscol] = (startpos+self.MAXNETPOS) >> 1
  1063.         for j in range(previouscol+1, 256): # Really 256
  1064.             self.netindex[j] = self.MAXNETPOS
  1065.  
  1066.  
  1067.     def paletteImage(self):
  1068.         """ PIL weird interface for making a paletted image: create an image which
  1069.            already has the palette, and use that in Image.quantize. This function
  1070.            returns this palette image. """
  1071.         if self.pimage is None:
  1072.             palette = []
  1073.             for i in range(self.NETSIZE):
  1074.                 palette.extend(self.colormap[i][:3])
  1075.  
  1076.             palette.extend([0]*(256-self.NETSIZE)*3)
  1077.  
  1078.             # a palette image to use for quant
  1079.             self.pimage = Image.new("P", (1, 1), 0)
  1080.             self.pimage.putpalette(palette)
  1081.         return self.pimage
  1082.  
  1083.  
  1084.     def quantize(self, image):
  1085.         """ Use a kdtree to quickly find the closest palette colors for the pixels """
  1086.         if get_cKDTree():
  1087.             return self.quantize_with_scipy(image)
  1088.         else:
  1089.             print('Scipy not available, falling back to slower version.')
  1090.             return self.quantize_without_scipy(image)
  1091.  
  1092.  
  1093.     def quantize_with_scipy(self, image):
  1094.         w,h = image.size
  1095.         px = np.asarray(image).copy()
  1096.         px2 = px[:,:,:3].reshape((w*h,3))
  1097.  
  1098.         cKDTree = get_cKDTree()
  1099.         kdtree = cKDTree(self.colormap[:,:3],leafsize=10)
  1100.         result = kdtree.query(px2)
  1101.         colorindex = result[1]
  1102.         print("Distance: %1.2f" % (result[0].sum()/(w*h)) )
  1103.         px2[:] = self.colormap[colorindex,:3]
  1104.  
  1105.         return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
  1106.  
  1107.  
  1108.     def quantize_without_scipy(self, image):
  1109.         """" This function can be used if no scipy is availabe.
  1110.        It's 7 times slower though.
  1111.        """
  1112.         w,h = image.size
  1113.         px = np.asarray(image).copy()
  1114.         memo = {}
  1115.         for j in range(w):
  1116.             for i in range(h):
  1117.                 key = (px[i,j,0],px[i,j,1],px[i,j,2])
  1118.                 try:
  1119.                     val = memo[key]
  1120.                 except KeyError:
  1121.                     val = self.convert(*key)
  1122.                     memo[key] = val
  1123.                 px[i,j,0],px[i,j,1],px[i,j,2] = val
  1124.         return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
  1125.  
  1126.     def convert(self, *color):
  1127.         i = self.inxsearch(*color)
  1128.         return self.colormap[i,:3]
  1129.  
  1130.     def inxsearch(self, r, g, b):
  1131.         """Search for BGR values 0..255 and return colour index"""
  1132.         dists = (self.colormap[:,:3] - np.array([r,g,b]))
  1133.         a= np.argmin((dists*dists).sum(1))
  1134.         return a
  1135.  
  1136.  
  1137.  
  1138. if __name__ == '__main__':
  1139.     im = np.zeros((200,200), dtype=np.uint8)
  1140.     im[10:30,:] = 100
  1141.     im[:,80:120] = 255
  1142.     im[-50:-40,:] = 50
  1143.  
  1144.     images = [im*1.0, im*0.8, im*0.6, im*0.4, im*0]
  1145.     writeGif('lala3.gif',images, duration=0.5, dither=0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement