Ë
    ÿ[;jA@  ã                   ó¦   — d Z ddlZddlmZ ddlZddlmZ ddlmZ ddlZddl	m
Z
 ddlmZ g d¢Zd	„ Zd
„ Zd„ Z G d„ d«      Zd„ Z G d„ de«      Zy)zEData structures to hold collections of images, with optional caching.é    N)Úglob)ÚSequence)Úcopy)ÚImage)ÚTiffFile)Ú
MultiImageÚImageCollectionÚconcatenate_imagesÚimread_collection_wrapperc                 ó°   — | D �cg c]  }|t         j                  df   ‘Œ }}	 t        j                  |«      }|S c c}w # t        $ r t        d«      ‚w xY w)ax  Concatenate all images in the image collection into an array.

    Parameters
    ----------
    ic : an iterable of images
        The images to be concatenated.

    Returns
    -------
    array_cat : 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.

    Notes
    -----
    ``concatenate_images`` receives any iterable object containing images,
    including ImageCollection and MultiImage, and returns a NumPy array.
    .zImage dimensions must agree.)ÚnpÚnewaxisÚconcatenateÚ
ValueError)ÚicÚimageÚ
all_imagesÚ	array_cats       ú^G:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\skimage/io/collection.pyr
   r
      sb   € ñ8 79Ó9±b¨U�%œŸ
™
 C˜Ó(°b€JÐ9ð9Ü—N‘N :Ó.ˆ	ð Ðùò :øô ò 9ÜÐ7Ó8Ð8ð9ús   …;¤A  Á Ac                 óŒ   — t        j                  d| «      D �cg c]  }|j                  «       rt        |«      n|‘Œ! }}|S c c}w )aA  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']
    z([0-9]+))ÚreÚsplitÚisdigitÚint)ÚsÚcÚks      r   Úalphanumeric_keyr   ;   sA   € ô, 02¯x©x¸
ÀAÔ/FÓGÑ/F¨!�1—9‘9”;ŒˆQŒ AÑ	%Ð/F€AÐGØ€Hùò 	Hs   ™$Ac                 óÐ   — t        | t        «      xr t        j                  | v }t        | t        «       }t        | t        «      }t        d„ | D «       «      }|xs
 |xr |xr |}|S )zlHelping function. Returns True if pattern contains a tuple, list, or a
    string separated with os.pathsep.c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w©N)Ú
isinstanceÚstr)Ú.0Úpats     r   Ú	<genexpr>z#_is_multipattern.<locals>.<genexpr>\   s   è ø€ ÐD±m¨s”j ¤c×*±mùs   ‚)r"   r#   ÚosÚpathsepr   Úall)Úinput_patternÚhas_str_ospathsepÚnot_a_stringÚhas_iterableÚhas_stringsÚis_multipatterns         r   Ú_is_multipatternr0   U   sl   € ô # =´#Ó6ÒV¼2¿:¹:ÈÐ;VÐÜ! -´Ó5Ð5€LÜ˜m¬XÓ6€LÜÑD±mÓDÓD€Kà'ò ØÒ5˜Ò5¨+ð ð Ðó    c                   ól   — e Zd ZdZ	 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y)r	   aH  Load and manage a collection of image files.

    Parameters
    ----------
    load_pattern : str or list of str
        Pattern string or list of strings to load. The filename path can be
        absolute or relative.
    conserve_memory : bool, optional
        If True, :class:`skimage.io.ImageCollection` does not 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.
    **load_func_kwargs : dict
        Any other keyword arguments are passed to `load_func`.

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

    Notes
    -----
    Note that files are always returned in alphanumerical order. Also note that slicing
    returns a new :class:`skimage.io.ImageCollection`, *not* a view into the data.

    ImageCollection image loading can be customized through
    `load_func`. For an ImageCollection ``ic``, ``ic[5]`` calls
    ``load_func(load_pattern[5])`` to load that image.

    For example, here is an ImageCollection that, for each video provided,
    loads every second frame::

      import imageio.v3 as iio3
      import itertools

      def vidread_step(f, step):
          vid = iio3.imiter(f)
          return list(itertools.islice(vid, None, None, step)

      video_file = 'no_time_for_that_tiny.gif'
      ic = ImageCollection(video_file, load_func=vidread_step, step=2)

      ic  # is an ImageCollection object of length 1 because 1 video is provided

      x = ic[0]
      x[5]  # the 10th frame of the first video

    Alternatively, if `load_func` is provided and `load_pattern` is a
    sequence, an :class:`skimage.io.ImageCollection` of corresponding length will
    be created, and the individual images will be loaded by calling `load_func` with the
    matching element of the `load_pattern` as its first argument. In this
    case, the elements of the sequence do not need to be names of existing
    files (or strings at all). For example, to create an :class:`skimage.io.ImageCollection`
    containing 500 images from a video::

      class FrameReader:
          def __init__ (self, f):
              self.f = f
          def __call__ (self, index):
              return iio3.imread(self.f, index=index)

      ic = ImageCollection(range(500), load_func=FrameReader('movie.mp4'))

      ic  # is an ImageCollection object of length 500

    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)

    Examples
    --------
    >>> import imageio.v3 as iio3
    >>> import skimage.io as io

    # Where your images are located
    >>> data_dir = os.path.join(os.path.dirname(__file__), '../data')

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

    >>> image_col = io.ImageCollection([f'{data_dir}/*.png', '{data_dir}/*.jpg'])

    >>> class MultiReader:
    ...     def __init__ (self, f):
    ...         self.f = f
    ...     def __call__ (self, index):
    ...         return iio3.imread(self.f, index=index)
    ...
    >>> filename = data_dir + '/no_time_for_that_tiny.gif'
    >>> ic = io.ImageCollection(range(24), load_func=MultiReader(filename))
    >>> len(image_col)
    23
    >>> isinstance(ic[0], np.ndarray)
    True
    Nc                 óJ  — g | _         t        |«      r{t        |t        «      r|j	                  t
        j                  «      }|D ]&  }| j                   j                  t        |«      «       Œ( t        | j                   t        ¬«      | _         nƒt        |t        «      rE| j                   j                  t        |«      «       t        | j                   t        ¬«      | _         n.t        |t        «      r|�t        |«      | _         nt        d«      ‚|€#ddlm} || _        | j#                  «       | _        n(|| _        t'        | j                   «      | _        d| _        |rd}n| j$                  }|| _        d| _        || _        t1        j2                  |t4        ¬«      | _        y)z'Load and manage a collection of images.)ÚkeyNzInvalid pattern as input.é   ©Úimread©Údtype)Ú_filesr0   r"   r#   r   r'   r(   Úextendr   Úsortedr   r   ÚlistÚ	TypeErrorÚ_ior7   Ú	load_funcÚ_find_imagesÚ
_numframesÚlenÚ_frame_indexÚ_conserve_memoryÚ_cachedÚload_func_kwargsr   ÚemptyÚobjectÚdata)ÚselfÚload_patternÚconserve_memoryr@   rG   Úpatternr7   Úmemory_slotss           r   Ú__init__zImageCollection.__init__Ð   s8  € ð ˆŒÜ˜LÔ)Ü˜,¬Ô,Ø+×1Ñ1´"·*±*Ó=�Û'�Ø—‘×"Ñ"¤4¨£=Õ1ð (ä  §¡Ô2BÔCˆD�KÜ˜¤cÔ*Ø�K‰K×Ñœt LÓ1Ô2Ü  §¡Ô2BÔCˆD�KÜ˜¤hÔ/°IÐ4IÜ˜|Ó,ˆD�KäÐ7Ó8Ð8àÐÝ#à#ˆDŒNØ"×/Ñ/Ó1ˆD�Oà&ˆDŒNÜ! $§+¡+Ó.ˆDŒOØ $ˆDÔáØ‰LàŸ?™?ˆLà /ˆÔØˆŒà 0ˆÔÜ—H‘H˜\´Ô8ˆ�	r1   c                 ó   — | j                   S r!   )r:   ©rK   s    r   ÚfileszImageCollection.filesø   s   € à�{‰{Ðr1   c                 ó   — | j                   S r!   )rE   rR   s    r   rM   zImageCollection.conserve_memoryü   s   € à×$Ñ$Ð$r1   c                 ó¤  — g }| j                   D ]Ç  }|j                  «       j                  d«      rRt        |d«      5 }t	        |«      }|t        t        |j                  «      «      D �cg c]  }||f‘Œ c}z  }d d d «       Œt	 t        j                  |«      }|j                  d«       d}	 	 |j                  |«       |j                  ||f«       |dz  }Œ+ || _        t        |«      S c c}w # 1 sw Y   ŒêxY w# t        $ r Y Œøw xY w# t        $ r Y nw xY wt        |d«      s�Œ|j                  s�Œ'|j                  j                  «        �ŒC)N)z.tiffz.tifÚrbr   r5   Úfp)r:   ÚlowerÚendswithÚopenr   ÚrangerC   Úpagesr   ÚseekÚOSErrorÚEOFErrorÚappendÚhasattrrW   ÚcloserD   )rK   ÚindexÚfnameÚfÚimgÚiÚims          r   rA   zImageCollection._find_images   s3  € ØˆØ—[”[ˆEØ�{‰{‹}×%Ñ%Ð&7Ô8Ü˜% Ô&¨!Ü" 1›+�CØ´%¼¸C¿I¹I»Ô2GÓHÑ2G¨Q˜u ašjÐ2GÑHÑH�E÷ 'Ð&ðÜŸ™ EÓ*�BØ—G‘G˜A”Jð �ØðØŸ™ œ
ð —L‘L %¨ Ô,Ø˜‘F�Að ð !ð* "ˆÔÜ�5‹zÐùò% I÷ 'Ð&ûô ò Ùðûô $ò Ùðúô ˜2˜tÖ$¨¯¬Ø—E‘E—K‘K–MsA   ½-C0Á*C+
Á5C0Â&C<Â.DÃ+C0Ã0C9	Ã<	DÄDÄ	DÄDc                 ó   — t        |d«      r|j                  «       }t        |t        t        f«      st        d«      ‚t        |t        «      ré| j                  |«      }|t        | j                  «      z  }| j                  r|| j                  k7  s| j                  |   €‡| j                  }| j                  r;| j                  |   \  }}|�||d<   	  | j                  |fi |¤Ž| j                  |<   n- | j                  | j                  |   fi |¤Ž| j                  |<   || _
        | j                  |   S t!        | j"                  «      |   }t%        | «      }| j                  rH|D �	cg c]  }	| j                  |	   d   ‘Œ c}	|_        |D �	cg c]  }	| j                  |	   ‘Œ c}	|_        n"|D �	cg c]  }	| j&                  |	   ‘Œ c}	|_        t        |«      |_        | j                  rv| j                  |v rF|j)                  | j                  «      |_
        t+        j$                  | j                  «      |_        |S t+        j,                  dt.        ¬«      |_        |S | j                  |   |_        |S # t
        $ r=}dt        |«      v r$|d=  | j                  |fi |¤Ž| j                  |<   n‚ Y d}~�Œ˜d}~ww xY wc c}	w c c}	w c c}	w )	aô  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 :class:`skimage.io.ImageCollection`
            The `n`-th image in the collection, or a new ImageCollection with
            the selected images.
        Ú	__index__z+slicing must be with an int or slice objectNÚimg_numz%unexpected keyword argument 'img_num'r   r5   r8   )ra   rj   r"   r   Úslicer>   Ú_check_imgnumrC   rJ   rM   rF   rG   rD   r@   r#   rS   r[   rB   r   r:   rc   r   rH   rI   )
rK   ÚnÚidxÚkwargsrd   rk   ÚeÚfidxÚnew_icrg   s
             r   Ú__getitem__zImageCollection.__getitem__  s{  € ô" �1�kÔ"Ø—‘“ˆAä˜!œc¤5˜\Ô*ÜÐIÓJÐJä�aœÔØ×"Ñ" 1Ó%ˆAØ”c˜$Ÿ)™)“nÑ$ˆCà×$Ò$¨¨d¯l©lÒ):ÀÇ	Á	È#ÁÐ@VØ×.Ñ.�Ø×$Ò$Ø%)×%6Ñ%6°qÑ%9‘N�E˜7ØÐ*Ø,3˜˜yÑ)ð"Ø)7¨¯©¸Ñ)HÀÑ)H˜Ÿ	™	 #šð &4 T§^¡^°D·J±J¸q±MÑ%LÀVÑ%L�D—I‘I˜c‘NØ �”à—9‘9˜S‘>Ð!ô ˜Ÿ™Ó)¨!Ñ,ˆDÜ˜$“ZˆFà× Ò ÙBFÓ GÁ$¸Q ×!2Ñ!2°1Ñ!5°aÓ!8À$Ñ G�”ÙEIÓ&JÁTÀ t×'8Ñ'8¸Ó';ÀTÑ&J�Õ#á9=Ó >¹°A §¡¨Q£¸Ñ >�”ä # D£	ˆFÔà×#Ò#Ø—<‘< 4Ñ'Ø%)§Z¡Z°·±Ó%=�F”NÜ"$§'¡'¨$¯)©)Ó"4�F”Kð
 ˆMô #%§(¡(¨1´FÔ";�F”Kð ˆMð #Ÿi™i¨™o�”ØˆMøôG %ò "ØBÄcÈ!ÃfÑLØ & yÐ 1Ø-;¨T¯^©^¸EÑ-LÀVÑ-L˜DŸI™I cšNà!õ +ûð"üò( !HùÚ&Jùâ >s*   Ã I8 Å*KÆKÆ2KÉ8	J>Ê2J9Ê9J>c                 ód   — | j                   }| |cxk  r|k  r
n n||z  }|S t        d|› d�«      ‚)z+Check that the given image number is valid.zThere are only z images in the collection)rB   Ú
IndexError)rK   rn   Únums      r   rm   zImageCollection._check_imgnumc  s?   € à�o‰oˆØˆ4�1Œ?�s�?Ø�C‘ˆAð ˆô ˜¨s¨eÐ3LÐMÓNÐNr1   c              #   óL   K  — t        t        | «      «      D ]	  }| |   –— Œ y­w)zIterate over the images.N)r[   rC   )rK   rg   s     r   Ú__iter__zImageCollection.__iter__l  s"   è ø€ ä”s˜4“yÖ!ˆAØ�q‘'‹Mñ "ùs   ‚"$c                 ó   — | j                   S )zNumber of images in collection.)rB   rR   s    r   Ú__len__zImageCollection.__len__q  s   € à�‰Ðr1   c                 ó,   — t        | j                  «      S r!   )r#   rS   rR   s    r   Ú__str__zImageCollection.__str__u  s   € Ü�4—:‘:‹Ðr1   c                 óL   — t        j                  | j                  «      | _        y)zÄ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   Ú
empty_likerJ   )rK   rn   s     r   ÚreloadzImageCollection.reloadx  s   € ô —M‘M $§)¡)Ó,ˆ�	r1   c                 ó   — t        | «      S )a©  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
        --------
        skimage.io.concatenate_images

        Raises
        ------
        ValueError
            If images in the :class:`skimage.io.ImageCollection` do not have identical
            shapes.
        )r
   rR   s    r   r   zImageCollection.concatenate„  s   € ô$ " $Ó'Ð'r1   ©TNr!   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rP   ÚpropertyrS   rM   rA   rt   rm   ry   r{   r}   r€   r   © r1   r   r	   r	   d   sg   „ ñiðX =Aó&9ðP ñó ðð ñ%ó ð%òò4GòRòò
òó
-ó(r1   r	   c                 ó   ‡ — dˆ fd„	}|S )Nc                 ó    •— t        | |‰¬«      S )a  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.

        )rM   r@   )r	   )rL   rM   r7   s     €r   Úimread_collectionz4imread_collection_wrapper.<locals>.imread_collectionš  s   ø€ ô( Ø¨/ÀVô
ð 	
r1   )Trˆ   )r7   r‹   s   ` r   r   r   ™  s   ø€ õ
ð0 Ðr1   c                   ó4   ‡ — e Zd ZdZdˆ fd„	Zed„ «       Zˆ xZS )r   a   A class containing all frames from multi-frame TIFF images.

    Parameters
    ----------
    load_pattern : str or list of str
        Pattern glob or filenames to load. The path can be absolute or
        relative.
    conserve_memory : bool, optional
        Whether to conserve memory by only caching the frames of a single
        image. Default is True.

    Notes
    -----
    `MultiImage` returns a list of image-data arrays. In this
    regard, it is very similar to `ImageCollection`, but the two differ in
    their treatment of multi-frame images.

    For a TIFF image containing N frames of size WxH, `MultiImage` stores
    all frames of that image as a single element of shape `(N, W, H)` in the
    list. `ImageCollection` instead creates N elements of shape `(W, H)`.

    For an animated GIF image, `MultiImage` reads only the first frame, while
    `ImageCollection` reads all frames by default.

    Examples
    --------
    # Where your images are located
    >>> data_dir = os.path.join(os.path.dirname(__file__), '../data')

    >>> multipage_tiff = data_dir + '/multipage.tif'
    >>> multi_img = MultiImage(multipage_tiff)
    >>> len(multi_img)  # multi_img contains one element
    1
    >>> multi_img[0].shape  # this element is a two-frame image of shape:
    (2, 15, 10)

    >>> image_col = ImageCollection(multipage_tiff)
    >>> len(image_col)  # image_col contains two elements
    2
    >>> for frame in image_col:
    ...     print(frame.shape)  # each element is a frame of shape (15, 10)
    ...
    (15, 10)
    (15, 10)
    c                 óF   •— ddl m} || _        t        ‰| �  ||fd|i|¤Ž y)zLoad a multi-img.r5   r6   r@   N)r?   r7   Ú	_filenameÚsuperrP   )rK   ÚfilenamerM   r9   Úimread_kwargsr7   Ú	__class__s         €r   rP   zMultiImage.__init__ä  s&   ø€ åà!ˆŒÜ‰Ñ˜ ?ÑV¸fÐVÈÓVr1   c                 ó   — | j                   S r!   )rŽ   rR   s    r   r�   zMultiImage.filenameë  s   € à�~‰~Ðr1   r‚   )rƒ   r„   r…   r†   rP   r‡   r�   Ú__classcell__)r’   s   @r   r   r   µ  s#   ø„ ñ,õ\Wð ñó ôr1   r   )r†   r'   r   r   Úcollections.abcr   r   Únumpyr   ÚPILr   Útifffiler   Ú__all__r
   r   r0   r	   r   r   rˆ   r1   r   Ú<module>rš      sU   ðÙ Kã 	Ý Û 	Ý $Ý ã Ý å ò€ò!òHò4÷r(ñ r(òj	ô88�õ 8r1   