o
    &j@                    @   s  d Z ddlmZmZmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddlZzddlmZ W n ey?   ddlmZ Y nw ddlZddlZddlZddlZddlmZ ddlZddlZdZejejeZ ej!e dZ"ej!e dZ#ej!e dZ$ej!ejejed	Z%e&ej'd
 Z(e&ej'd Z)e&ej'd Z*dZ+ddddej,ej-ej.ej/gZ0G dd de1Z2e3dfddZ4dddZ5G dd de6Z7dd Z8dd Z9dd  Z:d!d" Z;d#d$ Z<d%d& Z=d'd( Z>d)d* Z?d+d, Z@d-d. ZAd/d0 ZBd1d2 ZCd3d4 ZDd5d6 ZEdd7d8ZFe7d9d:d; ZGe7d<d=d> ZHe7d?ddAdBZIe7d?dCdD ZJe7dEddFdGZKe7dHdIdJ ZLe7dKddMdNZMe7dOdPdQ ZNdRdS ZOdTdU ZPddVdWZQddXdYZRddZd[ZSdd\d]ZTdd^d_ZUdd`daZVddbdcZWddde ZXdfdg ZYddjdkZZddldmZ[dndo Z\ddpdqZ]		ddtduZ^	w	ddxdyZ_		dd{d|Z`	}	sdd~dZa	w	sdddZbdddZcdddZde+fddZedddZfdd Zgdd Zhdd ZiG dd de6ZjG dd dejZkG dd dejZldd Zmg dZnenD ]\ZoZpZqemeoepeqer eo< qdS )z5Collection of basic functions used throughout imgaug.    )print_functiondivisionabsolute_importN)IterableALLz
quokka.jpgzquokka_annotations.jsonzquokka_depth_map_halfres.pngzDejaVuSans.ttffloatintZuint
matplotlibnearestlinearareacubicc                   @      e Zd ZdZdS )DeprecationWarningzWarning for deprecated calls.

    Since python 2.7 DeprecatedWarning is silent by default. So we define
    our own DeprecatedWarning here so that it is not silent by default.

    N__name__
__module____qualname____doc__ r   r   N/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/imgaug/imgaug.pyr   <       r      c                 C   s   ddl }|j| ||d dS )a  Generate a a warning with stacktrace.

    Parameters
    ----------
    msg : str
        The message of the warning.

    category : class
        The class of the warning to produce.

    stacklevel : int, optional
        How many steps above this function to "jump" in the stacktrace when
        displaying file and line number of the error message.
        Usually ``2``.

    r   Ncategory
stacklevel)warningswarn)msgr   r   r   r   r   r   r   E   s   r   c                 C   s   t | t|d dS )a  Generate a non-silent deprecation warning with stacktrace.

    The used warning is ``imgaug.imgaug.DeprecationWarning``.

    Parameters
    ----------
    msg : str
        The message of the warning.

    stacklevel : int, optional
        How many steps above this function to "jump" in the stacktrace when
        displaying file and line number of the error message.
        Usually ``2``

    r   N)r   r   )r   r   r   r   r   warn_deprecatedZ   s   r   c                   @   s&   e Zd ZdZ		dddZdd ZdS )	
deprecateda  Decorator to mark deprecated functions with warning.

    Adapted from
    <https://github.com/scikit-image/scikit-image/blob/master/skimage/_shared/utils.py>.

    Parameters
    ----------
    alt_func : None or str, optional
        If given, tell user what function to use instead.

    behavior : {'warn', 'raise'}, optional
        Behavior during call to deprecated function: ``warn`` means that the
        user is warned that the function is deprecated; ``raise`` means that
        an error is raised.

    removed_version : None or str, optional
        The package version in which the deprecated function will be removed.

    comment : None or str, optional
        An optional comment that will be appended to the warning message.

    Nr   c                 C      || _ || _|| _|| _d S N)alt_funcbehaviorremoved_versioncomment)selfr#   r$   r%   r&   r   r   r   __init__      
zdeprecated.__init__c                    s   d }j d urdj f }d }jd urdjf }d }jd ur1tjdkr1djdf }ddd |||fD  t fd	d
}d  }|jd u rY||_|S |d |j |_|S )NzUse ``%s`` instead.z!It will be removed in version %s.r   z%s.z.  c                 S   s   g | ]}|d ur|qS r"   r   ).0Zsubmsgr   r   r   
<listcomp>   s
    z'deprecated.__call__.<locals>.<listcomp>c                     s   dd l }t|dr|d }n|d }d|v s d|v r,d| d jjjf }ndjf }|d   ddd	}jd
krKt	|dd n	jdkrTt
|| i |S )Nr   getfullargspecr'   clsz!Method ``%s.%s()`` is deprecated.z Function ``%s()`` is deprecated.r*   z```r      )r   raise)inspecthasattrr-   
getargspec	__class__r   rstripreplacer$   r   r   )argskwargsr2   	arg_namesZmain_msgr   Zaddendumfuncr'   r   r   wrapped   s"   


z$deprecated.__call__.<locals>.wrappedz**Deprecated**. z

    )	r#   r%   r&   lenr6   join	functoolswrapsr   )r'   r<   Zalt_msgZrmv_msgZcomment_msgr=   docr   r;   r   __call__   s,   



zdeprecated.__call__)Nr   NN)r   r   r   r   r(   rC   r   r   r   r   r    m   s    
r    c                 C      t | tjS )zCheck whether a variable is a numpy array.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a numpy array. Otherwise ``False``.

    )
isinstancenpZndarrayvalr   r   r   is_np_array      rI   c                 C   s   t | tjo
t| S )zCheck whether a variable is a numpy scalar.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a numpy scalar. Otherwise ``False``.

    )rE   rF   ZgenericZisscalarrG   r   r   r   is_np_scalar   s   rK   c                 C   s   t | tjot | t S )zCheck whether a variable is an ``int``.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is an ``int``. Otherwise ``False``.

    )rE   numbersIntegralboolrG   r   r   r   is_single_integer      rO   c                 C   s"   t | tjot|  ot | t S )zCheck whether a variable is a ``float``.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a ``float``. Otherwise ``False``.

    )rE   rL   RealrO   rN   rG   r   r   r   is_single_float  s
   
rR   c                 C   s   t | pt| S )zCheck whether a variable is a ``number``, i.e. an ``int`` or ``float``.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a ``number``. Otherwise ``False``.

    )rO   rR   rG   r   r   r   is_single_number  s   rS   c                 C   s
   t | tS )z
    Checks whether a variable is iterable.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is an iterable. Otherwise ``False``.

    )rE   r   rG   r   r   r   is_iterable)  s   
rT   c                 C   rD   )zCheck whether a variable is a string.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a string. Otherwise ``False``.

    )rE   sixstring_typesrG   r   r   r   	is_string<     rW   c                 C   s   t | t dkS )zCheck whether a variable is a ``bool``.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a ``bool``. Otherwise ``False``.

    TtyperG   r   r   r   is_single_boolM  s   r[   c                 C      t | ot| jjtjS )zCheck whether a variable is a numpy integer array.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a numpy integer array. Otherwise ``False``.

    )rI   
issubclassdtyperZ   rF   integerrG   r   r   r   is_integer_array_  rP   r`   c                 C   r\   )zCheck whether a variable is a numpy float array.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a numpy float array. Otherwise ``False``.

    )rI   r]   r^   rZ   rF   ZfloatingrG   r   r   r   is_float_arrayp  rP   ra   c                 C   s.   t jd dkrt jd dkrt| dS t| S )zCheck whether a variable is a callable, e.g. a function.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` if the variable is a callable. Otherwise ``False``.

    r   r0      r   rC   )sysversion_infor3   callablerG   r   r   r   is_callable  s   
rf   c                 C   rD   )zCheck whether a variable is a generator.

    Parameters
    ----------
    val
        The variable to check.

    Returns
    -------
    bool
        ``True`` is the variable is a generator. Otherwise ``False``.

    )rE   typesGeneratorTyperG   r   r   r   is_generator  rX   ri   c                 c   sR    t | ttfs| V  dS | D ]}t |ttfr#t|D ]}|V  qq|V  qdS )a7  Flatten arbitrarily nested lists/tuples.

    Code partially taken from https://stackoverflow.com/a/10824420.

    Parameters
    ----------
    nested_iterable
        A ``list`` or ``tuple`` of arbitrarily nested values.

    Yields
    ------
    any
        All values in `nested_iterable`, flattened.

    N)rE   listtupleflatten)Znested_iterableijr   r   r   rl     s   
rl   c                   C   s   t djjS )zReturn the name of the caller, e.g. a function.

    Returns
    -------
    str
        The name of the caller as a string

    rb   )rc   	_getframef_codeco_namer   r   r   r   caller_name  s   
rr   c                 C   s^   | dus|dusJ d|dur#| du sJ dt | f td |} ddl}|j|  dS )a  Set the seed of imgaug's global RNG.

    The global RNG controls most of the "randomness" in imgaug.

    The global RNG is the default one used by all augmenters. Under special
    circumstances (e.g. when an augmenter is switched to deterministic mode),
    the global RNG is replaced with a local one. The state of that replacement
    may be dependent on the global RNG's state at the time of creating the
    child RNG.

    .. note::

        This function is not yet marked as deprecated, but might be in the
        future. The preferred way to seed `imgaug` is via
        :func:`~imgaug.random.seed`.

    Parameters
    ----------
    entropy : int
        The seed value to use.

    seedval : None or int, optional
        Deprecated since 0.4.0.

    NzKExpected argument 'entropy' or 'seedval' to be not-None, but bothwere None.zArgument 'seedval' is the outdated name for 'entropy'. Hence, if it is provided, 'entropy' must be None. Got 'entropy' value of type %s.z9Parameter 'seedval' is deprecated. Use 'entropy' instead.r   )rZ   r   imgaug.randomrandomseed)ZentropyZseedvalimgaugr   r   r   ru     s   
ru   z!imgaug.random.normalize_generatorc                 C      ddl }|j| S )a  Normalize various inputs to a numpy random generator.

    Parameters
    ----------
    random_state : None or int or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.bit_generator.SeedSequence or numpy.random.RandomState
        See :func:`~imgaug.random.normalize_generator`.

    Returns
    -------
    numpy.random.Generator or numpy.random.RandomState
        In numpy <=1.16 a ``RandomState``, in 1.17+ a ``Generator`` (even if
        the input was a ``RandomState``).

    r   N)rs   rt   Znormalize_generator_random_staterv   r   r   r   normalize_random_state     rz   zimgaug.random.get_global_rngc                  C   s   ddl } | j S )zGet or create the current global RNG of imgaug.

    Note that the first call to this function will create a global RNG.

    Returns
    -------
    imgaug.random.RNG
        The global RNG to use.

    r   N)rs   rt   Zget_global_rngrv   r   r   r   current_random_state  s   
r}   z!imgaug.random.convert_seed_to_rngFc                 C   s8   ddl }| du r|r|jj S |jj S |j| S )aa  Create a new numpy random number generator.

    Parameters
    ----------
    seed : None or int, optional
        The seed value to use. If ``None`` and `fully_random` is ``False``,
        the seed will be derived from the global RNG. If `fully_random` is
        ``True``, the seed will be provided by the OS.

    fully_random : bool, optional
        Whether the seed will be provided by the OS.

    Returns
    -------
    numpy.random.Generator or numpy.random.RandomState
        In numpy <=1.16 a ``RandomState``, in 1.17+ a ``Generator``.
        Both are initialized with the provided seed.

    r   N)rs   rt   RNGZcreate_fully_randomZcreate_pseudo_random_)ru   Zfully_randomrv   r   r   r   new_random_state!  s   r   c                  C   s   ddl } | jdS )zCreate a dummy random state using a seed of ``1``.

    Returns
    -------
    imgaug.random.RNG
        The new random state.

    r   Nrb   )rs   rt   r~   r|   r   r   r   dummy_random_state@  s   
r   z.imgaug.random.copy_generator_unless_global_rngc                 C   s$   ddl }|r|j| S |j| S )a  Copy an existing numpy (random number) generator.

    Parameters
    ----------
    random_state : numpy.random.Generator or numpy.random.RandomState
        The generator to copy.

    force_copy : bool, optional
        If ``True``, this function will always create a copy of every random
        state. If ``False``, it will not copy numpy's default random state,
        but all other random states.

    Returns
    -------
    rs_copy : numpy.random.RandomState
        The copied random state.

    r   N)rs   rt   Zcopy_generatorZ&copy_generator_unless_global_generator)ry   Z
force_copyrv   r   r   r   copy_random_stateN  s   r   zimgaug.random.derive_generator_c                 C   rw   )a  Derive a child numpy random generator from another one.

    Parameters
    ----------
    random_state : numpy.random.Generator or numpy.random.RandomState
        The generator from which to derive a new child generator.

    Returns
    -------
    numpy.random.Generator or numpy.random.RandomState
        In numpy <=1.16 a ``RandomState``, in 1.17+ a ``Generator``.
        In both cases a derived child generator.

    r   N)rs   rt   Zderive_generator_rx   r   r   r   derive_random_stateh  r{   r   z imgaug.random.derive_generators_rb   c                 C   s   ddl }|jj| |dS )a*  Derive child numpy random generators from another one.

    Parameters
    ----------
    random_state : numpy.random.Generator or numpy.random.RandomState
        The generator from which to derive new child generators.

    n : int, optional
        Number of child generators to derive.

    Returns
    -------
    list of numpy.random.Generator or list of numpy.random.RandomState
        In numpy <=1.16 a ``list`` of  ``RandomState`` s,
        in 1.17+ a ``list`` of ``Generator`` s.
        In both cases lists of derived child generators.

    r   N)n)rs   rt   Zderive_generators_)ry   r   rv   r   r   r   derive_random_states|  s   r   z imgaug.random.advance_generator_c                 C   s   ddl }|j|  dS )zAdvance a numpy random generator's internal state.

    Parameters
    ----------
    random_state : numpy.random.Generator or numpy.random.RandomState
        Generator of which to advance the internal state.

    r   N)rs   rt   Zadvance_generator_rx   r   r   r   forward_random_state  s   
r   c                 C   s   ddl m}m} | dkr|ddddd}|S t| tr3t| dkr3|| d | d | d | d	 d}|S t| |r<| }|S t| |rdt| jdksLJ d
| jdd dks]J d| jf | jd }|S tdt	| f )a  Generate a normalized rectangle for the standard quokka image.

    Parameters
    ----------
    extract : 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        Unnormalized representation of the image subarea to be extracted.

            * If ``str`` ``square``, then a squared area
              ``(x: 0 to max 643, y: 0 to max 643)`` will be extracted from
              the image.
            * If a ``tuple``, then expected to contain four ``number`` s
              denoting ``(x1, y1, x2, y2)``.
            * If a :class:`~imgaug.augmentables.bbs.BoundingBox`, then that
              bounding box's area will be extracted from the image.
            * If a :class:`~imgaug.augmentables.bbs.BoundingBoxesOnImage`,
              then expected to contain exactly one bounding box and a shape
              matching the full image dimensions (i.e. ``(643, 960, *)``).
              Then the one bounding box will be used similar to
              ``BoundingBox`` above.

    Returns
    -------
    imgaug.augmentables.bbs.BoundingBox
        Normalized representation of the area to extract from the standard
        quokka image.

    r   BoundingBoxBoundingBoxesOnImagesquare  x1y1x2y2   rb   r   r0   zXProvided BoundingBoxesOnImage instance may currently only contain a single bounding box.r     zXExpected BoundingBoxesOnImage instance on an image of shape (643, 960, ?). Got shape %s.zrExpected 'square' or tuple of four entries or BoundingBox or BoundingBoxesOnImage for parameter 'extract', got %s.)
imgaug.augmentables.bbsr   r   rE   rk   r>   bounding_boxesshape	ExceptionrZ   )extractr   r   bbr   r   r   _quokka_normalize_extract  s8   


r   c                 C   s  t | r| j} t |r|j}t| }|du r	 t|S t|trt| dv s(J t|dv s0J t| dkrGt|dkrG| d |d ksFJ nt|dkrT||d  tdd |dd D }|suJ dtd	d |dd D f t	| dd D ])\}}|| du r|||< q}t
|| r|| ||< q}tt|||  ||< q}t|S t
|st|rt| ||f}t|S td
t|f )a  Compute the intended new shape of an image-like array after resizing.

    Parameters
    ----------
    from_shape : tuple or ndarray
        Old shape of the array. Usually expected to be a ``tuple`` of form
        ``(H, W)`` or ``(H, W, C)`` or alternatively an array with two or
        three dimensions.

    to_shape : None or tuple of ints or tuple of floats or int or float or ndarray
        New shape of the array.

            * If ``None``, then `from_shape` will be used as the new shape.
            * If an ``int`` ``V``, then the new shape will be ``(V, V, [C])``,
              where ``C`` will be added if it is part of `from_shape`.
            * If a ``float`` ``V``, then the new shape will be
              ``(H*V, W*V, [C])``, where ``H`` and ``W`` are the old
              height/width.
            * If a ``tuple`` ``(H', W', [C'])`` of ints, then ``H'`` and ``W'``
              will be used as the new height and width.
            * If a ``tuple`` ``(H', W', [C'])`` of floats (except ``C``), then
              ``H'`` and ``W'`` will be used as the new height and width.
            * If a numpy array, then the array's shape will be used.

    Returns
    -------
    tuple of int
        New shape.

    Nr   r0   r0   r   c                 S   s   g | ]
}|d u pt |qS r"   rS   r+   vr   r   r   r,         z*_compute_resized_shape.<locals>.<listcomp>r   zOExpected the first two entries in to_shape to be None or numbers, got types %s.c                 S      g | ]}t |qS r   rY   r   r   r   r   r,         zrExpected to_shape to be None or ndarray or tuple of floats or tuple of ints or single int or single float, got %s.)rI   r   rj   rE   rk   r>   appendallstr	enumeraterO   r   rF   roundrR   _compute_resized_shaper   rZ   )Z
from_shapeZto_shapeZto_shape_computedZis_to_s_valid_valuesrm   Zfrom_shape_ir   r   r   r     sR   !


r   c                 C   sR   t jtdd}|durt|}||}| dur't|j| }t||dd }|S )a  Return an image of a quokka as a numpy array.

    Parameters
    ----------
    size : None or float or tuple of int, optional
        Size of the output image. Input into
        :func:`~imgaug.imgaug.imresize_single_image`. Usually expected to be a
        ``tuple`` ``(H, W)``, where ``H`` is the desired height and ``W`` is
        the width. If ``None``, then the image will not be resized.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        Subarea of the quokka image to extract:

            * If ``None``, then the whole image will be used.
            * If ``str`` ``square``, then a squared area
              ``(x: 0 to max 643, y: 0 to max 643)`` will be extracted from
              the image.
            * If a ``tuple``, then expected to contain four ``number`` s
              denoting ``(x1, y1, x2, y2)``.
            * If a :class:`~imgaug.augmentables.bbs.BoundingBox`, then that
              bounding box's area will be extracted from the image.
            * If a :class:`~imgaug.augmentables.bbs.BoundingBoxesOnImage`,
              then expected to contain exactly one bounding box and a shape
              matching the full image dimensions (i.e. ``(643, 960, *)``).
              Then the one bounding box will be used similar to
              ``BoundingBox`` above.

    Returns
    -------
    (H,W,3) ndarray
        The image array of dtype ``uint8``.

    RGBZpilmodeNr   r   )imageioimread	QUOKKA_FPr   extract_from_imager   r   imresize_single_image)sizer   imgr   shape_resizedr   r   r   quokka%  s   "
r   c                 C   s   t | ddS )a  Return an (square) image of a quokka as a numpy array.

    Parameters
    ----------
    size : None or float or tuple of int, optional
        Size of the output image. Input into
        :func:`~imgaug.imgaug.imresize_single_image`. Usually expected to be a
        ``tuple`` ``(H, W)``, where ``H`` is the desired height and ``W`` is
        the width. If ``None``, then the image will not be resized.

    Returns
    -------
    (H,W,3) ndarray
        The image array of dtype ``uint8``.

    r   )r   r   )r   r   r   r   r   quokka_squareQ  rJ   r   c                 C   s   ddl m} tjtdd}t|ddd}|dur!t|}||}| du r,|jdd	 } t	|j| }t||dd	 }|d
 }|
tjd }d| }|||jdd	 d dS )a  Return a heatmap (here: depth map) for the standard example quokka image.

    Parameters
    ----------
    size : None or float or tuple of int, optional
        See :func:`~imgaug.imgaug.quokka`.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        See :func:`~imgaug.imgaug.quokka`.

    Returns
    -------
    imgaug.augmentables.heatmaps.HeatmapsOnImage
        Depth map as an heatmap object. Values close to ``0.0`` denote objects
        that are close to the camera. Values close to ``1.0`` denote objects
        that are furthest away (among all shown objects).

    r   )HeatmapsOnImager   r   r   r   interpolationNr   ).r   g     o@rb   r0   r   )Zimgaug.augmentables.heatmapsr   r   r   QUOKKA_DEPTH_MAP_HALFRES_FPr   r   r   r   r   astyperF   float32)r   r   r   r   r   r   Zimg_0to1r   r   r   quokka_heatmape  s   
r   c                 C   s8  ddl m} ttd}t|}W d   n1 sw   Y  g }g }|d d d D ]}|d }|d }	|| ||	 q,tjd	tj	d
}
t
jjt|t||
jd\}}d|
||df< |durot|}||
}
||
|
jdd d d}| durt|
j| }||dd }t|dd d |_|S )a  Return a segmentation map for the standard example quokka image.

    Parameters
    ----------
    size : None or float or tuple of int, optional
        See :func:`~imgaug.imgaug.quokka`.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        See :func:`~imgaug.imgaug.quokka`.

    Returns
    -------
    imgaug.augmentables.segmaps.SegmentationMapsOnImage
        Segmentation map object.

    r   )SegmentationMapsOnImagerNpolygons	keypointsxy)r   r   rb   r^   r   rb   r   r   )Zimgaug.augmentables.segmapsr   openQUOKKA_ANNOTATIONS_FPjsonloadr   rF   zerosint32skimageZdrawZpolygonarrayr   r   r   r   resizerk   )r   r   r   f	json_dictxxyykp_dictr   r   Zimg_segZrrccr   Zsegmapr   r   r   r   quokka_segmentation_map  s2   


r   c                 C   s   ddl m}m} d\}}|durt|}|j}|j}ttd}t	|}W d   n1 s/w   Y  g }	|d D ]}
|	
||
d | |
d | d	 q:|durZ|j|jd
f}nd}||	|d}| durpt|| }||}|S )aI  Return example keypoints on the standard example quokke image.

    The keypoints cover the eyes, ears, nose and paws.

    Parameters
    ----------
    size : None or float or tuple of int or tuple of float, optional
        Size of the output image on which the keypoints are placed. If
        ``None``, then the keypoints are not projected to any new size
        (positions on the original image are used). ``float`` s lead to
        relative size changes, ``int`` s to absolute sizes in pixels.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        Subarea to extract from the image. See :func:`~imgaug.imgaug.quokka`.

    Returns
    -------
    imgaug.augmentables.kps.KeypointsOnImage
        Example keypoints on the quokka image.

    r   )KeypointKeypointsOnImager   r   Nr   r   r   r   r   r   r0   r   r   r0   r   )Zimgaug.augmentables.kpsr   r   r   r   r   r   r   r   r   r   heightwidthr   on)r   r   r   r   lefttop
bb_extractr   r   r   r   r   Zkpsoir   r   r   r   quokka_keypoints  s(   $

r   c              	   C   s   ddl m}m} d\}}|durt|}|j}|j}ttd}t	|}W d   n1 s/w   Y  g }	|d D ]}
|	
||
d | |
d | |
d	 | |
d
 | d q:|durd|j|jdf}nd}||	|d}| durzt|| }||}|S )aV  Return example bounding boxes on the standard example quokke image.

    Currently only a single bounding box is returned that covers the quokka.

    Parameters
    ----------
    size : None or float or tuple of int or tuple of float, optional
        Size of the output image on which the BBs are placed. If ``None``, then
        the BBs are not projected to any new size (positions on the original
        image are used). ``float`` s lead to relative size changes, ``int`` s
        to absolute sizes in pixels.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        Subarea to extract from the image. See :func:`~imgaug.imgaug.quokka`.

    Returns
    -------
    imgaug.augmentables.bbs.BoundingBoxesOnImage
        Example BBs on the quokka image.

    r   r   r   Nr   r   r   r   r   r   r   r0   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   ZbbsZbb_dictr   Zbbsoir   r   r   r   quokka_bounding_boxes  s6   





r   c                    s   ddl m}m} d\ |durt|}|j |jttd}t	|}W d   n1 s/w   Y  g }|d D ]}|
| fdd|d	 D  q:|durZ|j|jd
f}	nd}	|||	d}
| durpt|	| }|
|}
|
S )aY  
    Returns example polygons on the standard example quokke image.

    The result contains one polygon, covering the quokka's outline.

    Parameters
    ----------
    size : None or float or tuple of int or tuple of float, optional
        Size of the output image on which the polygons are placed. If ``None``,
        then the polygons are not projected to any new size (positions on the
        original image are used). ``float`` s lead to relative size changes,
        ``int`` s to absolute sizes in pixels.

    extract : None or 'square' or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage
        Subarea to extract from the image. See :func:`~imgaug.imgaug.quokka`.

    Returns
    -------
    imgaug.augmentables.polys.PolygonsOnImage
        Example polygons on the quokka image.

    r   )PolygonPolygonsOnImager   Nr   r   c                    s$   g | ]}|d    |d  fqS r   r   )r+   pointr   r   r   r   r,   G  s    z#quokka_polygons.<locals>.<listcomp>r   r0   r   r   )Zimgaug.augmentables.polysr   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   Z	poly_jsonr   Zpsoir   r   r   r   quokka_polygons#  s0   

r   c                 C   sp   t j| }t j|}|dkr| | nt | d }|dkr#|| nt |d }t t t ||ddS )a  Calculcate the angle in radians between vectors `v1` and `v2`.

    From
    http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python

    Parameters
    ----------
    v1 : (N,) ndarray
        First vector.

    v2 : (N,) ndarray
        Second vector.

    Returns
    -------
    float
        Angle in radians.

    Examples
    --------
    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([0, 1, 0]))
    1.570796...

    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([1, 0, 0]))
    0.0

    >>> angle_between_vectors(np.float32([1, 0, 0]), np.float32([-1, 0, 0]))
    3.141592...

    r   g      g      ?)rF   ZlinalgZnormr   ZarccosZclipdot)Zv1Zv2Zlength1Zlength2Zv1_unitZv2_unitr   r   r   angle_between_vectorsV  s
    r   c                 C   s   dd }|| |f||f}	|||f||f}
|	d |
d  |	d |
d   }|	d |
d  |	d |
d   }|	d |
d  |	d |
d   }|dkrV|| }|| }||fS dS )a  Compute the intersection point of two lines.

    Taken from https://stackoverflow.com/a/20679579 .

    Parameters
    ----------
    x1 : number
        x coordinate of the first point on line 1.
        (The lines extends beyond this point.)

    y1 : number
        y coordinate of the first point on line 1.
        (The lines extends beyond this point.)

    x2 : number
        x coordinate of the second point on line 1.
        (The lines extends beyond this point.)

    y2 : number
        y coordinate of the second point on line 1.
        (The lines extends beyond this point.)

    x3 : number
        x coordinate of the first point on line 2.
        (The lines extends beyond this point.)

    y3 : number
        y coordinate of the first point on line 2.
        (The lines extends beyond this point.)

    x4 : number
        x coordinate of the second point on line 2.
        (The lines extends beyond this point.)

    y4 : number
        y coordinate of the second point on line 2.
        (The lines extends beyond this point.)

    Returns
    -------
    tuple of number or bool
        The coordinate of the intersection point as a ``tuple`` ``(x, y)``.
        If the lines are parallel (no intersection point or an infinite number
        of them), the result is ``False``.

    c                 S   sL   | d |d  }|d | d  }| d |d  |d | d   }||| fS )Nrb   r   r   )Zpoint1Zpoint2Zline_yZline_xZsloper   r   r   
_make_line  s    z3compute_line_intersection_point.<locals>._make_liner   rb   r   Fr   )r   r   r   r   Zx3Zy3Zx4Zy4r   line1line2DZDxZDyr   r   r   r   r   compute_line_intersection_point  s   0   r   r      r      c              
   C   s  ddl m}m}m} | jjdv sJ d| jjf | j}	| jtjkr(| tj	} |
| } |t|}
|| }|j||f|t||
d t| }|jd suz|jdd W n tyt } zd	t|v rjt|}W Y d
}~nd
}~ww |j|	kr||	}|S )a  Draw text on an image.

    This uses by default DejaVuSans as its font, which is included in this
    library.

    **Supported dtypes**:

        * ``uint8``: yes; fully tested
        * ``uint16``: no
        * ``uint32``: no
        * ``uint64``: no
        * ``int8``: no
        * ``int16``: no
        * ``int32``: no
        * ``int64``: no
        * ``float16``: no
        * ``float32``: yes; not tested
        * ``float64``: no
        * ``float128``: no
        * ``bool``: no

        TODO check if other dtypes could be enabled

    Parameters
    ----------
    img : (H,W,3) ndarray
        The image array to draw text on.
        Expected to be of dtype ``uint8`` or ``float32`` (expected value
        range is ``[0.0, 255.0]``).

    y : int
        x-coordinate of the top left corner of the text.

    x : int
        y- coordinate of the top left corner of the text.

    text : str
        The text to draw.

    color : iterable of int, optional
        Color of the text to draw. For RGB-images this is expected to be an
        RGB color.

    size : int, optional
        Font size of the text to draw.

    Returns
    -------
    (H,W,3) ndarray
        Input image with text drawn on it.

    r   )Image	ImageDraw	ImageFont)uint8r   zSCan currently draw text only on images of dtype 'uint8' or 'float32'. Got dtype %s.)fillfontZ	WRITEABLET)writez/cannot set WRITEABLE flag to True of this arrayN)ZPILr   r   r   r^   namerF   r   r   r   Z	fromarrayZtruetypeDEFAULT_FONT_FPZDrawtextrk   ZasarrayflagsZsetflags
ValueErrorr   copy)r   r   r   r   colorr   Z	PIL_ImageZPIL_ImageDrawZPIL_ImageFontinput_dtyper   contextZimg_npexr   r   r   	draw_text  s2   5






r  c                    s  t | dkr| S trdkrtdf tr fn)t dks/J dt f tdd D sIJ dtdd D tf t| trqt d	d
 | D }|dkrgttt	| dS fdd| D S | j
}| jdv sJ dt|f |d }|d |d }}| jdkr|d nd}d d  t rtt|  n  trtt| n |krΈ|krt| S d |fv rt|d  gt|dd  }	tj|	| jdS tdd | j
dd D }
|
rJ dtdd | D f du s+tv s+J dddd tD tf du rB |ks:|kr>tjn+tjn'dtjfv rNtjndtjfv rZtjndtjfv rftjntjddlm} tjkr|j| g dg ddd n|j| g d g d!dd | f}|dur||f }tj|| jd}t| D ]\}j}|j}|d"krÈ tj!d# n|d$krՈtjkrՈ tj"n|d%kr tj#|dur|d&kr fd'dt$%|D }tj&|d(d)}n
tj' fd*}|jjjjks J d+jj|jjf t |j
dkr>|dur>|dkr>|ddddtj(f }|d"krH|d,k}n+|d$kratjkraddlm} |)|tj*}n|d%krsddlm} |)|tj+}|||< q|S )-aB  Resize each image in a list or array to a specified size.

    **Supported dtypes**:

        * ``uint8``: yes; fully tested
        * ``uint16``: yes; tested
        * ``uint32``: no (1)
        * ``uint64``: no (2)
        * ``int8``: yes; tested (3)
        * ``int16``: yes; tested
        * ``int32``: limited; tested (4)
        * ``int64``: no (2)
        * ``float16``: yes; tested (5)
        * ``float32``: yes; tested
        * ``float64``: yes; tested
        * ``float128``: no (1)
        * ``bool``: yes; tested (6)

        - (1) rejected by ``cv2.imresize``
        - (2) results too inaccurate
        - (3) mapped internally to ``int16`` when interpolation!="nearest"
        - (4) only supported for interpolation="nearest", other interpolations
              lead to cv2 error
        - (5) mapped internally to ``float32``
        - (6) mapped internally to ``uint8``

    Parameters
    ----------
    images : (N,H,W,[C]) ndarray or list of (H,W,[C]) ndarray
        Array of the images to resize.
        Usually recommended to be of dtype ``uint8``.

    sizes : float or iterable of int or iterable of float
        The new size of the images, given either as a fraction (a single
        float) or as a ``(height, width)`` ``tuple`` of two integers or as a
        ``(height fraction, width fraction)`` ``tuple`` of two floats.

    interpolation : None or str or int, optional
        The interpolation to use during resize.
        If ``int``, then expected to be one of:

            * ``cv2.INTER_NEAREST`` (nearest neighbour interpolation)
            * ``cv2.INTER_LINEAR`` (linear interpolation)
            * ``cv2.INTER_AREA`` (area interpolation)
            * ``cv2.INTER_CUBIC`` (cubic interpolation)

        If ``str``, then expected to be one of:

            * ``nearest`` (identical to ``cv2.INTER_NEAREST``)
            * ``linear`` (identical to ``cv2.INTER_LINEAR``)
            * ``area`` (identical to ``cv2.INTER_AREA``)
            * ``cubic`` (identical to ``cv2.INTER_CUBIC``)

        If ``None``, the interpolation will be chosen automatically. For size
        increases, ``area`` interpolation will be picked and for size
        decreases, ``linear`` interpolation will be picked.

    Returns
    -------
    (N,H',W',[C]) ndarray
        Array of the resized images.

    Examples
    --------
    >>> import imgaug as ia
    >>> images = np.zeros((2, 8, 16, 3), dtype=np.uint8)
    >>> images_resized = ia.imresize_many_images(images, 2.0)
    >>> images_resized.shape
    (2, 16, 32, 3)

    Convert two RGB images of height ``8`` and width ``16`` to images of
    height ``2*8=16`` and width ``2*16=32``.

    >>> images_resized = ia.imresize_many_images(images, (2.0, 4.0))
    >>> images_resized.shape
    (2, 16, 64, 3)

    Convert two RGB images of height ``8`` and width ``16`` to images of
    height ``2*8=16`` and width ``4*16=64``.

    >>> images_resized = ia.imresize_many_images(images, (16, 32))
    >>> images_resized.shape
    (2, 16, 32, 3)

    Converts two RGB images of height ``8`` and width ``16`` to images of
    height ``16`` and width ``32``.

    r   zLIf 'sizes' is given as a single number, it is expected to be >= 0, got %.8f.r   zYIf 'sizes' is given as a tuple, it is expected be a tuple of two entries, got %d entries.c                 S      g | ]
}t |o|d kqS r   r   r+   rH   r   r   r   r,     r   z(imresize_many_images.<locals>.<listcomp>z|If 'sizes' is given as a tuple, it is expected be a tuple of two ints or two floats, each >= 0, got types %s with values %s.c                 S   r   r   rY   r  r   r   r   r,     r   c                 S   s   h | ]}|j qS r   r   r+   imager   r   r   	<setcomp>      z'imresize_many_images.<locals>.<setcomp>rb   sizesr   c                    s(   g | ]}t |tjd f  dd qS ).r	  r   .)imresize_many_imagesrF   newaxisr  )r   r
  r   r   r,     s    r0   r   z4Expected array of shape (N, H, W, [C]), got shape %sr0   Nr   c                 S   s   g | ]}|d kqS r  r   )r+   axisr   r   r   r,     r   zCannot resize images, because at least one image has a height and/or width and/or number of channels of zero. Observed shapes were: %s.c                 S   s   g | ]}|j qS r   r   r  r   r   r   r,     r  z9Expected 'interpolation' to be None or one of %s. Got %s., c                 S   r   r   )r   )r+   Zvalid_ipr   r   r   r,     r   r
   r   r   dtypes)	rN   r   uint16int8int16r   float16r   float64)
uint32uint64uint128uint256int64int128int256float96float128float256allowedZ
disallowed	augmenter)rN   r   r  r  r  r  r   r  )r  r  r  r  r   r  r  r  r  r   r!  rN   r   r  r     c                    s(   g | ]}t jd |f  fdqS ).r   )cv2r   )r+   c)height_targetr  interwidth_targetr   r   r,     s    r  r   zkExpected cv2.resize() to keep the input dtype '%s', but got '%s'. This is an internal error. Please report.   ),r>   rS   r   r   r   rE   rj   r  rF   r   r   ndimrR   r   r   r   rk   r   r^   anyIMRESIZE_VALID_INTERPOLATIONSr?   r&  
INTER_AREAINTER_LINEARINTER_NEARESTINTER_CUBIC r  gate_dtypesr   r   r   r   r  r   smxrangestackr   r  Zrestore_dtypes_r  r  )imagesr
  r   Z	nb_shapesr   	nb_imagesZheight_imageZwidth_imagenb_channelsZ	shape_outZhas_zero_size_axesiadtZresult_shaperesultrm   r   Zinput_dtype_nameZchannelsZ
result_imgr   )r(  r  r)  r   r
  r*  r   r    s  ]









	



r  c                 C   s4   t | dr| j} t| dv sJ dt| | f d S )Nr   r   zPExpected image with two or three dimensions, but got %d dimensions and shape %s.)r3   r   r>   r   r   r   r   _assert_two_or_three_dims'  s   

r?  c                 C   s~   t |  d}| jdkrd}| ddddtjf } t| tjddddddf ||d}|r;|ddddddf S |d S )aU  Resize a single image.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.imresize_many_images`.

    Parameters
    ----------
    image : (H,W,C) ndarray or (H,W) ndarray
        Array of the image to resize.
        Usually recommended to be of dtype ``uint8``.

    sizes : float or iterable of int or iterable of float
        See :func:`~imgaug.imgaug.imresize_many_images`.

    interpolation : None or str or int, optional
        See :func:`~imgaug.imgaug.imresize_many_images`.

    Returns
    -------
    (H',W',C) ndarray or (H',W') ndarray
        The resized image.

    Fr   TNr   r   r  )r?  r.  rF   r  r  )r  r
  r   Z	grayscalersr   r   r   r   /  s   
 r   constantTc                 C   s2  ddl m} ddlm} | jdkrt| S |j| g dg ddd |dur-td	 |}t|  t	|o8|dk}	t
|oIt|d
v oIdd |D }
|	sV|
sVJ dt| t	|r^||g}t|| jk rlt|dg }|j| |d |d ||d} | j}tjj| t|||d}|r|jj|jkr||}|S )aP	  Resize an array by pooling values within blocks.

    **Supported dtypes**:

        * ``uint8``: yes; fully tested
        * ``uint16``: yes; tested
        * ``uint32``: yes; tested (2)
        * ``uint64``: no (1)
        * ``int8``: yes; tested
        * ``int16``: yes; tested
        * ``int32``: yes; tested (2)
        * ``int64``: no (1)
        * ``float16``: yes; tested
        * ``float32``: yes; tested
        * ``float64``: yes; tested
        * ``float128``: yes; tested (2)
        * ``bool``: yes; tested

        - (1) results too inaccurate (at least when using np.average as func)
        - (2) Note that scikit-image documentation says that the wrapped
              pooling function converts inputs to ``float64``. Actual tests
              showed no indication of that happening (at least when using
              preserve_dtype=True).

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Image-like array to pool. Ideally of datatype ``float64``.

    block_size : int or tuple of int
        Spatial size of each group of values to pool, aka kernel size.

          * If a single ``int``, then a symmetric block of that size along
            height and width will be used.
          * If a ``tuple`` of two values, it is assumed to be the block size
            along height and width of the image-like, with pooling happening
            per channel.
          * If a ``tuple`` of three values, it is assumed to be the block size
            along height, width and channels.

    func : callable
        Function to apply to a given block in order to convert it to a single
        number, e.g. :func:`numpy.average`, :func:`numpy.min`,
        :func:`numpy.max`.

    pad_mode : str, optional
        Padding mode to use if the array cannot be divided by `block_size`
        without remainder. See :func:`~imgaug.imgaug.pad` for details.

    pad_cval : number, optional
        Value to use for padding if `mode` is ``constant``.
        See :func:`numpy.pad` for details.

    preserve_dtype : bool, optional
        Whether to convert the array back to the input datatype if it is
        changed away from that in the pooling process.

    cval : None or number, optional
        Deprecated. Old name for `pad_cval`.

    Returns
    -------
    (H',W') ndarray or (H',W',C') ndarray
        Array after pooling.

    rb   r  r   r   )rN   r   r  r  r  r  r   r  r   r  r   )r  r  r  r  r  r  r!  Nr"  zB`cval` is a deprecated argument in pool(). Use `pad_cval` instead.r   c                 S   r  rb   )rO   r  r   r   r   r,     r   zpool.<locals>.<listcomp>ztExpected argument 'block_size' to be a single integer >0 or a tuple of 2 or 3 values with each one being >0. Got %s.)Zheight_multipleZwidth_multiplemodecval)rD  )r5  r  Z
augmentersr   rF   r   r6  r   r?  rO   rT   r>   r   r.  rj   pad_to_multiples_ofr^   r   measureZblock_reducerk   r   r   )arr
block_sizer<   pad_modepad_cvalpreserve_dtyperD  r=  ZiasizeZis_valid_intZis_valid_tupler   Zarr_reducedr   r   r   poolV  sP   E




rL  reflect   c              	   C      t | |tj||||dS )a|  Resize an array using average pooling.

    Defaults to ``pad_mode="reflect"`` to ensure that padded values do not
    affect the average.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.pool`.

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Image-like array to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    block_size : int or tuple of int or tuple of int
        Size of each block of values to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    pad_mode : str, optional
        Padding mode to use if the array cannot be divided by `block_size`
        without remainder.
        See :func:`~imgaug.imgaug.pad` for details.

    pad_cval : number, optional
        Padding value.
        See :func:`~imgaug.imgaug.pool` for details.

    preserve_dtype : bool, optional
        Whether to preserve the input array dtype.
        See  :func:`~imgaug.imgaug.pool` for details.

    cval : None or number, optional
        Deprecated. Old name for `pad_cval`.

    Returns
    -------
    (H',W') ndarray or (H',W',C') ndarray
        Array after average pooling.

    rI  rJ  rK  rD  )rL  rF   ZaveragerG  rH  rI  rJ  rK  rD  r   r   r   avg_pool     +rR  edgec              	   C   rO  )a  Resize an array using max-pooling.

    Defaults to ``pad_mode="edge"`` to ensure that padded values do not affect
    the maximum, even if the dtype was something else than ``uint8``.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.pool`.

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Image-like array to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    block_size : int or tuple of int or tuple of int
        Size of each block of values to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    pad_mode : str, optional
        Padding mode to use if the array cannot be divided by `block_size`
        without remainder.
        See :func:`~imgaug.imgaug.pad` for details.

    pad_cval : number, optional
        Padding value.
        See :func:`~imgaug.imgaug.pool` for details.

    preserve_dtype : bool, optional
        Whether to preserve the input array dtype.
        See  :func:`~imgaug.imgaug.pool` for details.

    cval : None or number, optional
        Deprecated. Old name for `pad_cval`.

    Returns
    -------
    (H',W') ndarray or (H',W',C') ndarray
        Array after max-pooling.

    rP  )rL  rF   maxrQ  r   r   r   max_pool  rS  rV  r   c                 C      t | |tj|||dS )aT  Resize an array using min-pooling.

    Defaults to ``pad_mode="edge"`` to ensure that padded values do not affect
    the minimum, even if the dtype was something else than ``uint8``.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.pool`.

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Image-like array to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    block_size : int or tuple of int or tuple of int
        Size of each block of values to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    pad_mode : str, optional
        Padding mode to use if the array cannot be divided by `block_size`
        without remainder.
        See :func:`~imgaug.imgaug.pad` for details.

    pad_cval : number, optional
        Padding value.
        See :func:`~imgaug.imgaug.pool` for details.

    preserve_dtype : bool, optional
        Whether to preserve the input array dtype.
        See  :func:`~imgaug.imgaug.pool` for details.

    Returns
    -------
    (H',W') ndarray or (H',W',C') ndarray
        Array after min-pooling.

    rI  rJ  rK  )rL  rF   minrG  rH  rI  rJ  rK  r   r   r   min_pool2  s   (r[  c                 C   rW  )a%  Resize an array using median-pooling.

    Defaults to ``pad_mode="reflect"`` to ensure that padded values do not
    affect the average.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.pool`.

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Image-like array to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    block_size : int or tuple of int or tuple of int
        Size of each block of values to pool.
        See :func:`~imgaug.imgaug.pool` for details.

    pad_mode : str, optional
        Padding mode to use if the array cannot be divided by `block_size`
        without remainder.
        See :func:`~imgaug.imgaug.pad` for details.

    pad_cval : number, optional
        Padding value.
        See :func:`~imgaug.imgaug.pool` for details.

    preserve_dtype : bool, optional
        Whether to preserve the input array dtype.
        See  :func:`~imgaug.imgaug.pool` for details.

    Returns
    -------
    (H',W') ndarray or (H',W',C') ndarray
        Array after min-pooling.

    rX  )rL  rF   ZmedianrZ  r   r   r   median_pool^  s   (r\  c                 C   s  t | }|dksJ dt| r | jdksJ d| j| jf nmt| s-J dt| f tdd | D sDJ dd	d
d | D  tdd | D s[J dd	dd | D  t dd | D dkstJ dd	dd | D  t dd | D dksJ dd	dd | D  tdd | D }tdd | D }| d jd }|du r|du rt	t
t
| }}n|durt	t
|| }n|durt	t
|| }|| |ksJ d|||| |f || }|| }t| r| jn| d j}	tj|||f|	d}
d}t|D ]<}t|D ]3}||k rB| | }|| }||jd  }|| }||jd  }||
||||ddf< |d7 }qq|
S )a  Combine multiple images into a single grid-like image.

    Calling this function with four images of the same shape and ``rows=2``,
    ``cols=2`` will combine the four images to a single image array of shape
    ``(2*H, 2*W, C)``, where ``H`` is the height of any of the images
    (analogous ``W``) and ``C`` is the number of channels of any image.

    Calling this function with four images of the same shape and ``rows=4``,
    ``cols=1`` is analogous to calling :func:`numpy.vstack` on the images.

    **Supported dtypes**:

        * ``uint8``: yes; fully tested
        * ``uint16``: yes; fully tested
        * ``uint32``: yes; fully tested
        * ``uint64``: yes; fully tested
        * ``int8``: yes; fully tested
        * ``int16``: yes; fully tested
        * ``int32``: yes; fully tested
        * ``int64``: yes; fully tested
        * ``float16``: yes; fully tested
        * ``float32``: yes; fully tested
        * ``float64``: yes; fully tested
        * ``float128``: yes; fully tested
        * ``bool``: yes; fully tested

    Parameters
    ----------
    images : (N,H,W,3) ndarray or iterable of (H,W,3) array
        The input images to convert to a grid.

    rows : None or int, optional
        The number of rows to show in the grid.
        If ``None``, it will be automatically derived.

    cols : None or int, optional
        The number of cols to show in the grid.
        If ``None``, it will be automatically derived.

    Returns
    -------
    (H',W',3) ndarray
        Image of the generated grid.

    r   z-Expected to get at least one image, got none.r   zbExpected to get an array of four dimensions denoting (N, H, W, C), got %d dimensions and shape %s.z0Expected to get an iterable of ndarrays, got %s.c                 S   r   r   )rI   r  r   r   r   r,     r   zdraw_grid.<locals>.<listcomp>z6Expected to get an iterable of ndarrays, got types %s.r  c                 S   s   g | ]}t t|qS r   )r   rZ   r  r   r   r   r,     s    c                 S   s   g | ]}|j d kqS r   )r.  r  r   r   r   r,         z<Expected to get images with three dimensions. Got shapes %s.c                 S      g | ]}t |jqS r   r   r   r  r   r   r   r,     r]  c                 S   s   h | ]}|j jqS r   r^   r   r  r   r   r   r    r   zdraw_grid.<locals>.<setcomp>rb   z;Expected to get images with the same dtypes, got dtypes %s.c                 S   s   g | ]}|j jqS r   r`  r  r   r   r   r,     r   c                 S   s   h | ]}|j d  qS )r+  r   r  r   r   r   r    r]  zGExpected to get images with the same number of channels, got shapes %s.c                 S   r^  r   r_  r  r   r   r   r,     r]  c                 S      g | ]}|j d  qS r  r   r  r   r   r   r,     r]  c                 S   ra  rB  r   r  r   r   r   r,     r]  r   NzExpected rows*cols to lead to at least as many cells as there were images provided, but got %d rows, %d cols (=%d cells) for %d images. r   )r>   rI   r.  r   rT   rZ   r   r?   rU  r   mathceilsqrtr^   rF   r   r7  r8  )r:  rowscolsr;  Zcell_height
cell_widthr<  r   r   r^   gridZcell_idxZrow_idxZcol_idxr  Zcell_y1Zcell_y2Zcell_x1Zcell_x2r   r   r   	draw_grid  s   .


ri  c                 C   s   t | ||d}t| dS )aS  Combine multiple images into a single image and plot the result.

    This will show a window of the results of :func:`~imgaug.imgaug.draw_grid`.

    **Supported dtypes**:

        minimum of (
            :func:`~imgaug.imgaug.draw_grid`,
            :func:`~imgaug.imgaug.imshow`
        )

    Parameters
    ----------
    images : (N,H,W,3) ndarray or iterable of (H,W,3) array
        See :func:`~imgaug.imgaug.draw_grid`.

    rows : None or int, optional
        See :func:`~imgaug.imgaug.draw_grid`.

    cols : None or int, optional
        See :func:`~imgaug.imgaug.draw_grid`.

    )re  rf  N)ri  imshow)r:  re  rf  rh  r   r   r   	show_grid  s   rk  c           
      C   s
  |dv sJ d|f |dkrG| }| j dkr,| jd dv r,| dddf dd	d	d
f }d}t|tj t|| td t| d	S dd	lm	} d}| jd | | jd | }}t
|d}|j||f|d\}}	|jd| jf  |	j| dd |  d	S )a  Show an image in a window.

    **Supported dtypes**:

        * ``uint8``: yes; not tested
        * ``uint16``: ?
        * ``uint32``: ?
        * ``uint64``: ?
        * ``int8``: ?
        * ``int16``: ?
        * ``int32``: ?
        * ``int64``: ?
        * ``float16``: ?
        * ``float32``: ?
        * ``float64``: ?
        * ``float128``: ?
        * ``bool``: ?

    Parameters
    ----------
    image : (H,W,3) ndarray
        Image to show.

    backend : {'matplotlib', 'cv2'}, optional
        Library to use to show the image. May be either matplotlib or
        OpenCV ('cv2'). OpenCV tends to be faster, but apparently causes more
        technical issues.

    )r	   r&  z/Expected backend 'matplotlib' or 'cv2', got %s.r&  r0   r   r  .r   Nr+  zimgaug-default-window`   rb      )Zfigsizedpizimgaug.imshow(%s)gray)Zcmap)r.  r   r&  ZnamedWindowZWINDOW_NORMALrj  ZwaitKeyZdestroyWindowZmatplotlib.pyplotZpyplotrU  ZsubplotsZcanvasset_window_titleshow)
r  backendZ	image_bgrZwin_nameZpltrn  hwZfigaxr   r   r   rj    s(   


rj  Assertion failed.c                 C   s   | st t|dS )a  Assert that a ``condition`` holds or raise an ``Exception`` otherwise.

    This was added because `assert` statements are removed in optimized code.
    It replaced `assert` statements throughout the library, but that was
    reverted again for readability and performance reasons.

    Parameters
    ----------
    condition : bool
        If ``False``, an exception is raised.

    message : str, optional
        Error message.

    N)AssertionErrorr   )	conditionmessager   r   r   	do_assertN  s   rz  c                 C   s4   | j }|d st| } | j }|d st| } | S )NZOWNDATAZC_CONTIGUOUS)r   rF   r   Zascontiguousarray)rG  r   r   r   r   _normalize_cv2_input_arr_c  s   

r{  c                 C   s   t t| |S )a  Map an input image to a new one using a lookup table.

    Added in 0.4.0.

    **Supported dtypes**:

        See :func:`~imgaug.imgaug.apply_lut_`.

    Parameters
    ----------
    image : ndarray
        See :func:`~imgaug.imgaug.apply_lut_`.

    table : ndarray or list of ndarray
        See :func:`~imgaug.imgaug.apply_lut_`.

    Returns
    -------
    ndarray
        Image after mapping via lookup table.

    )
apply_lut_rF   r   )r  tabler   r   r   	apply_lutm  s   r~  c              
   C   s  | j }t|dkrdn|d }d|v r| S t| } t|tr5t||ks.J d|t|f tj|dd}|j d|fkrH|tjddddf }|j d	ks_|j dd|fks_J d
|j ||f |dkr|j d	krzt|tjddtjf dd|f}g }t	t
t|d D ](}|d }|d }|t| dddd||f |dddd||f  qtj|ddS | jjdksJ d| jjf |jjdksJ d|jjf tj| || d} | S )a  Map an input image in-place to a new one using a lookup table.

    Added in 0.4.0.

    **Supported dtypes**:

        * ``uint8``: yes; fully tested
        * ``uint16``: no
        * ``uint32``: no
        * ``uint64``: no
        * ``int8``: no
        * ``int16``: no
        * ``int32``: no
        * ``int64``: no
        * ``float16``: no
        * ``float32``: no
        * ``float64``: no
        * ``float128``: no
        * ``bool``: no

    Parameters
    ----------
    image : ndarray
        Image of dtype ``uint8`` and shape ``(H,W)`` or ``(H,W,C)``.

    table : ndarray or list of ndarray
        Table of dtype ``uint8`` containing the mapping from old to new
        values. Either a ``list`` of ``C`` ``(256,)`` arrays or a single
        array of shape ``(256,)`` or ``(256, C)`` or ``(1, 256, C)``.
        In case of ``(256,)`` the same table is used for all channels,
        otherwise a channelwise table is used and ``C`` is expected to match
        the number of channels.

    Returns
    -------
    ndarray
        Image after mapping via lookup table.
        This *might* be the same array instance as provided via `image`.

    r   rb   r+  r   z<Expected to get %d tables (one per channel), got %d instead.r,     N)r  zExpected 'table' to be any of the following: A list of C (256,) arrays, an array of shape (256,), an array of shape (256, C), an array of shape (1, 256, C). Transformed 'table' up to shape %s for image with shape %s (C=%d).r%  r   z#Expected uint8 image, got dtype %s.z#Expected uint8 table, got dtype %s.)dst)r   r>   r{  rE   rj   rF   r9  r  ZtileZaranger   rc  r   r|  Zconcatenater^   r   r&  ZLUT)r  r}  Zimage_shape_origr<  ZsublutsZ	group_idxZc_startZc_endr   r   r   r|    sR   *

r|  c                   @   s>   e Zd ZdZ		dddZdd Zdd Zd	d
 Zdd ZdS )HooksImagesa  Class to intervene with image augmentation runs.

    This is e.g. useful to dynamically deactivate some augmenters.

    Parameters
    ----------
    activator : None or callable, optional
        A function that gives permission to execute an augmenter.
        The expected interface is::

            ``f(images, augmenter, parents, default)``

        where ``images`` are the input images to augment, ``augmenter`` is the
        instance of the augmenter to execute, ``parents`` are previously
        executed augmenters and ``default`` is an expected default value to be
        returned if the activator function does not plan to make a decision
        for the given inputs.

    propagator : None or callable, optional
        A function that gives permission to propagate the augmentation further
        to the children of an augmenter. This happens after the activator.
        In theory, an augmenter may augment images itself (if allowed by the
        activator) and then execute child augmenters afterwards (if allowed by
        the propagator). If the activator returned ``False``, the propagation
        step will never be executed.
        The expected interface is::

            ``f(images, augmenter, parents, default)``

        with all arguments having identical meaning to the activator.

    preprocessor : None or callable, optional
        A function to call before an augmenter performed any augmentations.
        The interface is:

            ``f(images, augmenter, parents)``

        with all arguments having identical meaning to the activator.
        It is expected to return the input images, optionally modified.

    postprocessor : None or callable, optional
        A function to call after an augmenter performed augmentations.
        The interface is the same as for the `preprocessor`.

    Examples
    --------
    >>> import numpy as np
    >>> import imgaug as ia
    >>> import imgaug.augmenters as iaa
    >>> seq = iaa.Sequential([
    >>>     iaa.GaussianBlur(3.0, name="blur"),
    >>>     iaa.Dropout(0.05, name="dropout"),
    >>>     iaa.Affine(translate_px=-5, name="affine")
    >>> ])
    >>> images = [np.zeros((10, 10), dtype=np.uint8)]
    >>>
    >>> def activator(images, augmenter, parents, default):
    >>>     return False if augmenter.name in ["blur", "dropout"] else default
    >>>
    >>> seq_det = seq.to_deterministic()
    >>> images_aug = seq_det.augment_images(images)
    >>> heatmaps = [np.random.rand(*(3, 10, 10))]
    >>> heatmaps_aug = seq_det.augment_images(
    >>>     heatmaps,
    >>>     hooks=ia.HooksImages(activator=activator)
    >>> )

    This augments images and their respective heatmaps in the same way.
    The heatmaps however are only modified by ``Affine``, not by
    ``GaussianBlur`` or ``Dropout``.

    Nc                 C   r!   r"   )	activator
propagatorpreprocessorpostprocessor)r'   r  r  r  r  r   r   r   r(   .	  r)   zHooksImages.__init__c                 C      | j du r|S |  ||||S )a  Estimate whether an augmenter may be executed.

        This also affects propagation of data to child augmenters.

        Returns
        -------
        bool
            If ``True``, the augmenter may be executed.
            Otherwise ``False``.

        N)r  r'   r:  r$  parentsdefaultr   r   r   is_activated5	  s   
zHooksImages.is_activatedc                 C   r  )a  Estimate whether an augmenter may call its children.

        This function decides whether an augmenter with children is allowed
        to call these in order to further augment the inputs.
        Note that if the augmenter itself performs augmentations (before/after
        calling its children), these may still be executed, even if this
        method returns ``False``.

        Returns
        -------
        bool
            If ``True``, the augmenter may propagate data to its children.
            Otherwise ``False``.

        N)r  r  r   r   r   is_propagatingE	  s   
zHooksImages.is_propagatingc                 C      | j du r|S |  |||S )zPreprocess input data per augmenter before augmentation.

        Returns
        -------
        (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
            The input images, optionally modified.

        N)r  r'   r:  r$  r  r   r   r   
preprocessY	     
	zHooksImages.preprocessc                 C   r  )zPostprocess input data per augmenter after augmentation.

        Returns
        -------
        (N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
            The input images, optionally modified.

        N)r  r  r   r   r   postprocessf	  r  zHooksImages.postprocess)NNNN)	r   r   r   r   r(   r  r  r  r  r   r   r   r   r    s    I
r  c                   @   r   )HooksHeatmapszClass to intervene with heatmap augmentation runs.

    This is e.g. useful to dynamically deactivate some augmenters.

    This class is currently the same as the one for images. This may or may
    not change in the future.

    Nr   r   r   r   r   r  t	  r   r  c                   @   r   )HooksKeypointszClass to intervene with keypoint augmentation runs.

    This is e.g. useful to dynamically deactivate some augmenters.

    This class is currently the same as the one for images. This may or may
    not change in the future.

    Nr   r   r   r   r   r  	  r   r  c                    s$    d ur n  fdd}|S )Nc                     s8   dd l }td f  |}t| | i |S )Nr   z8Using imgaug.imgaug.%s is deprecated. Use %s.%s instead.)	importlibr   import_modulegetattr)r8   r9   r  moduleclass_name_newclass_name_oldmodule_name_newr   r   _func	  s   
z,_mark_moved_class_or_function.<locals>._funcr   )r  r  r  r  r   r  r   _mark_moved_class_or_function	  s   	r  ))r   imgaug.augmentables.kpsN)r   r  N)r   imgaug.augmentables.bbsN)r   r  N)r   imgaug.augmentables.polysN)r   r  N)ZMultiPolygonr  N)Z_ConcavePolygonRecovererr  N)r   zimgaug.augmentables.heatmapsN)r   zimgaug.augmentables.segmapsN)ZBatchzimgaug.augmentables.batchesN)ZBatchLoaderimgaug.multicoreN)ZBackgroundAugmenterr  N)Zcompute_geometric_medianr  N)Z&_convert_points_to_shapely_line_stringr  N)Z_interpolate_point_pairr  N)Z_interpolate_pointsr  N)Z#_interpolate_points_by_max_distancer  N)padimgaug.augmenters.sizeN)Zpad_to_aspect_ratior  N)rE  r  N)Z!compute_paddings_for_aspect_ratior  Z&compute_paddings_to_reach_aspect_ratio)Z&compute_paddings_to_reach_multiples_ofr  N)Z&compute_paddings_to_reach_exponents_ofr  N)r   )NN)NF)FrB  r"   )r   r   )rA  r   TN)rM  rN  TN)rT  r   TN)rT  r   T)rM  rN  T)rv  )sr   
__future__r   r   r   rb  rL   rc   osr   rg   r@   collections.abcr   ImportErrorcollectionsnumpyrF   r&  r   rU   Z	six.movesZmovesr7  Zskimage.drawr   Zskimage.measurer   pathdirnameabspath__file__ZFILE_DIRr?   r   r   r   r   setZsctypesZNP_FLOAT_TYPESZNP_INT_TYPESZNP_UINT_TYPESZIMSHOW_BACKEND_DEFAULTr3  r2  r1  r4  r0  Warningr   UserWarningr   r   objectr    rI   rK   rO   rR   rS   rT   rW   r[   r`   ra   rf   ri   rl   rr   ru   rz   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r?  r   rL  rR  rV  r[  r\  ri  rk  rj  rz  r{  r~  r|  r  r  r  r  MOVEDr  r  r  localsr   r   r   r   <module>   s    			
\
,




8
K
,

(
3
.
53*
D
Z  
'
~
/
/
,

,
k
=
[ 