ó
 ‰\c           @€  sã   d  Z  d d l m Z d d l Z d d l m Z d d l Z d d l m Z d d l Z d d l	 Z	 d d l
 m Z d d l m Z d	 d
 d d g Z d „  Z d „  Z d
 e f d „  ƒ  YZ d „  Z d	 e f d „  ƒ  YZ d S(   sE   Data structures to hold collections of images, with optional caching.iÿÿÿÿ(   t   with_statementN(   t   glob(   t   copy(   t   Imagei   (   t   TiffFilet
   MultiImaget   ImageCollectiont   concatenate_imagest   imread_collection_wrapperc         C€  s]   g  |  D] } | t  j d f ^ q } y t  j | ƒ } Wn t k
 rX t d ƒ ‚ n X| S(   sò  Concatenate all images in the image collection into an array.

    Parameters
    ----------
    ic: an iterable of images (including ImageCollection and MultiImage)
        The images to be concatenated.

    Returns
    -------
    ar : np.ndarray
        An array having one more dimension than the images in `ic`.

    See Also
    --------
    ImageCollection.concatenate, MultiImage.concatenate

    Raises
    ------
    ValueError
        If images in `ic` don't have identical shapes.
    .s   Image dimensions must agree.(   t   npt   newaxist   concatenatet
   ValueError(   t   ict   imgt
   all_imagest   ar(    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR      s    &c         C€  sA   g  t  j d |  ƒ D]$ } | j ƒ  r1 t | ƒ n | ^ q } | S(   s?  Convert string to list of strings and ints that gives intuitive sorting.

    Parameters
    ----------
    s: string

    Returns
    -------
    k: a list of strings and ints

    Examples
    --------
    >>> alphanumeric_key('z23a')
    ['z', 23, 'a']
    >>> filenames = ['f9.10.png', 'e10.png', 'f9.9.png', 'f10.10.png',
    ...              'f10.9.png']
    >>> sorted(filenames)
    ['e10.png', 'f10.10.png', 'f10.9.png', 'f9.10.png', 'f9.9.png']
    >>> sorted(filenames, key=alphanumeric_key)
    ['e10.png', 'f9.9.png', 'f9.10.png', 'f10.9.png', 'f10.10.png']
    s   ([0-9]+)(   t   ret   splitt   isdigitt   int(   t   st   ct   k(    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   alphanumeric_key3   s    =c           B€  s†   e  Z d  Z e d d „ Z e d „  ƒ Z e d „  ƒ Z d „  Z	 d „  Z
 d „  Z d „  Z d „  Z d	 „  Z d d
 „ Z d „  Z RS(   sœ	  Load and manage a collection of image files.

    Note that files are always stored in alphabetical order. Also note that
    slicing returns a new ImageCollection, *not* a view into the data.

    Parameters
    ----------
    load_pattern : str or list
        Pattern glob or filenames to load. The path can be absolute or
        relative.  Multiple patterns should be separated by os.pathsep,
        e.g. '/tmp/work/*.png:/tmp/other/*.jpg'.  Also see
        implementation notes below.
    conserve_memory : bool, optional
        If True, never keep more than one in memory at a specific
        time.  Otherwise, images will be cached once they are loaded.

    Other parameters
    ----------------
    load_func : callable
        ``imread`` by default.  See notes below.

    Attributes
    ----------
    files : list of str
        If a glob string is given for `load_pattern`, this attribute
        stores the expanded file list.  Otherwise, this is simply
        equal to `load_pattern`.

    Notes
    -----
    ImageCollection can be modified to load images from an arbitrary
    source by specifying a combination of `load_pattern` and
    `load_func`.  For an ImageCollection ``ic``, ``ic[5]`` uses
    ``load_func(file_pattern[5])`` to load the image.

    Imagine, for example, an ImageCollection that loads every tenth
    frame from a video file::

      class AVILoader:
          video_file = 'myvideo.avi'

          def __call__(self, frame):
              return video_read(self.video_file, frame)

      avi_load = AVILoader()

      frames = range(0, 1000, 10) # 0, 10, 20, ...
      ic = ImageCollection(frames, load_func=avi_load)

      x = ic[5] # calls avi_load(frames[5]) or equivalently avi_load(50)

    Another use of ``load_func`` would be to convert all images to ``uint8``::

      def imread_convert(f):
          return imread(f).astype(np.uint8)

      ic = ImageCollection('/tmp/*.png', load_func=imread_convert)

    For files with multiple images, the images will be flattened into a list
    and added to the list of available images.  In this case, ``load_func``
    should accept the keyword argument ``img_num``.

    Examples
    --------
    >>> import skimage.io as io
    >>> from skimage import data_dir

    >>> coll = io.ImageCollection(data_dir + '/chess*.png')
    >>> len(coll)
    2
    >>> coll[0].shape
    (200, 200)

    >>> ic = io.ImageCollection('/tmp/work/*.png:/tmp/other/*.jpg')

    c         K€  s"  t  | t j ƒ r~ | j t j ƒ } g  |  _ x$ | D] } |  j j t | ƒ ƒ q4 Wt	 |  j d t
 ƒ|  _ |  j ƒ  |  _ n$ | |  _ t |  j ƒ |  _ d |  _ | r± d } n	 |  j } | |  _ d |  _ | d k rô d d l m } | |  _ n	 | |  _ | |  _ t j | d t ƒ|  _ d S(   s'   Load and manage a collection of images.t   keyi   (   t   imreadt   dtypeN(   t
   isinstancet   sixt   string_typesR   t   ost   pathsept   _filest   extendR   t   sortedR   t   _find_imagest
   _numframest   lent   Nonet   _frame_indext   _conserve_memoryt   _cachedt   _ioR   t	   load_funct   load_func_kwargsR	   t   emptyt   objectt   data(   t   selft   load_patternt   conserve_memoryR,   R-   t   patternt   memory_slotsR   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   __init__œ   s*    									c         C€  s   |  j  S(   N(   R!   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   files½   s    c         C€  s   |  j  S(   N(   R)   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR3   Á   s    c      
   C€  sV  g  } x:|  j  D]/} | j ƒ  j d ƒ r„ t | d ƒ E } t | ƒ } | g  t t | j ƒ ƒ D] } | | f ^ qb 7} Wd  QXq y  t j | ƒ } | j	 d ƒ Wn t
 t f k
 rÀ q n Xd } xM t ry | j	 | ƒ Wn t k
 rõ Pn X| j | | f ƒ | d 7} qÊ Wt | d ƒ r | j r | j j ƒ  q q W| |  _ t | ƒ S(   Ns   .tiffs   .tift   rbi    i   t   fp(   s   .tiffs   .tif(   R!   t   lowert   endswitht   openR   t   rangeR&   t   pagesR   t   seekt   IOErrort   OSErrort   Truet   EOFErrort   appendt   hasattrR9   t   closeR(   (   R1   t   indext   fnamet   fR   t   it   im(    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR$   Å   s.    ;		c   
      C€  s¦  t  | d ƒ r | j ƒ  } n  t | ƒ t t g k rE t d ƒ ‚ n  t | ƒ t k r‡|  j | ƒ } | t |  j ƒ } |  j	 r‘ | |  j
 k s¤ |  j | d k r||  j } |  j rP|  j | \ } } | d k	 râ | | d <n  y |  j | |  |  j | <Wqpt k
 rL} d t | ƒ k rF| d =|  j | |  |  j | <qM‚  qpXn  |  j |  j | |  |  j | <| |  _
 n  |  j | St |  j ƒ | } t |  ƒ } |  j rüg  | D] }	 |  j |	 d ^ q¶| _ g  | D] }	 |  j |	 ^ qÝ| _ n# g  | D] }	 |  j |	 ^ q| _ t | ƒ | _ |  j	 rŽ|  j
 | k rs| j |  j
 ƒ | _
 t j |  j ƒ | _ qžt j d d t ƒ| _ n |  j | | _ | Sd S(	   sâ  Return selected image(s) in the collection.

        Loading is done on demand.

        Parameters
        ----------
        n : int or slice
            The image number to be returned, or a slice selecting the images
            and ordering to be returned in a new ImageCollection.

        Returns
        -------
        img : ndarray or ImageCollection.
            The `n`-th image in the collection, or a new ImageCollection with
            the selected images.

        t	   __index__s+   slicing must be with an int or slice objectt   img_nums%   unexpected keyword argument 'img_num'i    i   R   N(   RE   RL   t   typeR   t   slicet	   TypeErrort   _check_imgnumR&   R0   R3   R*   R'   R-   R(   R,   t   strR7   R=   R%   R   R!   RG   R	   R.   R/   (
   R1   t   nt   idxt   kwargsRH   RM   t   et   fidxt   new_icRJ   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   __getitem__ß   sL    		
 	'&#	c         C€  sG   |  j  } | | k o! | k  n r3 | | } n t d | ƒ ‚ | S(   s+   Check that the given image number is valid.s*   There are only %s images in the collection(   R%   t
   IndexError(   R1   RS   t   num(    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyRQ   *  s    	
c         c€  s*   x# t  t |  ƒ ƒ D] } |  | Vq Wd S(   s   Iterate over the images.N(   R=   R&   (   R1   RJ   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   __iter__4  s    c         C€  s   |  j  S(   s   Number of images in collection.(   R%   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   __len__9  s    c         C€  s   t  |  j ƒ S(   N(   RR   R7   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   __str__=  s    c         C€  s   t  j |  j ƒ |  _ d S(   sÄ   Clear the image cache.

        Parameters
        ----------
        n : None or int
            Clear the cache for this image only. By default, the
            entire cache is erased.

        N(   R	   t
   empty_likeR0   (   R1   RS   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   reload@  s    
c         C€  s
   t  |  ƒ S(   s  Concatenate all images in the collection into an array.

        Returns
        -------
        ar : np.ndarray
            An array having one more dimension than the images in `self`.

        See Also
        --------
        concatenate_images

        Raises
        ------
        ValueError
            If images in the `ImageCollection` don't have identical shapes.
        (   R   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR   L  s    N(   t   __name__t
   __module__t   __doc__RB   R'   R6   t   propertyR7   R3   R$   RY   RQ   R\   R]   R^   R`   R   (    (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR   M   s   M!		K	
			c         €  s   t  ‡  f d † } | S(   Nc         €  s   t  |  d | d ˆ  ƒS(   s  Return an `ImageCollection` from files matching the given pattern.

        Note that files are always stored in alphabetical order. Also note that
        slicing returns a new ImageCollection, *not* a view into the data.

        See `skimage.io.ImageCollection` for details.

        Parameters
        ----------
        load_pattern : str or list
            Pattern glob or filenames to load. The path can be absolute or
            relative.  Multiple patterns should be separated by a colon,
            e.g. '/tmp/work/*.png:/tmp/other/*.jpg'.  Also see
            implementation notes below.
        conserve_memory : bool, optional
            If True, never keep more than one in memory at a specific
            time.  Otherwise, images will be cached once they are loaded.

        R3   R,   (   R   (   R2   R3   (   R   (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   imread_collectiona  s    (   RB   (   R   Re   (    (   R   s4   lib/python2.7/site-packages/skimage/io/collection.pyR   `  s    c           B€  s,   e  Z d  Z e d d „ Z e d „  ƒ Z RS(   sµ  A class containing a single multi-frame image.

    Parameters
    ----------
    filename : str
        The complete path to the image file.
    conserve_memory : bool, optional
        Whether to conserve memory by only caching a single frame. Default is
        True.

    Notes
    -----
    If ``conserve_memory=True`` the memory footprint can be reduced, however
    the performance can be affected because frames have to be read from file
    more often.

    The last accessed frame is cached, all other frames will have to be read
    from file.

    The current implementation makes use of ``tifffile`` for Tiff files and
    PIL otherwise.

    Examples
    --------
    >>> from skimage import data_dir

    >>> img = MultiImage(data_dir + '/multipage.tif') # doctest: +SKIP
    >>> len(img) # doctest: +SKIP
    2
    >>> for frame in img: # doctest: +SKIP
    ...     print(frame.shape) # doctest: +SKIP
    (15, 10)
    (15, 10)

    c         €  sQ   d d l  m ‰ ‡  ‡ f d †  } | |  _ t t |  ƒ j | | d | | d S(   s   Load a multi-img.i   (   R   c         €  s   | j  d ˆ  ƒ ˆ |  |  S(   NR   (   t
   setdefault(   RH   RU   (   R   R   (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR,   ¥  s    R,   N(   R+   R   t	   _filenamet   superR   R6   (   R1   t   filenameR3   R   t   imread_kwargsR,   (    (   R   R   s4   lib/python2.7/site-packages/skimage/io/collection.pyR6      s
    	c         C€  s   |  j  S(   N(   Rg   (   R1   (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyRi   ­  s    N(   Ra   Rb   Rc   RB   R'   R6   Rd   Ri   (    (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyR   z  s   $(   Rc   t
   __future__R    R   R   R   R   t   numpyR	   R   t   PILR   t   external.tifffileR   t   __all__R   R   R/   R   R   R   (    (    (    s4   lib/python2.7/site-packages/skimage/io/collection.pyt   <module>   s"   				ÿ 	