o
    e}V                     @   sz   d Z ddlmZmZm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 ejd	d
ddd ZG dd	 d	eZdS )z^Classes dealing with segmentation maps.

E.g. masks, semantic or instance segmentation maps.

    )print_functiondivisionabsolute_importN   )imgaug)blend   )IAugmentableSegmentationMapsOnImagez.(Note the plural 'Maps' instead of old 'Map'.)alt_funccommentc                  O   s   t | i |S )z@Object representing a segmentation map associated with an image.)r
   )argskwargs r   KD:\Projects\ConvertPro\env\Lib\site-packages\imgaug/augmentables/segmaps.pySegmentationMapOnImage   s   r   c                   @   s   e Zd ZdZg dZd%ddZdd Zejdd	d
d Z	d&ddZ
			d'ddZd(ddZ		d)ddZejddddd Zd*dd Zd&d!d"Zd&d#d$ZdS )+r
   a  
    Object representing a segmentation map associated with an image.

    Attributes
    ----------
    DEFAULT_SEGMENT_COLORS : list of tuple of int
        Standard RGB colors to use during drawing, ordered by class index.

    Parameters
    ----------
    arr : (H,W) ndarray or (H,W,C) ndarray
        Array representing the segmentation map(s). May have dtypes bool,
        int or uint.

    shape : tuple of int
        Shape of the image on which the segmentation map(s) is/are placed.
        **Not** the shape of the segmentation map(s) array, unless it is
        identical to the image shape (note the likely difference between the
        arrays in the number of channels).
        This is expected to be ``(H, W)`` or ``(H, W, C)`` with ``C`` usually
        being ``3``.
        If there is no corresponding image, use ``(H_arr, W_arr)`` instead,
        where ``H_arr`` is the height of the segmentation map(s) array
        (analogous ``W_arr``).

    nb_classes : None or int, optional
        Deprecated.

    )*)r   r   r   )      K   )<      r   )      r   )r         )   r   0   )      r   )F      r!   )r!   2   r   )   r   r   )      r%   )r      r&   )r   r%   r   )   n   (   )r   r$   r   )r&   r   r   )r'   r      )r&   r&   r   )r      r   )r   r   r&   )r&   r&   r&   )r   r   r   )s      %   )r   Z   r.   )   p   r-   )r   A   d   )z   r2      )H      r/   )#   x   r9   )r9   r   r,   )i   r4   r   )}   _   r<   )r   @   r=   )r,   r<   r0   )U   7      )r0   r;   r3   )r=   r   r   )r>   r0   a   )r=   r=   r   )r0   k   r/   )r   r   r=   )r=   r=   r=   Nc                 C   s  t |sJ dt|f |jdv sJ d|j|jf t|ts*J dt| |jjdkrJt 	d |jdkr?|dk}nt
j|dd	t
j}|jjd
krd|j|jf| _|jdkrc|dt
jf }nd|jjdv rt
|jdd dksJ dt
|f |jjdkr|jjdksJ d|jjf n|jjdkr|jjdksJ d|jjf |j|jf| _|jdkr|dt
jf }n	td|jjf |jjdkr|t
j}|| _|| _|d urt 	d d S d S )Nz$Expected to get numpy array, got %s.)r      zZExpected segmentation map array to be 2- or 3-dimensional, got %d dimensions and shape %s.z|Expected 'shape' to be a tuple denoting the shape of the image on which the segmentation map is placed. Got type %s instead.fzGot a float array as the segmentation map in SegmentationMapsOnImage. That is deprecated. Please provide instead a (H,W,[C]) array of dtype bool_, int or uint, where C denotes the segmentation map index.r   g      ?)Zaxisbool.)iur   r3   zPExpected segmentation map array to only contain values >=0, got a minimum of %d.rG   z]When using uint arrays as segmentation maps, only uint8 and uint16 are allowed. Got dtype %s.rF      zaWhen using int arrays as segmentation maps, only int8, int16 and int32 are allowed. Got dtype %s.zSInput was expected to be an array of dtype 'bool', 'int' or 'uint'. Got dtype '%s'.int32zProviding nb_classes to SegmentationMapsOnImage is no longer necessary and hence deprecated. The argument is ignored and can be safely removed.)iaZis_np_arraytypendimshape
isinstancetupledtypekindwarn_deprecatednpZargmaxastyperI   name
_input_wasZnewaxisminZflatitemsize	Exceptionarr)selfrZ   rM   
nb_classesr   r   r   __init__f   s|   




z SegmentationMapsOnImage.__init__c                 C   sV   | j \}}| j|}|dkr)|jd dksJ d|jf |dddddf S |S )a  Return the seg.map array, with original dtype and shape ndim.

        Here, "original" denotes the dtype and number of shape dimensions that
        was used when the :class:`SegmentationMapsOnImage` instance was
        created, i.e. upon the call of
        :func:`SegmentationMapsOnImage.__init__`.
        Internally, this class may use a different dtype and shape to simplify
        computations.

        .. note::

            The height and width may have changed compared to the original
            input due to e.g. pooling operations.

        Returns
        -------
        ndarray
            Segmentation map array.
            Same dtype and number of dimensions as was originally used when
            the :class:`SegmentationMapsOnImage` instance was created.

        r   r   zOriginally got a (H,W) segmentation map. Internal array should now have shape (H,W,1), but got %s. This might be an internal error.Nr   )rV   rZ   rT   rM   )r[   Zinput_dtypeZ
input_ndimZ	arr_inputr   r   r   get_arr   s   
zSegmentationMapsOnImage.get_arrz!SegmentationMapsOnImage.get_arr())r   c                 O   s   |   S )z=Return the seg.map array, with original dtype and shape ndim.)r^   r[   r   r   r   r   r   get_arr_int   s   z#SegmentationMapsOnImage.get_arr_intc                 C   s   dd }|du r||g}n	t |s||g}||d | jjd }||d | jjd }tj||dftjd}| j|dd	|d
dS )a&  
        Render the segmentation map as an RGB image.

        Parameters
        ----------
        size : None or float or iterable of int or iterable of float, optional
            Size of the rendered RGB image as ``(height, width)``.
            See :func:`~imgaug.imgaug.imresize_single_image` for details.
            If set to ``None``, no resizing is performed and the size of the
            segmentation map array is used.

        colors : None or list of tuple of int, optional
            Colors to use. One for each class to draw.
            If ``None``, then default colors will be used.

        Returns
        -------
        list of (H,W,3) ndarray
            Rendered segmentation map (dtype is ``uint8``).
            One per ``C`` in the original input array ``(H,W,C)``.

        c                 S   sH   | d u r|S t | rtt||  dS t | r| S tdt| f )Nr   zExpected float or int, got %s.)rJ   Zis_single_floatmaxintZis_single_integer
ValueErrorrK   )ZsizevalZarr_axis_sizer   r   r   _handle_sizeval   s   

z5SegmentationMapsOnImage.draw.<locals>._handle_sizevalNr   r   rC   rP   g      ?segmentation_mapT)alpharesizecolorsdraw_background)rJ   is_iterablerZ   rM   rS   zerosuint8draw_on_image)r[   sizeri   rd   heightwidthimager   r   r   draw   s   


zSegmentationMapsOnImage.draw      ?rf   Fr   c                 C   s  |dur	t d |jdksJ d|jf |jd dks'J d|jd f |jjdks6J d|jjf d	|  kr@d
ksHn J d|f |dv sSJ d|f |durY|ntj}|dkrnt j|| j	jdd dd}g }t
| j	| j	jd }	|	D ]}
|
dddddf }
dt
|
 }t
j|
jd |
jd dft
jd}|t|ksJ d|t|f t
|
}tt||D ]\}}||v r|
|k}|||< qt j||jdd dd}t|||}|r|}nt j|
|k|jdd dd}t
|}| | ||  }|| q}|S )a   Draw the segmentation map as an overlay over an image.

        Parameters
        ----------
        image : (H,W,3) ndarray
            Image onto which to draw the segmentation map. Expected dtype
            is ``uint8``.

        alpha : float, optional
            Alpha/opacity value to use for the mixing of image and
            segmentation map. Larger values mean that the segmentation map
            will be more visible and the image less visible.

        resize : {'segmentation_map', 'image'}, optional
            In case of size differences between the image and segmentation
            map, either the image or the segmentation map can be resized.
            This parameter controls which of the two will be resized to the
            other's size.

        colors : None or list of tuple of int, optional
            Colors to use. One for each class to draw.
            If ``None``, then default colors will be used.

        draw_background : bool, optional
            If ``True``, the background will be drawn like any other class.
            If ``False``, the background will not be drawn, i.e. the respective
            background pixels will be identical with the image's RGB color at
            the corresponding spatial location and no color overlay will be
            applied.

        background_class_id : int, optional
            Class id to interpret as the background class.
            See `draw_background`.

        background_threshold : None, optional
            Deprecated.
            This parameter is ignored.

        Returns
        -------
        list of (H,W,3) ndarray
            Rendered overlays as ``uint8`` arrays.
            Always a **list** containing one RGB image per segmentation map
            array channel.

        Nz[The argument `background_threshold` is deprecated and ignored. Please don't use it anymore.rC   zFExpected to draw on 3-dimensional image, got image with %d dimensions.r   zBExpected to draw on RGB image, got image with %d channels instead.rm   z5Expected to get image with dtype uint8, got dtype %s.g:0yEg1  ?z8Expected 'alpha' to be in interval [0.0, 1.0], got %.4f.)rf   rr   z>Expected 'resize' to be "segmentation_map" or "image", got %s.rr   r   Zcubicinterpolationr   re   zWCan't draw all %d classes as it would exceed the maximum number of %d available colors.nearest)rJ   rR   rL   rM   rP   rU   r
   DEFAULT_SEGMENT_COLORSimresize_single_imagerZ   rS   Zdsplitra   rl   rm   lenuniquezipsmxrangeblendlibZblend_alphaZ
atleast_3dappend)r[   rr   rg   rh   ri   rj   Zbackground_class_idZbackground_thresholdZsegmaps_drawnZarr_channelwiserZ   r\   Zsegmap_drawnZ
ids_in_mapccolorZ
class_maskZsegmap_on_imageZmixZforeground_maskr   r   r   rn     s   1




z%SegmentationMapsOnImage.draw_on_imageconstantc           	   	   C   s2   ddl m} |j| j||||||d}| j|dS )a  Pad the segmentation maps at their top/right/bottom/left side.

        Parameters
        ----------
        top : int, optional
            Amount of pixels to add at the top side of the segmentation map.
            Must be ``0`` or greater.

        right : int, optional
            Amount of pixels to add at the right side of the segmentation map.
            Must be ``0`` or greater.

        bottom : int, optional
            Amount of pixels to add at the bottom side of the segmentation map.
            Must be ``0`` or greater.

        left : int, optional
            Amount of pixels to add at the left side of the segmentation map.
            Must be ``0`` or greater.

        mode : str, optional
            Padding mode to use. See :func:`~imgaug.imgaug.pad` for details.

        cval : number, optional
            Value to use for padding if `mode` is ``constant``.
            See :func:`~imgaug.imgaug.pad` for details.

        Returns
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Padded segmentation map with height ``H'=H+top+bottom`` and
            width ``W'=W+left+right``.

        r   ro   )toprightbottomleftmodecvalrZ   )
augmentersro   padrZ   deepcopy)	r[   r   r   r   r   r   r   iasize
arr_paddedr   r   r   r     s
   #zSegmentationMapsOnImage.padc           	      C   sB   ddl m} |j| j|||dd\}}| j|d}|r||fS |S )a  Pad the segmentation maps until they match a target aspect ratio.

        Depending on which dimension is smaller (height or width), only the
        corresponding sides (left/right or top/bottom) will be padded. In
        each case, both of the sides will be padded equally.

        Parameters
        ----------
        aspect_ratio : float
            Target aspect ratio, given as width/height. E.g. ``2.0`` denotes
            the image having twice as much width as height.

        mode : str, optional
            Padding mode to use.
            See :func:`~imgaug.imgaug.pad` for details.

        cval : number, optional
            Value to use for padding if `mode` is ``constant``.
            See :func:`~imgaug.imgaug.pad` for details.

        return_pad_amounts : bool, optional
            If ``False``, then only the padded instance will be returned.
            If ``True``, a tuple with two entries will be returned, where
            the first entry is the padded instance and the second entry are
            the amounts by which each array side was padded. These amounts are
            again a tuple of the form ``(top, right, bottom, left)``, with
            each value being an integer.

        Returns
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Padded segmentation map as :class:`SegmentationMapsOnImage`
            instance.

        tuple of int
            Amounts by which the instance's array was padded on each side,
            given as a tuple ``(top, right, bottom, left)``.
            This tuple is only returned if `return_pad_amounts` was set to
            ``True``.

        r   r   T)aspect_ratior   r   return_pad_amountsr   )r   ro   pad_to_aspect_ratiorZ   r   )	r[   r   r   r   r   r   r   Zpad_amountssegmapr   r   r   r     s   +
z+SegmentationMapsOnImage.pad_to_aspect_ratioz SegmentationMapsOnImage.resize()z(resize() has the exactly same interface.r   c                 O   s   | j |i |S )zBResize the seg.map(s) array given a target size and interpolation.)rh   r_   r   r   r   scale  s   zSegmentationMapsOnImage.scalerw   c                 C   s   t j| j||d}| |S )a  Resize the seg.map(s) array given a target size and interpolation.

        Parameters
        ----------
        sizes : float or iterable of int or iterable of float
            New size of the array in ``(height, width)``.
            See :func:`~imgaug.imgaug.imresize_single_image` for details.

        interpolation : None or str or int, optional
            The interpolation to use during resize.
            Nearest neighbour interpolation (``"nearest"``) is almost always
            the best choice.
            See :func:`~imgaug.imgaug.imresize_single_image` for details.

        Returns
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Resized segmentation map object.

        ru   )rJ   ry   rZ   r   )r[   sizesrv   Zarr_resizedr   r   r   rh     s   

zSegmentationMapsOnImage.resizec                 C   s4   t |du r| jn||du r| jn|d}| j|_|S )a~  Create a shallow copy of the segmentation map object.

        Parameters
        ----------
        arr : None or (H,W) ndarray or (H,W,C) ndarray, optional
            Optionally the `arr` attribute to use for the new segmentation map
            instance. Will be copied from the old instance if not provided.
            See
            :func:`~imgaug.augmentables.segmaps.SegmentationMapsOnImage.__init__`
            for details.

        shape : None or tuple of int, optional
            Optionally the shape attribute to use for the the new segmentation
            map instance. Will be copied from the old instance if not provided.
            See
            :func:`~imgaug.augmentables.segmaps.SegmentationMapsOnImage.__init__`
            for details.

        Returns
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Shallow copy.

        NrM   )r
   rZ   rM   rV   r[   rZ   rM   r   r   r   r   copy  s   zSegmentationMapsOnImage.copyc                 C   s:   t t|du r
| jn||du r| jn|d}| j|_|S )ax  Create a deep copy of the segmentation map object.

        Parameters
        ----------
        arr : None or (H,W) ndarray or (H,W,C) ndarray, optional
            Optionally the `arr` attribute to use for the new segmentation map
            instance. Will be copied from the old instance if not provided.
            See
            :func:`~imgaug.augmentables.segmaps.SegmentationMapsOnImage.__init__`
            for details.

        shape : None or tuple of int, optional
            Optionally the shape attribute to use for the the new segmentation
            map instance. Will be copied from the old instance if not provided.
            See
            :func:`~imgaug.augmentables.segmaps.SegmentationMapsOnImage.__init__`
            for details.

        Returns
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Deep copy.

        Nr   )r
   rS   r   rZ   rM   rV   r   r   r   r   r     s   z SegmentationMapsOnImage.deepcopy)N)NN)rt   rf   NFr   N)r   r   r   r   r   r   )r   r   F)rw   )__name__
__module____qualname____doc__rx   r]   r^   rJ   
deprecatedr`   rs   rn   r   r   r   rh   r   r   r   r   r   r   r
      s.    
.F
#

2

x(
7


 )r   
__future__r   r   r   numpyrS   Z	six.movesmovesr}    r   rJ   r   r   r   baser	   r   r   r
   r   r   r   r   <module>   s    
