o
    e)                    @   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mZ ddlmZ ddlmZmZmZmZ G d	d
 d
eZG dd deZG dd deZdS )z$Classes representing bounding boxes.    )print_functiondivisionabsolute_importN   )imgaug   )IAugmentable)normalize_shapeproject_coords_remove_out_of_image_fraction__normalize_shift_argsc                   @   s  e Zd ZdZdgddZedd Zedd Zed	d
 Zedd Z	edd Z
edd Zedd Zedd Zedd Zedd Zdd Zdd Zdd Zdhd d!Zdhd"d#Zdgd$d%Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zdid4d5Zejd6d7d8d9d: Zd;d< Z d=d> Z!djd?d@Z"dkdAdBZ#	C	E	G	3dldHdIZ$	D	3	dmdJdKZ%	E	dmdLdMZ&		2dndNdOZ'dPdQ Z(dRdS Z)dodUdVZ*dodWdXZ+e,dYdZ Z-dpd[d\Z.dpd]d^Z/d_d` Z0dadb Z1dcdd Z2dedf Z3dS )qBoundingBoxa  Class representing bounding boxes.

    Each bounding box is parameterized by its top left and bottom right
    corners. Both are given as x and y-coordinates. The corners are intended
    to lie inside the bounding box area. As a result, a bounding box that lies
    completely inside the image but has maximum extensions would have
    coordinates ``(0.0, 0.0)`` and ``(W - epsilon, H - epsilon)``. Note that
    coordinates are saved internally as floats.

    Parameters
    ----------
    x1 : number
        X-coordinate of the top left of the bounding box.

    y1 : number
        Y-coordinate of the top left of the bounding box.

    x2 : number
        X-coordinate of the bottom right of the bounding box.

    y2 : number
        Y-coordinate of the bottom right of the bounding box.

    label : None or str, optional
        Label of the bounding box, e.g. a string representing the class.

    Nc                 C   sF   ||kr	||}}||kr||}}|| _ || _|| _|| _|| _dS )z"Create a new BoundingBox instance.Nx1y1x2y2labelselfr   r   r   r   r    r   GD:\Projects\ConvertPro\env\Lib\site-packages\imgaug/augmentables/bbs.py__init__/   s   


zBoundingBox.__init__c                 C   sD   t jdt jd}| j| jf|dddf< | j| jf|dddf< |S )a  Get the top-left and bottom-right coordinates as one array.

        Added in 0.4.0.

        Returns
        -------
        ndarray
            A ``(N, 2)`` numpy array with ``N=2`` containing the top-left
            and bottom-right coordinates.

        r   r   dtyper   Nr   )npemptyfloat32r   r   r   r   )r   arrr   r   r   coords<   s   zBoundingBox.coordsc                 C      t t| jS )zGet the x-coordinate of the top left corner as an integer.

        Returns
        -------
        int
            X-coordinate of the top left corner, rounded to the closest
            integer.

        )intr   roundr   r   r   r   r   x1_intN      zBoundingBox.x1_intc                 C   r!   )zGet the y-coordinate of the top left corner as an integer.

        Returns
        -------
        int
            Y-coordinate of the top left corner, rounded to the closest
            integer.

        )r"   r   r#   r   r$   r   r   r   y1_int]   r&   zBoundingBox.y1_intc                 C   r!   )zGet the x-coordinate of the bottom left corner as an integer.

        Returns
        -------
        int
            X-coordinate of the bottom left corner, rounded to the closest
            integer.

        )r"   r   r#   r   r$   r   r   r   x2_intl   r&   zBoundingBox.x2_intc                 C   r!   )zGet the y-coordinate of the bottom left corner as an integer.

        Returns
        -------
        int
            Y-coordinate of the bottom left corner, rounded to the closest
            integer.

        )r"   r   r#   r   r$   r   r   r   y2_int{   r&   zBoundingBox.y2_intc                 C      | j | j S )zEstimate the height of the bounding box.

        Returns
        -------
        number
            Height of the bounding box.

        )r   r   r$   r   r   r   height      
zBoundingBox.heightc                 C   r*   )zEstimate the width of the bounding box.

        Returns
        -------
        number
            Width of the bounding box.

        )r   r   r$   r   r   r   width   r,   zBoundingBox.widthc                 C      | j | jd  S )zEstimate the x-coordinate of the center point of the bounding box.

        Returns
        -------
        number
            X-coordinate of the center point of the bounding box.

        r   )r   r-   r$   r   r   r   center_x      
zBoundingBox.center_xc                 C   r.   )zEstimate the y-coordinate of the center point of the bounding box.

        Returns
        -------
        number
            Y-coordinate of the center point of the bounding box.

        r   )r   r+   r$   r   r   r   center_y   r0   zBoundingBox.center_yc                 C   s   | j | j S )zEstimate the area of the bounding box.

        Returns
        -------
        number
            Area of the bounding box, i.e. ``height * width``.

        )r+   r-   r$   r   r   r   area   r,   zBoundingBox.areac                 C   sZ   t |tr
|\}}n|j|j}}| j|  ko| jkn  o,| j|  ko*| jkS   S )aa  Estimate whether the bounding box contains a given point.

        Parameters
        ----------
        other : tuple of number or imgaug.augmentables.kps.Keypoint
            Point to check for.

        Returns
        -------
        bool
            ``True`` if the point is contained in the bounding box,
            ``False`` otherwise.

        )
isinstancetuplexyr   r   r   r   )r   otherr5   r6   r   r   r   contains   s   

8zBoundingBox.containsc                 C   s8   t | j| jf| j| jfg||\\| _| _\| _| _| S )a  Project the bounding box onto a differently shaped image in-place.

        E.g. if the bounding box is on its original image at
        ``x1=(10 of 100 pixels)`` and ``y1=(20 of 100 pixels)`` and is
        projected onto a new image with size ``(width=200, height=200)``,
        its new position will be ``(x1=20, y1=40)``.
        (Analogous for ``x2``/``y2``.)

        This is intended for cases where the original image is resized.
        It cannot be used for more complex changes (e.g. padding, cropping).

        Added in 0.4.0.

        Parameters
        ----------
        from_shape : tuple of int or ndarray
            Shape of the original image. (Before resize.)

        to_shape : tuple of int or ndarray
            Shape of the new image. (After resize.)

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            ``BoundingBox`` instance with new coordinates.
            The object may have been modified in-place.

        )r
   r   r   r   r   r   Z
from_shapeZto_shaper   r   r   project_   s   zBoundingBox.project_c                 C   s   |   ||S )az  Project the bounding box onto a differently shaped image.

        E.g. if the bounding box is on its original image at
        ``x1=(10 of 100 pixels)`` and ``y1=(20 of 100 pixels)`` and is
        projected onto a new image with size ``(width=200, height=200)``,
        its new position will be ``(x1=20, y1=40)``.
        (Analogous for ``x2``/``y2``.)

        This is intended for cases where the original image is resized.
        It cannot be used for more complex changes (e.g. padding, cropping).

        Parameters
        ----------
        from_shape : tuple of int or ndarray
            Shape of the original image. (Before resize.)

        to_shape : tuple of int or ndarray
            Shape of the new image. (After resize.)

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            ``BoundingBox`` instance with new coordinates.

        )deepcopyr:   r9   r   r   r   project   s   zBoundingBox.projectr   c                 C   sD   | j | | | _ | j| | | _| j| | | _| j| | | _| S )a  Extend the size of the bounding box along its sides in-place.

        Added in 0.4.0.

        Parameters
        ----------
        all_sides : number, optional
            Value by which to extend the bounding box size along all
            sides.

        top : number, optional
            Value by which to extend the bounding box size along its top
            side.

        right : number, optional
            Value by which to extend the bounding box size along its right
            side.

        bottom : number, optional
            Value by which to extend the bounding box size along its bottom
            side.

        left : number, optional
            Value by which to extend the bounding box size along its left
            side.

        Returns
        -------
        imgaug.BoundingBox
            Extended bounding box.
            The object may have been modified in-place.

        r   r   r   r   r   Z	all_sidestoprightbottomleftr   r   r   extend_  s
   "zBoundingBox.extend_c                 C   s   |   |||||S )a9  Extend the size of the bounding box along its sides.

        Parameters
        ----------
        all_sides : number, optional
            Value by which to extend the bounding box size along all
            sides.

        top : number, optional
            Value by which to extend the bounding box size along its top
            side.

        right : number, optional
            Value by which to extend the bounding box size along its right
            side.

        bottom : number, optional
            Value by which to extend the bounding box size along its bottom
            side.

        left : number, optional
            Value by which to extend the bounding box size along its left
            side.

        Returns
        -------
        imgaug.BoundingBox
            Extended bounding box.

        )r;   rC   r>   r   r   r   extendD  s   zBoundingBox.extendc                 C   s\   t | j|j}t | j|j}t| j|j}t| j|j}||ks$||kr&|S t||||dS )aL  Compute the intersection BB between this BB and another BB.

        Note that in extreme cases, the intersection can be a single point.
        In that case the intersection bounding box exists and it will be
        returned, but it will have a height and width of zero.

        Parameters
        ----------
        other : imgaug.augmentables.bbs.BoundingBox
            Other bounding box with which to generate the intersection.

        default : any, optional
            Default value to return if there is no intersection.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox or any
            Intersection bounding box of the two bounding boxes if there is
            an intersection.
            If there is no intersection, the default value will be returned,
            which can by anything.

        r   r   r   r   )maxr   r   minr   r   r   )r   r7   defaultZx1_iZy1_iZx2_iZy2_ir   r   r   intersectione  s   zBoundingBox.intersectionc                 C   s8   t t| j|jt| j|jt| j|jt| j|jdS )a  Compute the union BB between this BB and another BB.

        This is equivalent to drawing a bounding box around all corner points
        of both bounding boxes.

        Parameters
        ----------
        other : imgaug.augmentables.bbs.BoundingBox
            Other bounding box with which to generate the union.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Union bounding box of the two bounding boxes.

        rE   )r   rG   r   r   rF   r   r   )r   r7   r   r   r   union  s   zBoundingBox.unionc                 C   s>   |  |}|du rdS | j|j |j }|dkr|j| S dS )a  Compute the IoU between this bounding box and another one.

        IoU is the intersection over union, defined as::

            ``area(intersection(A, B)) / area(union(A, B))``
            ``= area(intersection(A, B))
                / (area(A) + area(B) - area(intersection(A, B)))``

        Parameters
        ----------
        other : imgaug.augmentables.bbs.BoundingBox
            Other bounding box with which to compare.

        Returns
        -------
        float
            IoU between the two bounding boxes.

        N        r   )rI   r2   )r   r7   ZintersZ
area_unionr   r   r   iou  s
   
zBoundingBox.iouc                 C   sR   t |}|dd \}}tdd||d}| j|dd}| j}|du r$|S ||j S )a+  Compute the area of the BB that is outside of the image plane.

        Added in 0.4.0.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape
            and must contain at least two integers.

        Returns
        -------
        float
            Total area of the bounding box that is outside of the image plane.
            Can be ``0.0``.

        r   r   rE   N)rH   )r	   r   rI   r2   )r   imageshaper+   r-   Zbb_imageinterr2   r   r   r   compute_out_of_image_area  s   z%BoundingBox.compute_out_of_image_areac           	      C   sp   | j }|dkr1t|}|dd \}}| jdk p| j|k}| jdk p&| j|k}|p*|}|r/dS dS | || S )a  Compute fraction of BB area outside of the image plane.

        This estimates ``f = A_ooi / A``, where ``A_ooi`` is the area of the
        bounding box that is outside of the image plane, while ``A`` is the
        total area of the bounding box.

        Added in 0.4.0.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape
            and must contain at least two integers.

        Returns
        -------
        float
            Fraction of the bounding box area that is outside of the image
            plane. Returns ``0.0`` if the bounding box is fully inside of
            the image plane. If the bounding box has an area of zero, the
            result is ``1.0`` if its coordinates are outside of the image
            plane, otherwise ``0.0``.

        r   r         ?rK   )r2   r	   r   r   rP   )	r   rM   r2   rN   r+   r-   Z
y1_outsideZ
x1_outsideZ
is_outsider   r   r   compute_out_of_image_fraction  s   z)BoundingBox.compute_out_of_image_fractionc                 C   s@   t |}|dd \}}| jdko| j|k o| jdko| j|k S )a  Estimate whether the bounding box is fully inside the image area.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape
            and must contain at least two integers.

        Returns
        -------
        bool
            ``True`` if the bounding box is fully inside the image area.
            ``False`` otherwise.

        r   r   )r	   r   r   r   r   )r   rM   rN   r+   r-   r   r   r   is_fully_within_image  s   
z!BoundingBox.is_fully_within_imagec                 C   sL   t |}|dd \}}ttjj}td|| d|| d}| |duS )a/  Estimate whether the BB is at least partially inside the image area.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape
            and must contain at least two integers.

        Returns
        -------
        bool
            ``True`` if the bounding box is at least partially inside the
            image area.
            ``False`` otherwise.

        r   r   r=   N)r	   r   finfor   epsr   rI   )r   rM   rN   r+   r-   rU   Zimg_bbr   r   r   is_partly_within_image  s
   z"BoundingBox.is_partly_within_imageTFc                 C   s    |  |rdS | |r|S |S )av  Estimate whether the BB is partially/fully outside of the image area.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape and
            must contain at least two integers.

        fully : bool, optional
            Whether to return ``True`` if the bounding box is fully outside
            of the image area.

        partly : bool, optional
            Whether to return ``True`` if the bounding box is at least
            partially outside fo the image area.

        Returns
        -------
        bool
            ``True`` if the bounding box is partially/fully outside of the
            image area, depending on defined parameters.
            ``False`` otherwise.

        F)rS   rV   )r   rM   fullypartlyr   r   r   is_out_of_image*  s
   

zBoundingBox.is_out_of_imagezBoundingBox.clip_out_of_image()3clip_out_of_image() has the exactly same interface.Zalt_funccommentc                 O   s   | j |i |S )z?Clip off all parts of the BB box that are outside of the image.clip_out_of_image)r   argskwargsr   r   r   cut_out_of_imageK  s   zBoundingBox.cut_out_of_imagec                 C   s   t |}|dd \}}|dksJ d|jf |dks$J d|jf ttjj}t| jd|| | _t| jd|| | _t| j	d|| | _	t| j
d|| | _
| S )a  Clip off parts of the BB box that are outside of the image in-place.

        Added in 0.4.0.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use for the clipping of the bounding box.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape and
            must contain at least two integers.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Bounding box, clipped to fall within the image dimensions.
            The object may have been modified in-place.

        r   r   z+Expected image with height>0, got shape %s.z*Expected image with width>0, got shape %s.)r	   rN   r   rT   r   rU   clipr   r   r   r   )r   rM   rN   r+   r-   rU   r   r   r   clip_out_of_image_R  s   



zBoundingBox.clip_out_of_image_c                 C      |   |S )a2  Clip off all parts of the BB box that are outside of the image.

        Parameters
        ----------
        image : (H,W,...) ndarray or tuple of int
            Image dimensions to use for the clipping of the bounding box.
            If an ``ndarray``, its shape will be used.
            If a ``tuple``, it is assumed to represent the image shape and
            must contain at least two integers.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Bounding box, clipped to fall within the image dimensions.

        r;   rc   r   rM   r   r   r   r^   v     zBoundingBox.clip_out_of_imagec                 C   s<   |  j |7  _ |  j|7  _|  j|7  _|  j|7  _| S )a  Move this bounding box along the x/y-axis in-place.

        The origin ``(0, 0)`` is at the top left of the image.

        Added in 0.4.0.

        Parameters
        ----------
        x : number, optional
            Value to be added to all x-coordinates. Positive values shift
            towards the right images.

        y : number, optional
            Value to be added to all y-coordinates. Positive values shift
            towards the bottom images.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Shifted bounding box.
            The object may have been modified in-place.

        r=   )r   r5   r6   r   r   r   shift_  s
   zBoundingBox.shift_c                 C   s(   t ||||||d\}}|  ||S )a   Move this bounding box along the x/y-axis.

        The origin ``(0, 0)`` is at the top left of the image.

        Parameters
        ----------
        x : number, optional
            Value to be added to all x-coordinates. Positive values shift
            towards the right images.

        y : number, optional
            Value to be added to all y-coordinates. Positive values shift
            towards the bottom images.

        top : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift this object *from* the
            top (towards the bottom).

        right : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift this object *from* the
            right (towards the left).

        bottom : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift this object *from* the
            bottom (towards the top).

        left : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift this object *from* the
            left (towards the right).

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Shifted bounding box.

        r?   r@   rA   rB   r   r;   rh   r   r5   r6   r?   r@   rA   rB   r   r   r   shift  s   *
zBoundingBox.shiftr      r   rQ   r         c              
   C   s4   t ||||||
||d}|	r||| S ||| S )a,  Draw a box showing the BB's label.

        The box is placed right above the BB's rectangle.

        Added in 0.4.0.

        Parameters
        ----------
        image : (H,W,C) ndarray
            The image onto which to draw the label.
            Currently expected to be ``uint8``.

        color : None or iterable of int, optional
            The color to use, corresponding to the channel layout of the
            image. Usually RGB. Text and background colors will be derived
            from this.

        color_text : None or iterable of int, optional
            The text color to use.
            If ``None``, derived from `color_bg`.

        color_bg : None or iterable of int, optional
            The background color of the label box.
            If ``None``, derived from `color`.

        alpha : float, optional
            The transparency of the drawn bounding box, where ``1.0`` denotes
            no transparency and ``0.0`` is invisible.

        size : int, optional
            The thickness of the bounding box in pixels. If the value is
            larger than ``1``, then additional pixels will be added around
            the bounding box (i.e. extension towards the outside).

        size_text : int, optional
            Font size to use.

        height : int, optional
            Height of the label box in pixels.

        copy : bool, optional
            Whether to copy the input image or change it in-place.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the bounding box is fully outside of
            the image. If set to ``False``, no error will be raised and only
            the parts inside the image will be drawn.

        Returns
        -------
        (H,W,C) ndarray(uint8)
            Image with bounding box drawn on it.

        color
color_textcolor_bgsizealpharaise_if_out_of_imager+   	size_text)_LabelOnImageDrawerdraw_on_imagedraw_on_image_)r   rM   rr   rs   rt   rv   ru   rx   r+   copyrw   Zdrawerr   r   r   draw_label_on_image  s   ;	zBoundingBox.draw_label_on_imagec                 C   s  |durt d |}|r"| |r"td| j| j| j| j|jf |r)t	
|n|}t|ttfr7t	|}t|D ]}	| j| j| j| jf\}
}}}| |rt	|
d|jd d }
t	|d|jd d }t	|d|jd d }t	|d|jd d }|
|	 |
|	 ||	 ||	 g}||	 ||	 ||	 ||	 g}tjj|||jd\}}|dkr||||ddf< q;t |rd| |||ddf  ||  |||ddf< t	|dd}q;|j}|t	j}d| |||ddf  ||  |||ddf< t	|dd|}q;|S )	a  Draw the rectangle of the bounding box on an image.

        This method does not draw the label.

        Added in 0.4.0.

        Parameters
        ----------
        image : (H,W,C) ndarray
            The image onto which to draw the bounding box rectangle.
            Currently expected to be ``uint8``.

        color : iterable of int, optional
            The color to use, corresponding to the channel layout of the
            image. Usually RGB.

        alpha : float, optional
            The transparency of the drawn bounding box, where ``1.0`` denotes
            no transparency and ``0.0`` is invisible.

        size : int, optional
            The thickness of the bounding box in pixels. If the value is
            larger than ``1``, then additional pixels will be added around
            the bounding box (i.e. extension towards the outside).

        copy : bool, optional
            Whether to copy the input image or change it in-place.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the bounding box is fully outside of
            the image. If set to ``False``, no error will be raised and only
            the parts inside the image will be drawn.

        thickness : None or int, optional
            Deprecated.

        Returns
        -------
        (H,W,C) ndarray(uint8)
            Image with bounding box drawn on it.

        NzoUsage of argument 'thickness' in BoundingBox.draw_on_image() is deprecated. The argument was renamed to 'size'.SCannot draw bounding box x1=%.8f, y1=%.8f, x2=%.8f, y2=%.8f on image with shape %s.r   r   rN   Gz?rn   )iaZwarn_deprecatedrY   	Exceptionr   r   r   r   rN   r   r|   r3   r4   listuint8ranger'   r)   r%   r(   rS   rb   skimageZdrawZpolygon_perimeterZis_float_arrayr   astyper   )r   rM   rr   rv   ru   r|   rw   	thicknessresultir   r   r   r   r6   r5   rrccinput_dtyper   r   r   draw_box_on_image  sR   .


zBoundingBox.draw_box_on_imagec           	   	   C   sH   | j |||||||d}| jdur"| j||||du r|n|d|d}|S )a  Draw the bounding box on an image.

        This will automatically also draw the label, unless it is ``None``.
        To only draw the box rectangle use
        :func:`~imgaug.augmentables.bbs.BoundingBox.draw_box_on_image`.
        To draw the label even if it is ``None`` or to configure e.g. its
        color, use
        :func:`~imgaug.augmentables.bbs.BoundingBox.draw_label_on_image`.

        Parameters
        ----------
        image : (H,W,C) ndarray
            The image onto which to draw the bounding box.
            Currently expected to be ``uint8``.

        color : iterable of int, optional
            The color to use, corresponding to the channel layout of the
            image. Usually RGB.

        alpha : float, optional
            The transparency of the drawn bounding box, where ``1.0`` denotes
            no transparency and ``0.0`` is invisible.

        size : int, optional
            The thickness of the bounding box in pixels. If the value is
            larger than ``1``, then additional pixels will be added around
            the bounding box (i.e. extension towards the outside).

        copy : bool, optional
            Whether to copy the input image or change it in-place.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the bounding box is fully outside of
            the image. If set to ``False``, no error will be raised and only
            the parts inside the image will be drawn.

        thickness : None or int, optional
            Deprecated.

        Returns
        -------
        (H,W,C) ndarray(uint8)
            Image with bounding box drawn on it.

        rr   rv   ru   r|   rw   r   NF)rr   rv   ru   r|   rw   )r   r   r}   )	r   rM   rr   rv   ru   r|   rw   r   Zimage_drawnr   r   r   rz     s   0
zBoundingBox.draw_on_imagec                 C   sf  |j d |j d }}| j| j| j| jf\}}}	}
| |}|r:t|	|
gd|d \}	}
t||gd|d \}}|rTt|| dk rH|d }t|
|	 dk rT|	d }
|rddl	m
} d}d}d}d}|dk rvt|}|| }|| }d}|	dk rt|	}|
| }
|| }d}	||kr|| }|
|kr|
| }||||g}tdd |D }|r|du rt|}|j|t||t||t||t||d}||	|
||f S d	||	||
f  ko||||fk n  }|
|	 || }}|dk}|dk}|r	|r	|r	||	|
||f S |rd}d}nd}d}|jdkr%tj||f|jd
S tj|||j d f|jd
S )a  Extract the image pixels within the bounding box.

        This function will zero-pad the image if the bounding box is
        partially/fully outside of the image.

        Parameters
        ----------
        image : (H,W) ndarray or (H,W,C) ndarray
            The image from which to extract the pixels within the bounding box.

        pad : bool, optional
            Whether to zero-pad the image if the object is partially/fully
            outside of it.

        pad_max : None or int, optional
            The maximum number of pixels that may be zero-paded on any side,
            i.e. if this has value ``N`` the total maximum of added pixels
            is ``4*N``.
            This option exists to prevent extremely large images as a result of
            single points being moved very far away during augmentation.

        prevent_zero_size : bool, optional
            Whether to prevent the height or width of the extracted image from
            becoming zero.
            If this is set to ``True`` and the height or width of the bounding
            box is below ``1``, the height/width will be increased to ``1``.
            This can be useful to prevent problems, e.g. with image saving or
            plotting.
            If it is set to ``False``, images will be returned as ``(H', W')``
            or ``(H', W', 3)`` with ``H`` or ``W`` potentially being 0.

        Returns
        -------
        (H',W') ndarray or (H',W',C) ndarray
            Pixels within the bounding box. Zero-padded if the bounding box
            is partially/fully outside of the image.
            If `prevent_zero_size` is activated, it is guarantueed that
            ``H'>0`` and ``W'>0``, otherwise only ``H'>=0`` and ``W'>=0``.

        r   r   r   )ru   c                 S   s   g | ]}|d kqS )r   r   ).0valr   r   r   
<listcomp>      z2BoundingBox.extract_from_image.<locals>.<listcomp>Nri   )r   r   r   r   r   )rN   r%   r(   r'   r)   rS   r   rb   absZ
augmentersru   anyrF   padrG   ndimzerosr   )r   rM   r   Zpad_maxZprevent_zero_sizer+   r-   r   r   r   r   Zfully_withinZiasizepad_top	pad_rightZ
pad_bottompad_leftZpaddingsZ
any_paddedZwithin_imageZ
out_heightZ	out_widthZnonzero_heightZnonzero_widthr   r   r   extract_from_image  s   +


zBoundingBox.extract_from_imagec                 C   sH   ddl m} || j| jd|| j| jd|| j| jd|| j| jdgS )zConvert the BB's corners to keypoints (clockwise, from top left).

        Returns
        -------
        list of imgaug.augmentables.kps.Keypoint
            Corners of the bounding box as keypoints.

        r   )Keypointr5   r6   )Zimgaug.augmentables.kpsr   r   r   r   r   )r   r   r   r   r   to_keypointsC  s   
zBoundingBox.to_keypointsc                 C   sB   ddl m} || j| jf| j| jf| j| jf| j| jfg| jdS )zConvert this bounding box to a polygon covering the same area.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.polys.Polygon
            The bounding box converted to a polygon.

        r   )Polygon)r   )Zimgaug.augmentables.polysr   r   r   r   r   r   )r   r   r   r   r   
to_polygonV  s   



zBoundingBox.to_polygon-C6?c                 C   sl   t |tr
|jj}nt|r|j}nt|r tt|}n	t	dt
|f | j}tj|j||ddS )a  Estimate if this and another BB have almost identical coordinates.

        Added in 0.4.0.

        Parameters
        ----------
        other : imgaug.augmentables.bbs.BoundingBox or iterable
            The other bounding box with which to compare this one.
            If this is an ``iterable``, it is assumed to represent the top-left
            and bottom-right coordinates of that bounding box, given as e.g.
            an ``(2,2)`` ndarray or an ``(4,)`` ndarray or as a similar list.

        max_distance : number, optional
            The maximum euclidean distance between a corner on one bounding
            box and the closest corner on the other bounding box. If the
            distance is exceeded for any such pair, the two BBs are not
            viewed as equal.

        Returns
        -------
        bool
            Whether the two bounding boxes have almost identical corner
            coordinates.

        zgExpected 'other' to be an iterable containing two (x,y)-coordinate pairs or a BoundingBox. Got type %s.r   )ZatolZrtol)r3   r   r    Zflatr   Zis_np_arrayis_iterabler   flatten
ValueErrortyper   Zallclose)r   r7   max_distanceZcoords_bZcoords_ar   r   r   coords_almost_equalsl  s   



z BoundingBox.coords_almost_equalsc                 C   s   | j |j krdS | j||dS )a  Compare this and another BB's label and coordinates.

        This is the same as
        :func:`~imgaug.augmentables.bbs.BoundingBox.coords_almost_equals` but
        additionally compares the labels.

        Added in 0.4.0.

        Parameters
        ----------
        other : imgaug.augmentables.bbs.BoundingBox or iterable
            The other object to compare against. Expected to be a
            ``BoundingBox``.

        max_distance : number, optional
            See
            :func:`~imgaug.augmentables.bbs.BoundingBox.coords_almost_equals`.

        Returns
        -------
        bool
            ``True`` if the coordinates are almost equal and additionally
            the labels are equal. Otherwise ``False``.

        F)r   )r   r   )r   r7   r   r   r   r   almost_equals  s   zBoundingBox.almost_equalsc                 C   s   t j|t jd}t|dksJ d|jf |jdks/|jdkr'|jd dks/J d|jf |jdkr9|d}t j|dd	\}}t j|dd	\}}| ||||d
S )aw  Convert a ``(2P,) or (P,2) ndarray`` to a BB instance.

        This is the inverse of
        :func:`~imgaug.BoundingBoxesOnImage.to_xyxy_array`.

        Added in 0.4.0.

        Parameters
        ----------
        xy : (2P,) ndarray or (P, 2) array or iterable of number or iterable of iterable of number
            Array containing ``P`` points in xy-form denoting a soup of
            points around which to place a bounding box.
            The array should usually be of dtype ``float32``.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Bounding box around the points.

        r   r   zPExpected to get at least one point to place a bounding box around, got shape %s.r   r   r   z;Expected input array of shape (P,) or (P, 2), got shape %s.r   r   )ZaxisrE   )	r   arrayr   lenrN   r   reshaperG   rF   )clsxyr   r   r   r   r   r   r   from_point_soup  s    $

zBoundingBox.from_point_soupc                 C   sb   t |du r| jn||du r| jn||du r| jn||du r | jn||du r-t| jdS |dS )a  Create a shallow copy of this BoundingBox instance.

        Parameters
        ----------
        x1 : None or number
            If not ``None``, then the ``x1`` coordinate of the copied object
            will be set to this value.

        y1 : None or number
            If not ``None``, then the ``y1`` coordinate of the copied object
            will be set to this value.

        x2 : None or number
            If not ``None``, then the ``x2`` coordinate of the copied object
            will be set to this value.

        y2 : None or number
            If not ``None``, then the ``y2`` coordinate of the copied object
            will be set to this value.

        label : None or string
            If not ``None``, then the ``label`` of the copied object
            will be set to this value.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Shallow copy.

        N)r   r   r   r   r   )r   r   r   r   r   r|   r;   r   r   r   r   r   r|     s   zBoundingBox.copyc                 C   s   | j |||||dS )a  
        Create a deep copy of the BoundingBox object.

        Parameters
        ----------
        x1 : None or number
            If not ``None``, then the ``x1`` coordinate of the copied object
            will be set to this value.

        y1 : None or number
            If not ``None``, then the ``y1`` coordinate of the copied object
            will be set to this value.

        x2 : None or number
            If not ``None``, then the ``x2`` coordinate of the copied object
            will be set to this value.

        y2 : None or number
            If not ``None``, then the ``y2`` coordinate of the copied object
            will be set to this value.

        label : None or string
            If not ``None``, then the ``label`` of the copied object
            will be set to this value.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBox
            Deep copy.

        r   )r|   r   r   r   r   r;     s   "zBoundingBox.deepcopyc                 C   
   | j | S )zGet the coordinate(s) with given indices.

        Added in 0.4.0.

        Returns
        -------
        ndarray
            xy-coordinate(s) as ``ndarray``.

        )r    r   indicesr   r   r   __getitem__)     
zBoundingBox.__getitem__c                 C   
   t | jS )zIterate over the coordinates of this instance.

        Added in 0.4.0.

        Yields
        ------
        ndarray
            An ``(2,)`` ``ndarray`` denoting an xy-coordinate pair.

        )iterr    r$   r   r   r   __iter__6  r   zBoundingBox.__iter__c                 C      |   S N__str__r$   r   r   r   __repr__C     zBoundingBox.__repr__c                 C   s   d| j | j| j| j| jf S )Nz9BoundingBox(x1=%.4f, y1=%.4f, x2=%.4f, y2=%.4f, label=%s)r   r$   r   r   r   r   F  s   zBoundingBox.__str__r   )r   r   r   r   r   TFr   r   r   r   NNNN)	rm   NNrQ   r   ro   rp   TFrm   rQ   r   TFN)TNT)r   )NNNNN)4__name__
__module____qualname____doc__r   propertyr    r%   r'   r(   r)   r+   r-   r/   r1   r2   r8   r:   r<   rC   rD   rI   rJ   rL   rP   rR   rS   rV   rY   r   
deprecatedra   rc   r^   rh   rl   r}   r   rz   r   r   r   r   r   classmethodr   r|   r;   r   r   r   r   r   r   r   r   r      s    










$

(
! %
!
$

.
H
e
>
 

+

(
'$r   c                   @   sd  e Zd ZdZdd Zedd Zejdd Zedd Zed	d
 Z	edd Z
dd Zdd Zedd Zedd ZejfddZdd Zdd Zdd Z		"dOd#d$ZdPd%d&ZdPd'd(Zd)d* Zd+d, Zejd-d.d/d0d1 Zd2d3 Zd4d5 ZdQd7d8Z dRd9d:Z!d;d< Z"d=d> Z#d?d@ Z$dSdAdBZ%dSdCdDZ&dEdF Z'dGdH Z(dIdJ Z)dKdL Z*dMdN Z+d"S )TBoundingBoxesOnImagea  Container for the list of all bounding boxes on a single image.

    Parameters
    ----------
    bounding_boxes : list of imgaug.augmentables.bbs.BoundingBox
        List of bounding boxes on the image.

    shape : tuple of int or ndarray
        The shape of the image on which the objects are placed.
        Either an image with shape ``(H,W,[C])`` or a ``tuple`` denoting
        such an image shape.

    Examples
    --------
    >>> import numpy as np
    >>> from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
    >>>
    >>> image = np.zeros((100, 100))
    >>> bbs = [
    >>>     BoundingBox(x1=10, y1=20, x2=20, y2=30),
    >>>     BoundingBox(x1=25, y1=50, x2=30, y2=70)
    >>> ]
    >>> bbs_oi = BoundingBoxesOnImage(bbs, shape=image.shape)

    c                 C   s   || _ t|| _d S r   )bounding_boxesr	   rN   r   r   rN   r   r   r   r   e  s   zBoundingBoxesOnImage.__init__c                 C   s   | j S )zGet the bounding boxes in this container.

        Added in 0.4.0.

        Returns
        -------
        list of BoundingBox
            Bounding boxes within this container.

        r   r$   r   r   r   itemsi  s   zBoundingBoxesOnImage.itemsc                 C   s
   || _ dS )zSet the bounding boxes in this container.

        Added in 0.4.0.

        Parameters
        ----------
        value : list of BoundingBox
            Bounding boxes within this container.

        Nr   )r   valuer   r   r   r   w  s   
c                 C   
   | j d S )zGet the height of the image on which the bounding boxes fall.

        Returns
        -------
        int
            Image height.

        r   r   r$   r   r   r   r+        

zBoundingBoxesOnImage.heightc                 C   r   )zGet the width of the image on which the bounding boxes fall.

        Returns
        -------
        int
            Image width.

        r   r   r$   r   r   r   r-     r   zBoundingBoxesOnImage.widthc                 C   s   t | jdkS )zDetermine whether this instance contains zero bounding boxes.

        Returns
        -------
        bool
            True if this object contains zero bounding boxes.

        r   )r   r   r$   r   r   r   r     s   
zBoundingBoxesOnImage.emptyc                 C   s^   t |}|dd | jdd kr|| _| S t| jD ]\}}|| j|| j|< q|| _| S )a<  Project BBs from one image (shape) to a another one in-place.

        Added in 0.4.0.

        Parameters
        ----------
        image : ndarray or tuple of int
            New image onto which the bounding boxes are to be projected.
            May also simply be that new image's shape tuple.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Object containing the same bounding boxes after projection to
            the new image shape.
            The object and its items may have been modified in-place.

        r   r   )r	   rN   	enumerater   r:   r   )r   rM   Zon_shaper   itemr   r   r   on_  s   zBoundingBoxesOnImage.on_c                 C   rd   )a  Project bounding boxes from one image (shape) to a another one.

        Parameters
        ----------
        image : ndarray or tuple of int
            New image onto which the bounding boxes are to be projected.
            May also simply be that new image's shape tuple.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Object containing the same bounding boxes after projection to
            the new image shape.

        )r;   r   rf   r   r   r   on  rg   zBoundingBoxesOnImage.onc                 C   s   t j|t jd}|jd dkrtg |S |jdkr |jd dks6|jdkr.|jdd dks6J d	|jf |d
}dd |D }| ||S )af  Convert an ``(N, 4) or (N, 2, 2) ndarray`` to a BBsOI instance.

        This is the inverse of
        :func:`~imgaug.BoundingBoxesOnImage.to_xyxy_array`.

        Parameters
        ----------
        xyxy : (N, 4) ndarray or (N, 2, 2) array
            Array containing the corner coordinates of ``N`` bounding boxes.
            Each bounding box is represented by its top-left and bottom-right
            coordinates.
            The array should usually be of dtype ``float32``.

        shape : tuple of int
            Shape of the image on which the bounding boxes are placed.
            Should usually be ``(H, W, C)`` or ``(H, W)``.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Object containing a list of :class:`BoundingBox` instances
            derived from the provided corner coordinates.

        r   r   r   r         r   r   z@Expected input array of shape (N, 4) or (N, 2, 2), got shape %s.)r   r   r   c                 S      g | ]}t |qS r   r   r   r   rowr   r   r   r         z8BoundingBoxesOnImage.from_xyxy_array.<locals>.<listcomp>)r   r   r   rN   r   r   r   )r   xyxyrN   boxesr   r   r   from_xyxy_array  s   


z$BoundingBoxesOnImage.from_xyxy_arrayc                 C   s(   t j|t jd}dd |D }| ||S )aS  Convert an ``(N, 2P) or (N, P, 2) ndarray`` to a BBsOI instance.

        Added in 0.4.0.

        Parameters
        ----------
        xy : (N, 2P) ndarray or (N, P, 2) array or iterable of iterable of number or iterable of iterable of iterable of number
            Array containing the corner coordinates of ``N`` bounding boxes.
            Each bounding box is represented by a soup of ``P`` points.
            If ``(N, P)`` then the second axis is expected to be in
            xy-form (e.g. ``x1``, ``y1``, ``x2``, ``y2``, ...).
            The final bounding box coordinates will be derived using ``min``
            and ``max`` operations on the xy-values.
            The array should usually be of dtype ``float32``.

        shape : tuple of int
            Shape of the image on which the bounding boxes are placed.
            Should usually be ``(H, W, C)`` or ``(H, W)``.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Object containing a list of :class:`BoundingBox` instances
            derived from the provided point soups.

        r   c                 S   r   r   r   r   r   r   r   r   *  r   z9BoundingBoxesOnImage.from_point_soups.<locals>.<listcomp>)r   r   r   )r   r   rN   r   r   r   r   from_point_soups
  s   
z%BoundingBoxesOnImage.from_point_soupsc                 C   sP   t jt| jdft jd}t| jD ]\}}|j|j|j|j	g||< q|
|S )a4  Convert the ``BoundingBoxesOnImage`` object to an ``(N,4) ndarray``.

        This is the inverse of
        :func:`~imgaug.BoundingBoxesOnImage.from_xyxy_array`.

        Parameters
        ----------
        dtype : numpy.dtype, optional
            Desired output datatype of the ndarray.

        Returns
        -------
        ndarray
            ``(N,4) ndarray``, where ``N`` denotes the number of bounding
            boxes and ``4`` denotes the top-left and bottom-right bounding
            box corner coordinates in form ``(x1, y1, x2, y2)``.

        r   r   )r   r   r   r   r   r   r   r   r   r   r   )r   r   Z
xyxy_arrayr   boxr   r   r   to_xyxy_array.  s   
z"BoundingBoxesOnImage.to_xyxy_arrayc                 C   s   |   dS )a	  Convert the ``BoundingBoxesOnImage`` object to an ``(N,2) ndarray``.

        Added in 0.4.0.

        Returns
        -------
        ndarray
            ``(2*B,2) ndarray`` of xy-coordinates, where ``B`` denotes the
            number of bounding boxes.

        r   )r   r   r$   r   r   r   to_xy_arrayH  s   z BoundingBoxesOnImage.to_xy_arrayc                 C   s   t j|t jd}|jd dks#|jdkr|jd dks#J d|jf t|t| jks9J dt|t| jf t| j|D ]$\}\}}}}t||g|_	t||g|_
t||g|_t||g|_q?| S )a  Modify the BB coordinates of this instance in-place.

        .. note::

            This currently expects exactly one entry in `xyxy` per bounding
            in this instance. (I.e. two corner coordinates per instance.)
            Otherwise, an ``AssertionError`` will be raised.

        .. note::

            This method will automatically flip x-coordinates if ``x1>x2``
            for a bounding box. (Analogous for y-coordinates.)

        Added in 0.4.0.

        Parameters
        ----------
        xyxy : (N, 4) ndarray or iterable of iterable of number
            Coordinates of ``N`` bounding boxes on an image, given as
            a ``(N,4)`` array of two corner xy-coordinates per bounding box.
            ``N`` must match the number of bounding boxes in this instance.

        Returns
        -------
        BoundingBoxesOnImage
            This instance itself, with updated bounding box coordinates.
            Note that the instance was modified in-place.

        r   r   r   r   r   z7Expected input array to have shape (N,4), got shape %s.zsExpected to receive an array with as many rows there are bounding boxes in this instance. Got %d rows, expected %d.)r   r   r   rN   r   r   r   ziprG   r   r   rF   r   r   )r   r   bbr   r   r   r   r   r   r   fill_from_xyxy_array_V  s$   (z*BoundingBoxesOnImage.fill_from_xyxy_array_c                 C   s    t j|t jd}| |dS )a  Modify the BB coordinates of this instance in-place.

        See
        :func:`~imgaug.augmentables.bbs.BoundingBoxesOnImage.fill_from_xyxy_array_`.

        Added in 0.4.0.

        Parameters
        ----------
        xy : (2*B, 2) ndarray or iterable of iterable of number
            Coordinates of ``B`` bounding boxes on an image, given as
            a ``(2*B,2)`` array of two corner xy-coordinates per bounding box.
            ``B`` must match the number of bounding boxes in this instance.

        Returns
        -------
        BoundingBoxesOnImage
            This instance itself, with updated bounding box coordinates.
            Note that the instance was modified in-place.

        r   )r   r   )r   r   r   r   r   )r   r   r   r   r   fill_from_xy_array_  s   z(BoundingBoxesOnImage.fill_from_xy_array_rm   rQ   r   TFNc           	   
   C   s:   |rt |n|}| jD ]}|j||||d||d}q|S )a/  Draw all bounding boxes onto a given image.

        Parameters
        ----------
        image : (H,W,3) ndarray
            The image onto which to draw the bounding boxes.
            This image should usually have the same shape as set in
            ``BoundingBoxesOnImage.shape``.

        color : int or list of int or tuple of int or (3,) ndarray, optional
            The RGB color of all bounding boxes.
            If a single ``int`` ``C``, then that is equivalent to ``(C,C,C)``.

        alpha : float, optional
            Alpha/transparency of the bounding box.

        size : int, optional
            Thickness in pixels.

        copy : bool, optional
            Whether to copy the image before drawing the bounding boxes.

        raise_if_out_of_image : bool, optional
            Whether to raise an exception if any bounding box is outside of the
            image.

        thickness : None or int, optional
            Deprecated.

        Returns
        -------
        (H,W,3) ndarray
            Image with drawn bounding boxes.

        Fr   )r   r|   r   rz   )	r   rM   rr   rv   ru   r|   rw   r   r   r   r   r   rz     s   &

z"BoundingBoxesOnImage.draw_on_imagec                    s    fddj D _ S )a  Remove in-place all BBs that are fully/partially outside of the image.

        Added in 0.4.0.

        Parameters
        ----------
        fully : bool, optional
            Whether to remove bounding boxes that are fully outside of the
            image.

        partly : bool, optional
            Whether to remove bounding boxes that are partially outside of
            the image.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Reduced set of bounding boxes, with those that were
            fully/partially outside of the image being removed.
            The object and its items may have been modified in-place.

        c                    s"   g | ]}|j j d s|qS )rW   rX   )rY   rN   r   r   rW   rX   r   r   r   r     s    z=BoundingBoxesOnImage.remove_out_of_image_.<locals>.<listcomp>r   r   rW   rX   r   r   r   remove_out_of_image_  s   z)BoundingBoxesOnImage.remove_out_of_image_c                 C   s   |   j||dS )aD  Remove all BBs that are fully/partially outside of the image.

        Parameters
        ----------
        fully : bool, optional
            Whether to remove bounding boxes that are fully outside of the
            image.

        partly : bool, optional
            Whether to remove bounding boxes that are partially outside of
            the image.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Reduced set of bounding boxes, with those that were
            fully/partially outside of the image being removed.

        r   )r|   r   r   r   r   r   remove_out_of_image  s   z(BoundingBoxesOnImage.remove_out_of_imagec                 C   s
   t | |S )a  Remove in-place all BBs with an OOI fraction of at least `fraction`.

        'OOI' is the abbreviation for 'out of image'.

        Added in 0.4.0.

        Parameters
        ----------
        fraction : number
            Minimum out of image fraction that a bounding box has to have in
            order to be removed. A fraction of ``1.0`` removes only bounding
            boxes that are ``100%`` outside of the image. A fraction of ``0.0``
            removes all bounding boxes.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Reduced set of bounding boxes, with those that had an out of image
            fraction greater or equal the given one removed.
            The object and its items may have been modified in-place.

        )r   r   fractionr   r   r   remove_out_of_image_fraction_
  s   
z2BoundingBoxesOnImage.remove_out_of_image_fraction_c                 C   rd   )a  Remove all BBs with an out of image fraction of at least `fraction`.

        Added in 0.4.0.

        Parameters
        ----------
        fraction : number
            Minimum out of image fraction that a bounding box has to have in
            order to be removed. A fraction of ``1.0`` removes only bounding
            boxes that are ``100%`` outside of the image. A fraction of ``0.0``
            removes all bounding boxes.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Reduced set of bounding boxes, with those that had an out of image
            fraction greater or equal the given one removed.

        )r|   r   r   r   r   r   remove_out_of_image_fraction#  s   z1BoundingBoxesOnImage.remove_out_of_image_fractionz(BoundingBoxesOnImage.clip_out_of_image()rZ   r[   c                 C   r   )z>Clip off all parts from all BBs that are outside of the image.r]   r$   r   r   r   ra   9  s   z%BoundingBoxesOnImage.cut_out_of_imagec                    s@    fdd j D  _ t j D ]\}}| j j |< q S )aX  
        Clip off in-place all parts from all BBs that are outside of the image.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Bounding boxes, clipped to fall within the image dimensions.
            The object and its items may have been modified in-place.

        c                    s   g | ]
}|  jr|qS r   )rV   rN   r   r$   r   r   r   N  s    

z;BoundingBoxesOnImage.clip_out_of_image_.<locals>.<listcomp>)r   r   r^   rN   )r   r   r   r   r$   r   rc   @  s   z'BoundingBoxesOnImage.clip_out_of_image_c                 C   s   |    S )zClip off all parts from all BBs that are outside of the image.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Bounding boxes, clipped to fall within the image dimensions.

        re   r$   r   r   r   r^   V  s   	z&BoundingBoxesOnImage.clip_out_of_imager   c                 C   s,   t | jD ]\}}|j||d| j|< q| S )a  Move all BBs along the x/y-axis in-place.

        The origin ``(0, 0)`` is at the top left of the image.

        Added in 0.4.0.

        Parameters
        ----------
        x : number, optional
            Value to be added to all x-coordinates. Positive values shift
            towards the right images.

        y : number, optional
            Value to be added to all y-coordinates. Positive values shift
            towards the bottom images.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Shifted bounding boxes.
            The object and its items may have been modified in-place.

        r   )r   r   rh   )r   r5   r6   r   r   r   r   r   rh   a  s   zBoundingBoxesOnImage.shift_c                 C   s*   t ||||||d\}}|  j||dS )a   Move all BBs along the x/y-axis.

        The origin ``(0, 0)`` is at the top left of the image.

        Parameters
        ----------
        x : number, optional
            Value to be added to all x-coordinates. Positive values shift
            towards the right images.

        y : number, optional
            Value to be added to all y-coordinates. Positive values shift
            towards the bottom images.

        top : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift all objects *from* the
            top (towards the bottom).

        right : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift all objects *from* the
            right (towads the left).

        bottom : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift all objects *from* the
            bottom (towards the top).

        left : None or int, optional
            Deprecated since 0.4.0.
            Amount of pixels by which to shift all objects *from* the
            left (towards the right).

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Shifted bounding boxes.

        ri   r   rj   rk   r   r   r   rl   }  s   )
zBoundingBoxesOnImage.shiftc              	   C   sx   ddl m} tjt| jdftjd}t| jD ]\}}|j|j	|j
|j	|j
|j|j|jg||< q|j|d| jdS )aJ  Convert the bounding boxes to one ``KeypointsOnImage`` instance.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.kps.KeypointsOnImage
            A keypoints instance containing ``N*4`` coordinates for ``N``
            bounding boxes. Order matches the order in ``bounding_boxes``.

        r   )KeypointsOnImage   r   r   r   )Zkpsr   r   r   r   r   r   r   r   r   r   r   Zfrom_xy_arrayr   rN   )r   r   r   r   r   r   r   r   to_keypoints_on_image  s   
z*BoundingBoxesOnImage.to_keypoints_on_imagec                 C   s  t |jt | jd ksJ dt | jd t |jf t| jD ]d\}}|jd| d  j|jd| d  j|jd| d  j|jd| d  jg}|jd| d  j|jd| d  j|jd| d  j|jd| d  jg}t||_t||_t	||_
t	||_q!|j| _| S )aJ  Invert the output of ``to_keypoints_on_image()`` in-place.

        This function writes in-place into this ``BoundingBoxesOnImage``
        instance.

        Added in 0.4.0.

        Parameters
        ----------
        kpsoi : imgaug.augmentables.kps.KeypointsOnImages
            Keypoints to convert back to bounding boxes, i.e. the outputs
            of ``to_keypoints_on_image()``.

        Returns
        -------
        BoundingBoxesOnImage
            Bounding boxes container with updated coordinates.
            Note that the instance is also updated in-place.

        r   z Expected %d coordinates, got %d.r   r   r   r   )r   Z	keypointsr   r   r5   r6   rG   r   r   rF   r   r   rN   )r   Zkpsoir   r   xxyyr   r   r   invert_to_keypoints_on_image_  s$   $$$$


z2BoundingBoxesOnImage.invert_to_keypoints_on_image_c                 C   s*   ddl m} dd | jD }||| jdS )a=  Convert the bounding boxes to one ``PolygonsOnImage`` instance.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.polys.PolygonsOnImage
            A ``PolygonsOnImage`` containing polygons. Each polygon covers
            the same area as the corresponding bounding box.

        r   )PolygonsOnImagec                 S      g | ]}|  qS r   )r   r   r   r   r   r     r   z=BoundingBoxesOnImage.to_polygons_on_image.<locals>.<listcomp>r   )Zpolysr   r   rN   )r   r   Zpolygonsr   r   r   to_polygons_on_image  s   z)BoundingBoxesOnImage.to_polygons_on_imagec                 C   s2   |du r| j dd }|du rt| j}t||S )a_  Create a shallow copy of the ``BoundingBoxesOnImage`` instance.

        Parameters
        ----------
        bounding_boxes : None or list of imgaug.augmntables.bbs.BoundingBox, optional
            List of bounding boxes on the image.
            If ``None``, the instance's bounding boxes will be copied.

        shape : tuple of int, optional
            The shape of the image on which the bounding boxes are placed.
            If ``None``, the instance's shape will be copied.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Shallow copy.

        Nr   r4   rN   r   r   r   r   r   r|     s
   

zBoundingBoxesOnImage.copyc                 C   s4   |du rdd | j D }|du rt| j}t||S )aW  Create a deep copy of the ``BoundingBoxesOnImage`` object.

        Parameters
        ----------
        bounding_boxes : None or list of imgaug.augmntables.bbs.BoundingBox, optional
            List of bounding boxes on the image.
            If ``None``, the instance's bounding boxes will be copied.

        shape : tuple of int, optional
            The shape of the image on which the bounding boxes are placed.
            If ``None``, the instance's shape will be copied.

        Returns
        -------
        imgaug.augmentables.bbs.BoundingBoxesOnImage
            Deep copy.

        Nc                 S   r   r   )r;   r   r   r   r   r   /  r   z1BoundingBoxesOnImage.deepcopy.<locals>.<listcomp>r   r   r   r   r   r;     s
   

zBoundingBoxesOnImage.deepcopyc                 C   r   )zGet the bounding box(es) with given indices.

        Added in 0.4.0.

        Returns
        -------
        list of imgaug.augmentables.bbs.BoundingBoxes
            Bounding box(es) with given indices.

        r   r   r   r   r   r   6  r   z BoundingBoxesOnImage.__getitem__c                 C   r   )a/  Iterate over the bounding boxes in this container.

        Added in 0.4.0.

        Yields
        ------
        BoundingBox
            A bounding box in this container.
            The order is identical to the order in the bounding box list
            provided upon class initialization.

        )r   r   r$   r   r   r   r   C  s   
zBoundingBoxesOnImage.__iter__c                 C   r   )zGet the number of items in this instance.

        Added in 0.4.0.

        Returns
        -------
        int
            Number of items in this instance.

        )r   r   r$   r   r   r   __len__R  r   zBoundingBoxesOnImage.__len__c                 C   r   r   r   r$   r   r   r   r   _  r   zBoundingBoxesOnImage.__repr__c                 C   s   dt | j| jf S )Nz"BoundingBoxesOnImage(%s, shape=%s))strr   rN   r$   r   r   r   r   b  s   zBoundingBoxesOnImage.__str__r   r   r   r   )NN),r   r   r   r   r   r   r   setterr+   r-   r   r   r   r   r   r   r   r   r   r   r   r   rz   r   r   r   r   r   r   ra   rc   r^   rh   rl   r   r   r   r|   r;   r   r   r   r   r   r   r   r   r   r   K  s`    





+
#2

5



- $

r   c                   @   s\   e Zd Z			ddd	Zd
d Zdd Zedd Zdd Zdd Z	edd Z
dd ZdS )ry   rm   Nr   rQ   Frp   ro   c	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S r   rq   )	r   rr   rs   rt   ru   rv   rw   r+   rx   r   r   r   r   k  s   
z_LabelOnImageDrawer.__init__c           
   
   C   s   | j r	| || |  \}}| ||\}}}}||ks!||kr#|S | |j|| || |jd |j||| j}	| 	||	||||}|S )Nr   )
rw   _do_raise_if_out_of_image_preprocess_colors_compute_bg_corner_coords_draw_label_arrr   rN   r   rx   _blend_label_arr_with_image_)
r   rM   bounding_boxrs   rt   r   r   r   r   	label_arrr   r   r   r{   w  s    z"_LabelOnImageDrawer.draw_on_image_c                 C   s   |  t||S r   )r{   r   r|   )r   rM   r  r   r   r   rz     s   z!_LabelOnImageDrawer.draw_on_imagec                 C   s.   | |rtd|j|j|j|j|jf d S )Nr~   )rY   r   r   r   r   r   rN   )r   rM   r  r   r   r   r     s   
z-_LabelOnImageDrawer._do_raise_if_out_of_imagec                 C   s   | j d urt| j nd }| j}| jd urt|}n
|d us#J d|}| j}| jd ur6t|}||fS d|d  d|d   d|d   }tjd|d	krQdnd
tjd}||fS )NzGExpected `color` to be set when `color_bg` is not set, but it was None.gA`"?r   gbX9?r   gv/?r   )r      rn   r   )rr   r   r   rt   rs   full)r   rr   rt   rs   grayr   r   r   r    s,   






z&_LabelOnImageDrawer._preprocess_colorsc                 C   s   |}| j }|jdd \}}|j|j|j}}}	|d | j }|| j }
|| d }|	| }	t||
gd|d \}}
t||	gd|d \}}	|||	|
fS )Nr   r   r   )ru   rN   r'   r%   r(   r+   r   rb   )r   rM   r  r   offsetr+   r-   r   r   r   r   r   r   r   r    s   
z-_LabelOnImageDrawer._compute_bg_corner_coordsc	           
      C   s@   t j|||f|d}	|d|	d< tj|	ddt|||d}	|	S )Nr   )r   r   r   .r   )r5   r6   textrr   ru   )r   r   r   r   Z	draw_textr   )
r   r   r+   r-   Znb_channelsr   rs   rt   rx   r  r   r   r   r    s   z#_LabelOnImageDrawer._draw_label_arrc                 C   s   | j }|dkr||||||d d f< |S |j}|tj}	|||||d d f tj}
d| |
 ||	  }t|dd|}||||||d d f< |S )Nr   r   r   rn   )rv   r   r   r   Zfloat64rb   )r   rM   r  r   r   r   r   rv   r   
foreground
backgroundblendr   r   r   r    s   "z0_LabelOnImageDrawer._blend_label_arr_with_image_)rm   NNr   rQ   Frp   ro   )r   r   r   r   r{   rz   r   r   r  r  r  r  r   r   r   r   ry   h  s    

	
ry   )r   
__future__r   r   r   r|   numpyr   Zskimage.drawr   Zskimage.measure r   r   baser   utilsr	   r
   r   r   objectr   r   ry   r   r   r   r   <module>   s8              C      #