o
    &Õj=N  ã                   @   sÄ   d Z ddlmZmZmZ ddlmZmZ ddlZ	ddl
Z
ddlZddlZddlmZ ddlmZ ddlmZ d	d
lmZ d	dlmZ e e¡G dd„ deƒƒZG dd„ deƒZG dd„ dejƒZdS )zû
Augmenters that deal with edge detection.

List of augmenters:

    * :class:`Canny`

:class:`~imgaug.augmenters.convolutional.EdgeDetect` and
:class:`~imgaug.augmenters.convolutional.DirectedEdgeDetect` are currently
still in ``convolutional.py``.

é    )Úprint_functionÚdivisionÚabsolute_import)ÚABCMetaÚabstractmethodN)Ú_normalize_cv2_input_arr_é   )Úmeta)Úblendé   )Ú
parameters)Údtypesc                   @   s   e Zd ZdZedd„ ƒZdS )ÚIBinaryImageColorizerz@Interface for classes that convert binary masks to color images.c                 C   s   dS )aè  
        Convert a binary image to a colorized one.

        Parameters
        ----------
        image_binary : ndarray
            Boolean ``(H,W)`` image.

        image_original : ndarray
            Original ``(H,W,C)`` input image.

        nth_image : int
            Index of the image in the batch.

        random_state : imgaug.random.RNG
            Random state to use.

        Returns
        -------
        ndarray
            Colorized form of `image_binary`.

        N© )ÚselfÚimage_binaryÚimage_originalÚ	nth_imageÚrandom_stater   r   úX/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/imgaug/augmenters/edges.pyÚcolorize#   s    zIBinaryImageColorizer.colorizeN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r      s    r   c                   @   s2   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ ZdS )Ú RandomColorsBinaryImageColorizera=  
    Colorizer using two randomly sampled foreground/background colors.

    Parameters
    ----------
    color_true : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
        Color of the foreground, i.e. all pixels in binary images that are
        ``True``. This parameter will be queried once per image to
        generate ``(3,)`` samples denoting the color. (Note that even for
        grayscale images three values will be sampled and converted to
        grayscale according to ``0.299*R + 0.587*G + 0.114*B``. This is the
        same equation that is also used by OpenCV.)

            * If an int, exactly that value will always be used, i.e. every
              color will be ``(v, v, v)`` for value ``v``.
            * If a tuple ``(a, b)``, three random values from the range
              ``a <= x <= b`` will be sampled per image.
            * If a list, then three random values will be sampled from that
              list per image.
            * If a StochasticParameter, three values will be sampled from the
              parameter per image.

    color_false : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
        Analogous to `color_true`, but denotes the color for all pixels that
        are ``False`` in the binary input image.

    ©r   éÿ   c                 C   s4   t j|dddddd| _t j|dddddd| _d S )NÚ
color_truer   TF©Úvalue_rangeÚtuple_to_uniformÚlist_to_choiceZallow_floatsÚcolor_false)ÚiapÚhandle_discrete_paramr   r#   )r   r   r#   r   r   r   Ú__init__\   s    úúz)RandomColorsBinaryImageColorizer.__init__c                 C   s(   | j jd|d}| jjd|d}||fS )N)é   )r   )r   Údraw_samplesr#   )r   r   r   r#   r   r   r   Ú_draw_samplesm   s   ÿÿz.RandomColorsBinaryImageColorizer._draw_samplesc           	      C   st  |j dksJ d|j f ƒ‚|jjdksJ d|jjf ƒ‚|j dks)J d|j f ƒ‚|jd dv s:J d	|jd f ƒ‚|jjd
ksHJ d|jj ƒ‚|  |¡\}}t|jd dƒ}tj|jd |jd |f|jd}|dkr–d|d  d|d   d|d   ||< d|d  d|d   d|d   || < n	|||< ||| < |jd dkr¸t 	||d d …d d …dd…f g¡}|S )Nr   zIExpected binary image to colorize to be 2-dimensional, got %d dimensions.ÚbzCExpected binary image to colorize to be boolean, got dtype kind %s.r'   z?Expected original image to be 3-dimensional, got %d dimensions.éÿÿÿÿ©r   r'   é   zDExpected original image to have 1, 3 or 4 channels. Got %d channels.Úuint8z:Expected original image to have dtype uint8, got dtype %s.r   r   )Údtypeg‰A`åÐ"Ó?gbX9´Èâ?gÉv¾Ÿ/½?r-   )
Úndimr/   ÚkindÚshapeÚnamer)   ÚminÚnpZzerosZdstack)	r   r   r   r   r   r   r#   Znb_channelsZimage_colorizedr   r   r   r   t   sf   ÿÿÿÿÿÿ
ÿÿÿÿþ

ÿ
þÿ

ÿ
þ
ÿ
ÿz)RandomColorsBinaryImageColorizer.colorizec                 C   s   d| j | jf S )Nz?RandomColorsBinaryImageColorizer(color_true=%s, color_false=%s))r   r#   ©r   r   r   r   Ú__str__¡   s   ÿÿz(RandomColorsBinaryImageColorizer.__str__N)r   r   )r   r   r   r   r&   r)   r   r7   r   r   r   r   r   ?   s    
-r   c                       sN   e Zd ZdZ						d‡ fdd„	Zd	d
„ Zdd„ Zdd„ Zdd„ Z‡  Z	S )ÚCannyaŠ  
    Apply a canny edge detector to input images.

    **Supported dtypes**:

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

    Parameters
    ----------
    alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
        Blending factor to use in alpha blending.
        A value close to 1.0 means that only the edge image is visible.
        A value close to 0.0 means that only the original image is visible.
        A value close to 0.5 means that the images are merged according to
        `0.5*image + 0.5*edge_image`.
        If a sample from this parameter is 0, no action will be performed for
        the corresponding image.

            * If an int or float, exactly that value will be used.
            * If a tuple ``(a, b)``, a random value from the range
              ``a <= x <= b`` will be sampled per image.
            * If a list, then a random value will be sampled from that list
              per image.
            * If a StochasticParameter, a value will be sampled from the
              parameter per image.

    hysteresis_thresholds : number or tuple of number or list of number or imgaug.parameters.StochasticParameter or tuple of tuple of number or tuple of list of number or tuple of imgaug.parameters.StochasticParameter, optional
        Min and max values to use in hysteresis thresholding.
        (This parameter seems to have not very much effect on the results.)
        Either a single parameter or a tuple of two parameters.
        If a single parameter is provided, the sampling happens once for all
        images with `(N,2)` samples being requested from the parameter,
        where each first value denotes the hysteresis minimum and each second
        the maximum.
        If a tuple of two parameters is provided, one sampling of `(N,)` values
        is independently performed per parameter (first parameter: hysteresis
        minimum, second: hysteresis maximum).

            * If this is a single number, both min and max value will always be
              exactly that value.
            * If this is a tuple of numbers ``(a, b)``, two random values from
              the range ``a <= x <= b`` will be sampled per image.
            * If this is a list, two random values will be sampled from that
              list per image.
            * If this is a StochasticParameter, two random values will be
              sampled from that parameter per image.
            * If this is a tuple ``(min, max)`` with ``min`` and ``max``
              both *not* being numbers, they will be treated according to the
              rules above (i.e. may be a number, tuple, list or
              StochasticParameter). A single value will be sampled per image
              and parameter.

    sobel_kernel_size : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
        Kernel size of the sobel operator initially applied to each image.
        This corresponds to ``apertureSize`` in ``cv2.Canny()``.
        If a sample from this parameter is ``<=1``, no action will be performed
        for the corresponding image.
        The maximum for this parameter is ``7`` (inclusive). Higher values are
        not accepted by OpenCV.
        If an even value ``v`` is sampled, it is automatically changed to
        ``v-1``.

            * If this is a single integer, the kernel size always matches that
              value.
            * If this is a tuple of integers ``(a, b)``, a random discrete
              value will be sampled from the range ``a <= x <= b`` per image.
            * If this is a list, a random value will be sampled from that
              list per image.
            * If this is a StochasticParameter, a random value will be sampled
              from that parameter per image.

    colorizer : None or imgaug.augmenters.edges.IBinaryImageColorizer, optional
        A strategy to convert binary edge images to color images.
        If this is ``None``, an instance of ``RandomColorBinaryImageColorizer``
        is created, which means that each edge image is converted into an
        ``uint8`` image, where edge and non-edge pixels each have a different
        color that was uniformly randomly sampled from the space of all
        ``uint8`` colors.

    seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
        See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.

    name : None or str, optional
        See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.

    random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
        Old name for parameter `seed`.
        Its usage will not yet cause a deprecation warning,
        but it is still recommended to use `seed` now.
        Outdated since 0.4.0.

    deterministic : bool, optional
        Deprecated since 0.4.0.
        See method ``to_deterministic()`` for an alternative and for
        details about what the "deterministic mode" actually does.

    Examples
    --------
    >>> import imgaug.augmenters as iaa
    >>> aug = iaa.Canny()

    Create an augmenter that generates random blends between images and
    their canny edge representations.

    >>> aug = iaa.Canny(alpha=(0.0, 0.5))

    Create a canny edge augmenter that generates edge images with a blending
    factor of max ``50%``, i.e. the original (non-edge) image is always at
    least partially visible.

    >>> aug = iaa.Canny(
    >>>     alpha=(0.0, 0.5),
    >>>     colorizer=iaa.RandomColorsBinaryImageColorizer(
    >>>         color_true=255,
    >>>         color_false=0
    >>>     )
    >>> )

    Same as in the previous example, but the edge image always uses the
    color white for edges and black for the background.

    >>> aug = iaa.Canny(alpha=(0.5, 1.0), sobel_kernel_size=[3, 7])

    Create a canny edge augmenter that initially preprocesses images using
    a sobel filter with kernel size of either ``3x3`` or ``13x13`` and
    alpha-blends with result using a strength of ``50%`` (both images
    equally visible) to ``100%`` (only edge image visible).

    >>> aug = iaa.Alpha(
    >>>     (0.0, 1.0),
    >>>     iaa.Canny(alpha=1),
    >>>     iaa.MedianBlur(13)
    >>> )

    Create an augmenter that blends a canny edge image with a median-blurred
    version of the input image. The median blur uses a fixed kernel size
    of ``13x13`` pixels.

    ©g        ç      ð?©)é<   éŒ   )é    éð   ©r'   é   NÚ
deprecatedc	           	   	      sæ   t t| ƒj||||d tj|ddddd| _t|tƒrLt|ƒdkrLt	 
|d ¡sLt	 
|d ¡sLtj|d d	d
ddddtj|d dd
ddddf| _ntj|dd
dddd| _tj|dddddd| _|d urm|| _d S tƒ | _d S )N)Úseedr3   r   ÚdeterministicÚalpha)r   r:   T)r    r!   r"   r   r   r   zhysteresis_thresholds[0]r   r   zhysteresis_thresholds[1]Úhysteresis_thresholdsÚsobel_kernel_size)r   rA   F)Úsuperr8   r&   r$   Zhandle_continuous_paramrE   Ú
isinstanceÚtupleÚlenÚiaZis_single_numberr%   rF   rG   r   Ú	colorizer)	r   rE   rF   rG   rM   rC   r3   r   rD   ©Ú	__class__r   r   r&   @  sh   
þþ
ÿþúúøúú
ÿÿýzCanny.__init__c                 C   sJ  t |ƒ}| d¡}| j |f|d ¡}| j}t|tƒr;|d  |f|d ¡}|d  |f|d ¡}tj||gdd}	n
| |df|d ¡}	| j	 |f|d ¡}
|	d d …df |	d d …df k}t 
|¡rz|	|d d …f d d …ddgf |	|d d …f< t 
|
dk ¡r…J dƒ‚t 
|
d	k¡rJ d
ƒ‚t |
d¡dk}|
|  d8  < ||	|
fS )Nr-   r   r   r   r+   )Zaxisr'   zLSampled a sobel kernel size below 0 in Canny. Allowed value range is 0 to 7.rA   zLSampled a sobel kernel size above 7 in Canny. Allowed value range is 0 to 7.)rK   Ú	duplicaterE   r(   rF   rI   rJ   r5   ÚstackrG   ÚanyÚmod)r   Zaugmentablesr   Z	nb_imagesÚrssÚalpha_samplesZhthreshZ
min_valuesZ
max_valuesÚhthresh_samplesÚsobel_samplesÚinvalidZeven_idxr   r   r   r)   }  s0   


ÿ 
,ÿÿ
zCanny._draw_samplesc                 C   s@  |j d u r|S |j }tj|dgg d¢| d | t|ƒ¡}|  ||d ¡}|d }|d }	|d }
tt|||	|
ƒƒ}|D ]a\}\}}}}|jd dv sUJ d	|jd f ƒ‚d|jdd… v }|dkr|dkr|st	j
t|d d …d d …dd
…f ƒ|d |d |dd}|dk}| jj||||| d}t |||¡|j |< q<|S )Nr.   )ÚboolZuint16Zuint32Zuint64Zuint128Zuint256Zint8Zint16Zint32Zint64Zint128Zint256Zfloat32Zfloat64Zfloat96Zfloat128Zfloat256)ÚallowedZ
disallowedZ	augmenterr+   r   r   r   r,   zeCanny edge detector can currently only handle images with channel numbers that are 1, 3 or 4. Got %d.r'   T)Z
threshold1Z
threshold2ZapertureSizeZ
L2gradient)r   r   )ÚimagesÚiadtZgate_dtypesrP   rK   r)   Ú	enumerateÚzipr2   Úcv2r8   r   rM   r   r
   Zblend_alpha)r   Úbatchr   ÚparentsÚhooksr[   rT   ZsamplesrU   rV   rW   ÚgenÚiÚimagerE   ZhthreshsZsobelZhas_zero_sized_axesZimage_cannyZimage_canny_colorr   r   r   Ú_augment_batch_¢  sP   
ö
ÿÿþûÿ
ÿ€zCanny._augment_batch_c                 C   s   | j | j| j| jgS )z=See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`.)rE   rF   rG   rM   r6   r   r   r   Úget_parametersÖ  s   ÿzCanny.get_parametersc                 C   s    d| j | j| j| j| j| jf S )NzhCanny(alpha=%s, hysteresis_thresholds=%s, sobel_kernel_size=%s, colorizer=%s, name=%s, deterministic=%s))rE   rF   rG   rM   r3   rD   r6   r   r   r   r7   Û  s   ýúzCanny.__str__)r9   r;   r@   NNNrB   rB   )
r   r   r   r   r&   r)   rf   rg   r7   Ú__classcell__r   r   rN   r   r8   §   s     ú=%4r8   )r   Ú
__future__r   r   r   Úabcr   r   Únumpyr5   r_   ÚsixZimgaugrL   Zimgaug.imgaugr   Ú r	   r
   r   r$   r   r\   Zadd_metaclassÚobjectr   r   Z	Augmenterr8   r   r   r   r   Ú<module>   s     h