o
    eR                    @   s   d Z ddlmZmZmZ ddlZddlZddl	Z
ddlZ
ddlZddlmZ ddlmZ ddlmZmZmZmZmZ G d	d
 d
eZG dd deZdddZdd Zdd ZdS )zClasses representing lines.    )print_functiondivisionabsolute_importN   )imgaug   )IAugmentable)normalize_shapeproject_coords_interpolate_points_remove_out_of_image_fraction__normalize_shift_argsc                   @   s  e Zd ZdZdid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diddZdiddZdjddZdd Zd d! Zd"d# Zdkd%d&Zdkd'd(Zdld*d+Zd,d- Zd.d/ Zdmd1d2Zdnd3d4Z	0	$dod6d7Z	8	)	$dpd9d:Z	8	$dqd;d<Z	8	)	$drd=d>Z	?	@	)	$dsdAdBZ 	C	@	$dtdDdEZ!				)	$dudFdGZ"		)dvdHdIZ#dJdK Z$dLdM Z%dNdO Z&dPdQ Z'dRdS Z(	0	$dwdTdUZ)	0	$dodVdWZ*dxdYdZZ+dxd[d\Z,dyd]d^Z-dyd_d`Z.dadb Z/dcdd Z0dedf Z1dgdh Z2dS )z
LineStringai  Class representing line strings.

    A line string is a collection of connected line segments, each
    having a start and end point. Each point is given as its ``(x, y)``
    absolute (sub-)pixel coordinates. The end point of each segment is
    also the start point of the next segment.

    The line string is not closed, i.e. start and end point are expected to
    differ and will not be connected in drawings.

    Parameters
    ----------
    coords : iterable of tuple of number or ndarray
        The points of the line string.

    label : None or str, optional
        The label of the line string.

    Nc                 C   s   t |r|jjdkr|tj}n4t|dkr!tjdtjd}n%t 	|s/J dt
|f tdd |D sAJ dt|f t|}|jd	krR|jd
 d	ksZJ d|jf || _|| _dS )z!Create a new LineString instance.float32r   r   r   dtypez1Expected 'coords' to be an iterable, got type %s.c                 S   s   g | ]}t |d kqS )r   len).0Zcoords_i r   ID:\Projects\ConvertPro\env\Lib\site-packages\imgaug/augmentables/lines.py
<listcomp>9       z'LineString.__init__.<locals>.<listcomp>z2Expected 'coords' to contain (x,y) tuples, got %s.r   z5Expected 'coords' to have shape (N, 2), got shape %s.N)iaZis_np_arrayr   nameastypenpr   r   zerosis_iterabletypeallstrndimshapecoordslabelselfr&   r'   r   r   r   __init__-   s0   


zLineString.__init__c                 C   s    t | jdkr	dS t|  S )zCompute the total euclidean length of the line string.

        Returns
        -------
        float
            The length based on euclidean distance, i.e. the sum of the
            lengths of each line segment.

        r   )r   r&   r   sumcompute_neighbour_distancesr)   r   r   r   lengthE   s   zLineString.lengthc                 C      | j dddf S )zGet an array of x-coordinates of all points of the line string.

        Returns
        -------
        ndarray
            ``float32`` x-coordinates of the line string points.

        Nr   r&   r-   r   r   r   xxT      
zLineString.xxc                 C   r/   )zGet an array of y-coordinates of all points of the line string.

        Returns
        -------
        ndarray
            ``float32`` y-coordinates of the line string points.

        Nr   r0   r-   r   r   r   yy`   r2   zLineString.yyc                 C      t | jt jS )ax  Get an array of discrete x-coordinates of all points.

        The conversion from ``float32`` coordinates to ``int32`` is done
        by first rounding the coordinates to the closest integer and then
        removing everything after the decimal point.

        Returns
        -------
        ndarray
            ``int32`` x-coordinates of the line string points.

        )r   roundr1   r   int32r-   r   r   r   xx_intl      zLineString.xx_intc                 C   r4   )ax  Get an array of discrete y-coordinates of all points.

        The conversion from ``float32`` coordinates to ``int32`` is done
        by first rounding the coordinates to the closest integer and then
        removing everything after the decimal point.

        Returns
        -------
        ndarray
            ``int32`` y-coordinates of the line string points.

        )r   r5   r3   r   r6   r-   r   r   r   yy_int|   r8   zLineString.yy_intc                 C   *   t | jdkr	dS t| jt| j S )a  Compute the height of a bounding box encapsulating the line.

        The height is computed based on the two points with lowest and
        largest y-coordinates.

        Returns
        -------
        float
            The height of the line string.

        r   r   )r   r&   r   maxr3   minr-   r   r   r   height      zLineString.heightc                 C   r:   )a  Compute the width of a bounding box encapsulating the line.

        The width is computed based on the two points with lowest and
        largest x-coordinates.

        Returns
        -------
        float
            The width of the line string.

        r   r   )r   r&   r   r;   r1   r<   r-   r   r   r   width   r>   zLineString.widthc                 C   sp   t | jdkrtjdtdS t|}|dd \}}td| jk| j|k }td| jk| j|k }t||S )a  Determine per point whether it is inside of a given image plane.

        Parameters
        ----------
        image : ndarray or tuple of int
            Either an image with shape ``(H,W,[C])`` or a ``tuple`` denoting
            such an image shape.

        Returns
        -------
        ndarray
            ``(N,) ``bool`` array with one value for each of the ``N`` points
            indicating whether it is inside of the provided image
            plane (``True``) or not (``False``).

        r   r   r   r   )	r   r&   r   r   boolr	   logical_andr1   r3   )r)   imager%   r=   r?   Zx_withinZy_withinr   r   r   get_pointwise_inside_image_mask   s   z*LineString.get_pointwise_inside_image_maskc                 C   s^   t | jdkrtjdtjdS ttj| jddddf | jddddf  d ddS )zCompute the euclidean distance between each two consecutive points.

        Returns
        -------
        ndarray
            ``(N-1,)`` ``float32`` array of euclidean distances between point
            pairs. Same order as in `coords`.

        r   r@   r   Nr   r   Zaxis)r   r&   r   r   r   sqrtr+   r-   r   r   r   r,      s   
.z&LineString.compute_neighbour_distancesc                    s   ddl ddlm} t |rj j jf nOt trEt	 j
dkr(|S t	 j
dkr=j j
dddf  n,j j
 n$t tr`t	 dksYJ dt	 f j  n	tdt f  fdd	| j
D S )
aR  Compute min distances between points of this and another line string.

        Parameters
        ----------
        other : tuple of number or imgaug.augmentables.kps.Keypoint or imgaug.augmentables.LineString
            Other object to which to compute the distances.

        default : any
            Value to return if `other` contains no points.

        Returns
        -------
        list of float or any
            For each coordinate of this line string, the distance to any
            closest location on `other`.
            `default` if no distance could be computed.

        r   Nr   Keypointr   z>Expected tuple 'other' to contain exactly two entries, got %d.z<Expected Keypoint or LineString or tuple (x,y), got type %s.c                    s   g | ]}j | qS r   )geometryPointZdistance)r   pointothershapelyr   r   r     s    z:LineString.compute_pointwise_distances.<locals>.<listcomp>)shapely.geometrykpsrH   
isinstancerI   rJ   xyr   r   r&   tuple
ValueErrorr!   )r)   rM   defaultrH   r   rL   r   compute_pointwise_distances   s2   


z&LineString.compute_pointwise_distancesc                 C   s&   | j |g d}t|dkr|S t|S )a  Compute the minimal distance between the line string and `other`.

        Parameters
        ----------
        other : tuple of number or imgaug.augmentables.kps.Keypoint or imgaug.augmentables.LineString
            Other object to which to compute the distance.

        default : any
            Value to return if this line string or `other` contain no points.

        Returns
        -------
        float or any
            Minimal distance to `other` or `default` if no distance could be
            computed.

        rV   r   )rW   r   r<   )r)   rM   rV   Z	distancesr   r   r   compute_distance	  s   zLineString.compute_distance-C6?c                 C   s   | j |tjd|k S )a  Estimate whether a point is on this line string.

        This method uses a maximum distance to estimate whether a point is
        on a line string.

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

        max_distance : float
            Maximum allowed euclidean distance between the point and the
            closest point on the line. If the threshold is exceeded, the point
            is not considered to fall on the line.

        Returns
        -------
        bool
            ``True`` if the point is on the line string, ``False`` otherwise.

        rX   )rY   r   inf)r)   rM   max_distancer   r   r   contains#  s   zLineString.containsc                 C   s   t | j||| _| S )a  Project the line string onto a differently shaped image in-place.

        E.g. if a point of the line string is on its original image at
        ``x=(10 of 100 pixels)`` and ``y=(20 of 100 pixels)`` and is projected
        onto a new image with size ``(width=200, height=200)``, its new
        position will be ``(x=20, y=40)``.

        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.lines.LineString
            Line string with new coordinates.
            The object may have been modified in-place.

        )r
   r&   r)   Z
from_shapeZto_shaper   r   r   project_;  s   zLineString.project_c                 C   s   |   ||S )aL  Project the line string onto a differently shaped image.

        E.g. if a point of the line string is on its original image at
        ``x=(10 of 100 pixels)`` and ``y=(20 of 100 pixels)`` and is projected
        onto a new image with size ``(width=200, height=200)``, its new
        position will be ``(x=20, y=40)``.

        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.lines.LineString
            Line string with new coordinates.

        )deepcopyr_   r^   r   r   r   projectZ  s   zLineString.projectc                 C   sj   | j }|dkrt| jdkrdS | | }t|rdS dS | |}tdd |D }|| }d| S )a  Compute fraction of polygon area outside of the image plane.

        This estimates ``f = A_ooi / A``, where ``A_ooi`` is the area of the
        polygon 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 polygon area that is outside of the image
            plane. Returns ``0.0`` if the polygon is fully inside of
            the image plane. If the polygon has an area of zero, the polygon
            is treated similarly to a :class:`LineString`, i.e. the fraction
            of the line that is inside the image plane is returned.

        r                 ?c                 S      g | ]}|j qS r   )r.   r   lsr   r   r   r         z<LineString.compute_out_of_image_fraction.<locals>.<listcomp>)r.   r   r&   rD   r   r"   clip_out_of_imager+   )r)   rC   r.   Z
points_ooiZlss_clippedZlength_after_clipZinside_image_factorr   r   r   compute_out_of_image_fractionu  s   
z(LineString.compute_out_of_image_fractionFc                 C   s"   t | jdkr	|S t| |S )aQ  Estimate whether the line string is fully inside an image plane.

        Parameters
        ----------
        image : ndarray or tuple of int
            Either an image with shape ``(H,W,[C])`` or a ``tuple`` denoting
            such an image shape.

        default : any
            Default value to return if the line string contains no points.

        Returns
        -------
        bool or any
            ``True`` if the line string is fully inside the image area.
            ``False`` otherwise.
            Will return `default` if this line string contains no points.

        r   )r   r&   r   r"   rD   )r)   rC   rV   r   r   r   is_fully_within_image  s   z LineString.is_fully_within_imagec                 C   s<   t | jdkr	|S | |}t|rdS t | |dkS )ao  
        Estimate whether the line string is at least partially inside the image.

        Parameters
        ----------
        image : ndarray or tuple of int
            Either an image with shape ``(H,W,[C])`` or a ``tuple`` denoting
            such an image shape.

        default : any
            Default value to return if the line string contains no points.

        Returns
        -------
        bool or any
            ``True`` if the line string is at least partially inside the image
            area. ``False`` otherwise.
            Will return `default` if this line string contains no points.

        r   T)r   r&   rD   r   anyrh   )r)   rC   rV   maskr   r   r   is_partly_within_image  s   

z!LineString.is_partly_within_imageTc                 C   s2   t | jdkr	|S | |rdS | |r|S |S )a  
        Estimate whether the line is partially/fully outside of the image area.

        Parameters
        ----------
        image : ndarray or tuple of int
            Either an image with shape ``(H,W,[C])`` or a tuple denoting
            such an image shape.

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

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

        default : any
            Default value to return if the line string contains no points.

        Returns
        -------
        bool or any
            ``True`` if the line string is partially/fully outside of the image
            area, depending on defined parameters.
            ``False`` otherwise.
            Will return `default` if this line string contains no points.

        r   F)r   r&   rj   rm   )r)   rC   fullypartlyrV   r   r   r   is_out_of_image  s   

zLineString.is_out_of_imagec                     s
  t  jdkr	g S  |}| }t  jdkr$t|sg S   gS t|r.  gS t|dd \}}d}td|| dfgt|| df|| || fgt|| || fd|| fgtd|| fdgg} 	|}g }	t
t jdd  jdd |dd |dd |}
|
D ]3\}\}}}}}|	|d	|f |D ]
}|	|d
d	f q|t  jd k}|r|s|	|d	|f qg }g }t
|	D ]\}\}}}|rt |dkr|| g }q|s|| q|t |	d k}| ot|	|d  d d
u }t |dkr|d nd}d}|s!|s!|	|d  d }d}d}|dur8tjt|t| }|durKtjt|t| }|du pS|dk}|du p\|dk}|rh|rh|| qt |dkru|| dd |D } fdd|D S )a  Clip off all parts of the line string that are outside of the image.

        Parameters
        ----------
        image : ndarray or tuple of int
            Either an image with shape ``(H,W,[C])`` or a ``tuple`` denoting
            such an image shape.

        Returns
        -------
        list of imgaug.augmentables.lines.LineString
            Line strings, clipped to the image shape.
            The result may contain any number of line strins, including zero.

        r   r   r   gMbP?)rb   rb   rb   Nr   FTg{Gz?c                 S   s   g | ]
}t |d kr|qS r@   r   r   liner   r   r   r   e      z0LineString.clip_out_of_image.<locals>.<listcomp>c                    s   g | ]} j |d qS )r0   r`   rq   r-   r   r   r   f  r   )r   r&   rD   r   rk   copyr"   r	   r   find_intersections_with	enumeratezipappendrA   linalgnormr   ) r)   rC   Zinside_image_maskZooi_maskr=   r?   epsedgesintersectionsZpointsgeni
line_startline_endZ	ooi_startZooi_endZ
inter_lineZp_interZis_lastlinesrr   coordZ	was_addedZooiZis_last_pointZis_next_ooiZp_prevZp_nextZ	dist_prevZ	dist_nextZdist_prev_okZdist_next_okr   r-   r   rh     s   











zLineString.clip_out_of_imagec                 C   s,  ddl }t|}g }t| jdd | jdd D ]z\}}|j||g}||}tt|}g }	|D ]O}
t	|
|jj
jrit|
jdkrh|
jd d |
jd d f}|
jd d |
jd d f}|	||g q4t	|
|jjjszJ dt|
f |	|
j|
jf q4t|	|fddd}|| q|S )	a&  Find all intersection points between this line string and `other`.

        Parameters
        ----------
        other : tuple of number or list of tuple of number or list of LineString or LineString
            The other geometry to use during intersection tests.

        Returns
        -------
        list of list of tuple of number
            All intersection points. One list per pair of consecutive start
            and end point, i.e. `N-1` lists of `N` points. Each list may
            be empty or may contain multiple points.

        r   Nr   r   zxExpected to find shapely.geometry.point.Point or shapely.geometry.linestring.LineString intersection, actually found %s.c                 S   s   t jt | | S Nr   rz   r{   r   )pZpsr   r   r   <lambda>      z4LineString.find_intersections_with.<locals>.<lambda>)key)rO    _convert_var_to_shapely_geometryrx   r&   rI   r   intersectionlist_flatten_shapely_collectionrQ   Z
linestringr   extendrK   rJ   r!   ry   rR   rS   sorted)r)   rM   rN   geomresultZp_startZp_endrf   r~   Zintersections_pointsinterZinter_startZ	inter_endZinter_sortedr   r   r   rv   j  s6   &

z"LineString.find_intersections_withr   c                 C   s8   | j dddf  |7  < | j dddf  |7  < | S )a  Move this line string 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
        -------
        result : imgaug.augmentables.lines.LineString
            Shifted line string.
            The object may have been modified in-place.

        Nr   r   r0   )r)   rR   rS   r   r   r   shift_  s   zLineString.shift_c                 C   *   t ||||||d\}}|  j||dS )a  Move this line string 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
        -------
        result : imgaug.augmentables.lines.LineString
            Shifted line string.

        toprightbottomleftrR   rS   r   r`   r   r)   rR   rS   r   r   r   r   r   r   r   shift     )
zLineString.shiftr   c              	   C   s    | j |dd||d|d}|dkS )a  Draw this line segment as a binary image mask.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the line mask.

        size_lines : int, optional
            Thickness of the line segments.

        size_points : int, optional
            Size of the points in pixels.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            Boolean line mask of shape `image_shape` (no channel axis).

        rc   F)alpha_linesalpha_points
size_linessize_pointsantialiasedraise_if_out_of_image      ?)draw_heatmap_array)r)   image_shaper   r   r   heatmapr   r   r   	draw_mask  s   zLineString.draw_maskrc   c                 C   sd   t |dkst |dkr|d dksJ d|f | jtj|tjdd||||d}|tjd	 S )
a  Draw the line segments of this line string as a heatmap array.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the line mask.

        alpha : float, optional
            Opacity of the line string. Higher values denote a more visible
            line string.

        size : int, optional
            Thickness of the line segments.

        antialiased : bool, optional
            Whether to draw the line with anti-aliasing activated.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            ``float32`` array of shape `image_shape` (no channel axis) with
            drawn line string. All values are in the interval ``[0.0, 1.0]``.

        r      r   r   1Expected (H,W) or (H,W,1) as image_shape, got %s.r      coloralphasizer   r        o@)r   draw_lines_on_imager   r   uint8r   r   )r)   r   r   r   r   r   arrr   r   r   draw_lines_heatmap_array  s    z#LineString.draw_lines_heatmap_arrayc                 C   sb   t |dkst |dkr|d dksJ d|f | jtj|tjdd|||d}|tjd	 S )
a  Draw the points of this line string as a heatmap array.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the point mask.

        alpha : float, optional
            Opacity of the line string points. Higher values denote a more
            visible points.

        size : int, optional
            Size of the points in pixels.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            ``float32`` array of shape `image_shape` (no channel axis) with
            drawn line string points. All values are in the
            interval ``[0.0, 1.0]``.

        r   r   r   r   r   r   r   )r   r   r   r   r   )r   draw_points_on_imager   r   r   r   r   )r)   r   r   r   r   r   r   r   r   draw_points_heatmap_array9  s   z$LineString.draw_points_heatmap_arrayc                 C   sN   | j |||||d}|dkr|S | j||||d}	t||	g}
tj|
ddS )a  
        Draw the line segments and points of the line string as a heatmap array.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the line mask.

        alpha_lines : float, optional
            Opacity of the line string. Higher values denote a more visible
            line string.

        alpha_points : float, optional
            Opacity of the line string points. Higher values denote a more
            visible points.

        size_lines : int, optional
            Thickness of the line segments.

        size_points : int, optional
            Size of the points in pixels.

        antialiased : bool, optional
            Whether to draw the line with anti-aliasing activated.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            ``float32`` array of shape `image_shape` (no channel axis) with
            drawn line segments and points. All values are in the
            interval ``[0.0, 1.0]``.

        )r   r   r   r   r   )r   r   r   r   rE   )r   r   r   Zdstackr;   )r)   r   r   r   r   r   r   r   Zheatmap_linesZheatmap_pointsr   r   r   r   r   b  s"   )zLineString.draw_heatmap_arrayr   r   r   r   c                 C   s  ddl m} ddlm} d}	t|trd}	tj|tjd}|j	dv s*J d|j
f t| jd	ks9|d
k s9|d	k r>t|S |rS| j|dddrStd|  |j
f |j	dkrjt|sfJ dt|f |g}n|j	dkr|t|r||g|j
d  }|tj}|j
dd \}
}g }t| jdd | jd	d D ]\}}||d	 |d |d	 |d f qtt|tj}t|}tj|j
dd tjd}|D ]T}|rtjj| \}}}n
tjj| \}}d}td|k||
k }td|k||k }t||}t|r&|| }|| }t|s|| n|}|| |||f< q|d	kr<tj ||ftjd}t!"||}|	rF|||  }n|j
dd }|j	dkrW|d }t#||}|$|||}|%|tj}|S )a  Draw the line segments of this line string on a given image.

        Parameters
        ----------
        image : ndarray or tuple of int
            The image onto which to draw.
            Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``
            usually being ``3`` (other values are not tested).
            If a tuple, expected to be ``(H, W, C)`` and will lead to a new
            ``uint8`` array of zeros being created.

        color : int or iterable of int
            Color to use as RGB, i.e. three values.

        alpha : float, optional
            Opacity of the line string. Higher values denote a more visible
            line string.

        size : int, optional
            Thickness of the line segments.

        antialiased : bool, optional
            Whether to draw the line with anti-aliasing activated.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            `image` with line drawn on it.

        r   dtypes)blendFTr   r   r   z?Expected image or shape of form (H,W) or (H,W,C), got shape %s.r   rZ   )ro   rn   zWCannot draw line string '%s' on image with shape %s, because it would be out of bounds.zHGot a 2D image. Expected then 'color' to be a single number, but got %s.r   r   r   Nrc   )r   )& r   Z
augmentersr   rQ   rT   r   r   r   r$   r%   r   r&   ru   rp   	Exception__str__r   Zis_single_numberr#   r   r   rx   ry   r5   r6   skimageZdrawZline_aarr   rB   rk   Zonescv2ZdilateZtileZblend_alpharestore_dtypes_)r)   rC   r   r   r   r   r   iadtZblendlibZimage_was_emptyr=   r?   r   r   r   r   rr   rrccvalZrr_maskZcc_maskrl   ZkernelZimage_blendZimage_color_shapeZimage_colorr   r   r   r     s   (



&

zLineString.draw_lines_on_imager      r   c           	      C   s8   ddl m} |j| j|jd}|j||||||d}|S )a  Draw the points of this line string onto a given image.

        Parameters
        ----------
        image : ndarray or tuple of int
            The image onto which to draw.
            Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``
            usually being ``3`` (other values are not tested).
            If a tuple, expected to be ``(H, W, C)`` and will lead to a new
            ``uint8`` array of zeros being created.

        color : iterable of int
            Color to use as RGB, i.e. three values.

        alpha : float, optional
            Opacity of the line string points. Higher values denote a more
            visible points.

        size : int, optional
            Size of the points in pixels.

        copy : bool, optional
            Whether it is allowed to draw directly in the input
            array (``False``) or it has to be copied (``True``).
            The routine may still have to copy, even if ``copy=False`` was
            used. Always use the return value.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            ``float32`` array of shape `image_shape` (no channel axis) with
            drawn line string points. All values are in the
            interval ``[0.0, 1.0]``.

        r   KeypointsOnImager%   r   r   r   ru   r   )rP   r   from_xy_arrayr&   r%   draw_on_image)	r)   rC   r   r   r   ru   r   r   kpsoir   r   r   r     s   +zLineString.draw_points_on_imagec                 C   s   dd }|d| |d| |d| |dur|nt |}|dur$|nt |d }|dur1|nt |}|dur<|nt |}|	durG|	n|}	|
durO|
n|d }
| j|t |t j||	||d	}| j|t |t j||
d
|d}|S )a`	  Draw this line string onto an image.

        Parameters
        ----------
        image : ndarray
            The `(H,W,C)` `uint8` image onto which to draw the line string.

        color : iterable of int, optional
            Color to use as RGB, i.e. three values.
            The color of the line and points are derived from this value,
            unless they are set.

        color_lines : None or iterable of int
            Color to use for the line segments as RGB, i.e. three values.
            If ``None``, this value is derived from `color`.

        color_points : None or iterable of int
            Color to use for the points as RGB, i.e. three values.
            If ``None``, this value is derived from ``0.5 * color``.

        alpha : float, optional
            Opacity of the line string. Higher values denote more visible
            points.
            The alphas of the line and points are derived from this value,
            unless they are set.

        alpha_lines : None or float, optional
            Opacity of the line string. Higher values denote more visible
            line string.
            If ``None``, this value is derived from `alpha`.

        alpha_points : None or float, optional
            Opacity of the line string points. Higher values denote more
            visible points.
            If ``None``, this value is derived from `alpha`.

        size : int, optional
            Size of the line string.
            The sizes of the line and points are derived from this value,
            unless they are set.

        size_lines : None or int, optional
            Thickness of the line segments.
            If ``None``, this value is derived from `size`.

        size_points : None or int, optional
            Size of the points in pixels.
            If ``None``, this value is derived from ``3 * size``.

        antialiased : bool, optional
            Whether to draw the line with anti-aliasing activated.
            This does currently not affect the point drawing.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        ndarray
            Image with line string drawn on it.

        c                 S   s    |d usJ d| t |f d S )Nz*Expected '%s' to not be None, got type %s.)r!   )Zarg_name	arg_valuer   r   r   _assert_not_none  s
   
z2LineString.draw_on_image.<locals>._assert_not_noner   r   r   Nr   r   r   Fr   )r   r   r   arrayr   r   r   )r)   rC   r   color_linescolor_pointsr   r   r   r   r   r   r   r   r   r   r   r   r   R  s>   F


zLineString.draw_on_imagec                 C   sr  ddl m} |jdv sJ d|jf t| jdks|dkr>|r/tjd|jdd  |jd	S tjd
|jdd  |jd	S | j	}| j
}	|d d }
t||
 }t|	|
 }t|d |
 }t|	d |
 }|||||d}t| jdkr|j||||dS | j|jdd d||d}|jdkrt|}|tj| }|j||||d}tt|ddtjS )a  Extract all image pixels covered by the line string.

        This will only extract pixels overlapping with the line string.
        As a rectangular image array has to be returned, non-overlapping
        pixels will be set to zero.

        This function will by default zero-pad the image if the line string is
        partially/fully outside of the image. This is for consistency with
        the same methods for bounding boxes and polygons.

        Parameters
        ----------
        image : ndarray
            The image of shape `(H,W,[C])` from which to extract the pixels
            within the line string.

        size : int, optional
            Thickness of the line.

        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.

        antialiased : bool, optional
            Whether to apply anti-aliasing to the line string.

        prevent_zero_size : bool, optional
            Whether to prevent height or width of the extracted image from
            becoming zero. If this is set to ``True`` and height or width of
            the line string 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 overlapping with the line string. Zero-padded if the
            line string is partially/fully outside of the image and
            ``pad=True``. If `prevent_zero_size` is activated, it is
            guarantueed that ``H'>0`` and ``W'>0``, otherwise only
            ``H'>=0`` and ``W'>=0``.

        r   BoundingBoxr   z0Expected image of shape (H,W,[C]), got shape %s.r   )r   r   r   Nr   r   r   )x1y1x2y2)padpad_maxprevent_zero_sizerc   )r   r   r   r   r   )bbsr   r$   r%   r   r&   r   r   r   r7   r9   r<   r;   extract_from_imager   Z
atleast_3dr   r   Zclipr5   r   )r)   rC   r   r   r   r   r   r   r1   r3   Zsizehr   r   r   r   Zbbr   Zimage_maskedextractr   r   r   r     s@   6	



zLineString.extract_from_imagec                 C   s0   t |ts	t|}| jtj| j|jgdddS )a'  Concatenate this line string with another one.

        This will add a line segment between the end point of this line string
        and the start point of `other`.

        Parameters
        ----------
        other : imgaug.augmentables.lines.LineString or ndarray or iterable of tuple of number
            The points to add to this line string.

        Returns
        -------
        imgaug.augmentables.lines.LineString
            New line string with concatenated points.
            The `label` of this line string will be kept.

        r   rE   r0   )rQ   r   r`   r   concatenater&   )r)   rM   r   r   r   r     s
   
zLineString.concatenatec                 C   s:   t | jdks|dk r|  S t| j|dd}| j|dS )a;  Derive a new line string with ``N`` interpolated points per edge.

        The interpolated points have (per edge) regular distances to each
        other.

        For each edge between points ``A`` and ``B`` this adds points
        at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
        point and ``N`` is the number of points to add per edge.

        Calling this method two times will split each edge at its center
        and then again split each newly created edge at their center.
        It is equivalent to calling `subdivide(3)`.

        Parameters
        ----------
        points_per_edge : int
            Number of points to interpolate on each edge.

        Returns
        -------
        imgaug.augmentables.lines.LineString
            Line string with subdivided edges.

        r   F)Znb_stepsclosedr0   )r   r&   r`   r   )r)   points_per_edger&   r   r   r   	subdivide3  s   zLineString.subdividec                    s    ddl m   fdd| jD S )zConvert the line string points to keypoints.

        Returns
        -------
        list of imgaug.augmentables.kps.Keypoint
            Points of the line string as keypoints.

        r   rG   c                    s   g | ]
\}} ||d qS )r   r   r   rR   rS   rG   r   r   r   ]  rs   z+LineString.to_keypoints.<locals>.<listcomp>)Zimgaug.augmentables.kpsrH   r&   r-   r   rG   r   to_keypointsR  s   
zLineString.to_keypointsc                 C   sR   ddl m} t| jdkrdS |t| jt| jt| jt| j| j	dS )a
  Generate a bounding box encapsulating the line string.

        Returns
        -------
        None or imgaug.augmentables.bbs.BoundingBox
            Bounding box encapsulating the line string.
            ``None`` if the line string contained no points.

        r   r   r   N)r   r   r   r   r'   )
r   r   r   r&   r   r<   r1   r3   r;   r'   )r)   r   r   r   r   to_bounding_box_  s   
zLineString.to_bounding_boxc                 C   s   ddl m} || j| jdS )aH  Generate a polygon from the line string points.

        Returns
        -------
        imgaug.augmentables.polys.Polygon
            Polygon with the same corner points as the line string.
            Note that the polygon might be invalid, e.g. contain less
            than ``3`` points or have self-intersections.

        r   )Polygon)r'   )Zpolysr   r&   r'   )r)   r   r   r   r   
to_polygonr  s   zLineString.to_polygonc                 C   s(   ddl m} || j|||||d|dS )a  Generate a heatmap object from the line string.

        This is similar to
        :func:`~imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`,
        executed with ``alpha=1.0``. The result is wrapped in a
        :class:`~imgaug.augmentables.heatmaps.HeatmapsOnImage` object instead
        of just an array. No points are drawn.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the line mask.

        size_lines : int, optional
            Thickness of the line.

        size_points : int, optional
            Size of the points in pixels.

        antialiased : bool, optional
            Whether to draw the line with anti-aliasing activated.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        imgaug.augmentables.heatmaps.HeatmapsOnImage
            Heatmap object containing drawn line string.

        r   )HeatmapsOnImage)r   r   r   r   r   )Zheatmapsr   r   )r)   r   r   r   r   r   r   r   r   r   
to_heatmap  s   #zLineString.to_heatmapc                 C   s&   ddl m} || j||||d|dS )a  Generate a segmentation map object from the line string.

        This is similar to
        :func:`~imgaug.augmentables.lines.LineString.draw_mask`.
        The result is wrapped in a ``SegmentationMapsOnImage`` object
        instead of just an array.

        Parameters
        ----------
        image_shape : tuple of int
            The shape of the image onto which to draw the line mask.

        size_lines : int, optional
            Thickness of the line.

        size_points : int, optional
            Size of the points in pixels.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if the line string 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
        -------
        imgaug.augmentables.segmaps.SegmentationMapsOnImage
            Segmentation map object containing drawn line string.

        r   )SegmentationMapsOnImage)r   r   r   r   )Zsegmapsr   r   )r)   r   r   r   r   r   r   r   r   to_segmentation_map  s   zLineString.to_segmentation_map   c           	      C   s   t |trnt |trt|g}nt|}t| jdkr%t|jdkr%dS dt| jt|jfv r3dS | |}||}||}||}tt|t|}||k S )a  Compare this and another LineString's coordinates.

        This is an approximate method based on pointwise distances and can
        in rare corner cases produce wrong outputs.

        Parameters
        ----------
        other : imgaug.augmentables.lines.LineString or tuple of number or ndarray or list of ndarray or list of tuple of number
            The other line string or its coordinates.

        max_distance : float, optional
            Max distance of any point from the other line string before
            the two line strings are evaluated to be unequal.

        points_per_edge : int, optional
            How many points to interpolate on each edge.

        Returns
        -------
        bool
            Whether the two LineString's coordinates are almost identical,
            i.e. the max distance is below the threshold.
            If both have no coordinates, ``True`` is returned.
            If only one has no coordinates, ``False`` is returned.
            Beyond that, the number of points is not evaluated.

        r   TF)	rQ   r   rT   r   r&   r   rW   r;   r   )	r)   rM   r\   r   Z	self_subdZ
other_subdZdist_self2otherZdist_other2selfdistr   r   r   coords_almost_equals  s   





zLineString.coords_almost_equalsc                 C   s    | j |j krdS | j|||dS )a  Compare this and another line string.

        Parameters
        ----------
        other: imgaug.augmentables.lines.LineString
            The other object to compare against. Expected to be a
            ``LineString``.

        max_distance : float, optional
            See :func:`~imgaug.augmentables.lines.LineString.coords_almost_equals`.

        points_per_edge : int, optional
            See :func:`~imgaug.augmentables.lines.LineString.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   )r)   rM   r\   r   r   r   r   almost_equals  s
   zLineString.almost_equalsc                 C   s,   t |du r| jn||du r| jdS |dS )a  Create a shallow copy of this line string.

        Parameters
        ----------
        coords : None or iterable of tuple of number or ndarray
            If not ``None``, then the coords of the copied object will be set
            to this value.

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

        Returns
        -------
        imgaug.augmentables.lines.LineString
            Shallow copy.

        Nr&   r'   )r   r&   r'   r(   r   r   r   ru      s
   zLineString.copyc                 C   s8   t |du rt| jn||du rt| jdS |dS )a  Create a deep copy of this line string.

        Parameters
        ----------
        coords : None or iterable of tuple of number or ndarray
            If not ``None``, then the coords of the copied object will be set
            to this value.

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

        Returns
        -------
        imgaug.augmentables.lines.LineString
            Deep copy.

        Nr   )r   r   ru   r&   copylibr`   r'   r(   r   r   r   r`   6  s   zLineString.deepcopyc                 C   
   | j | S )zGet the coordinate(s) with given indices.

        Added in 0.4.0.

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

        r0   r)   indicesr   r   r   __getitem__M     
zLineString.__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__Z  r   zLineString.__iter__c                 C      |   S r   r   r-   r   r   r   __repr__g     zLineString.__repr__c                 C   s$   d dd | jD }d|| jf S )N, c                 S   s   g | ]
\}}d ||f qS )z(%.2f, %.2f)r   r   r   r   r   r   l  rs   z&LineString.__str__.<locals>.<listcomp>zLineString([%s], label=%s))joinr&   r'   )r)   Z
points_strr   r   r   r   j  s   zLineString.__str__r   rZ   )F)TFTr   r   r   NNNN)r   r   F)rc   r   TF)rc   r   F)rc   rc   r   r   TF)r   rc   r   TF)r   rc   r   TFr   NNrc   NNr   NNTF)r   TNTT)r   r   TF)rZ   r   NN)3__name__
__module____qualname____doc__r*   propertyr.   r1   r3   r7   r9   r=   r?   rD   r,   rW   rY   r]   r_   ra   ri   rj   rm   rp   rh   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   r`   r   r   r   r   r   r   r   r   r      s    









,

&

'r
7
-
"
-
)
=

5
j
_
,

(
1

r   c                   @   s   e Zd ZdZdd Zedd Zejdd Zedd Zd	d
 Z	dd Z
edd ZejfddZ					d@ddZdAddZdAddZdd Zdd  Zd!d" Zd#d$ ZdBd&d'ZdCd(d)Zd*d+ Zd,d- Zd.d/ Zd0d1 ZdDd2d3ZdDd4d5Zd6d7 Zd8d9 Z d:d; Z!d<d= Z"d>d? Z#dS )ELineStringsOnImagea  Object that represents all line strings on a single image.

    Parameters
    ----------
    line_strings : list of imgaug.augmentables.lines.LineString
        List of line strings 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.lines import LineString, LineStringsOnImage
    >>>
    >>> image = np.zeros((100, 100))
    >>> lss = [
    >>>     LineString([(0, 0), (10, 0)]),
    >>>     LineString([(10, 20), (30, 30), (50, 70)])
    >>> ]
    >>> lsoi = LineStringsOnImage(lss, shape=image.shape)

    c                 C   s^   t |sJ dt|f tdd |D s%J dddd |D  || _t|| _d S )Nz9Expected 'line_strings' to be an iterable, got type '%s'.c                 S      g | ]}t |tqS r   rQ   r   r   vr   r   r   r     r   z/LineStringsOnImage.__init__.<locals>.<listcomp>z/Expected iterable of LineString, got types: %s.r  c                 S      g | ]}t t|qS r   r#   r!   r  r   r   r   r     r   )r   r    r!   r"   r  line_stringsr	   r%   r)   r  r%   r   r   r   r*     s   zLineStringsOnImage.__init__c                 C   s   | j S )zGet the line strings in this container.

        Added in 0.4.0.

        Returns
        -------
        list of LineString
            Line strings within this container.

        r  r-   r   r   r   items  s   zLineStringsOnImage.itemsc                 C   s
   || _ dS )zSet the line strings in this container.

        Added in 0.4.0.

        Parameters
        ----------
        value : list of LineString
            Line strings within this container.

        Nr  )r)   valuer   r   r   r    s   
c                 C   s   t | jdkS )zEstimate whether this object contains zero line strings.

        Returns
        -------
        bool
            ``True`` if this object contains zero line strings.

        r   )r   r  r-   r   r   r   empty  s   
zLineStringsOnImage.emptyc                 C   s^   t |}|dd | jdd kr|| _| S t| jD ]\}}|| j|| j|< q|| _| S )a   Project the line strings from one image shape to a new one in-place.

        Added in 0.4.0.

        Parameters
        ----------
        image : ndarray or tuple of int
            The new image onto which to project.
            Either an image with shape ``(H,W,[C])`` or a tuple denoting
            such an image shape.

        Returns
        -------
        imgaug.augmentables.lines.LineStrings
            Object containing all projected line strings.
            The object and its items may have been modified in-place.

        r   r   )r	   r%   rw   r  r_   r  )r)   rC   Zon_shaper   itemr   r   r   on_  s   zLineStringsOnImage.on_c                 C      |   |S )a  Project the line strings from one image shape to a new one.

        Parameters
        ----------
        image : ndarray or tuple of int
            The new image onto which to project.
            Either an image with shape ``(H,W,[C])`` or a tuple denoting
            such an image shape.

        Returns
        -------
        imgaug.augmentables.lines.LineStrings
            Object containing all projected line strings.

        )r`   r  )r)   rC   r   r   r   on  s   zLineStringsOnImage.onc                 C   s&   g }|D ]	}| t| q| ||S )ag  Convert an ``(N,M,2)`` ndarray to a ``LineStringsOnImage`` object.

        This is the inverse of
        :func:`~imgaug.augmentables.lines.LineStringsOnImage.to_xy_array`.

        Parameters
        ----------
        xy : (N,M,2) ndarray or iterable of (M,2) ndarray
            Array containing the point coordinates ``N`` line strings
            with each ``M`` points given as ``(x,y)`` coordinates.
            ``M`` may differ if an iterable of arrays is used.
            Each array should usually be of dtype ``float32``.

        shape : tuple of int
            ``(H,W,[C])`` shape of the image on which the line strings are
            placed.

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Object containing a list of ``LineString`` objects following the
            provided point coordinates.

        )ry   r   )clsxyr%   lssZxy_lsr   r   r   from_xy_arrays  s   
z!LineStringsOnImage.from_xy_arraysc                    s"   ddl m  fdd| jD S )a  Convert this object to an iterable of ``(M,2)`` arrays of points.

        This is the inverse of
        :func:`~imgaug.augmentables.lines.LineStringsOnImage.from_xy_array`.

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

        Returns
        -------
        list of ndarray
            The arrays of point coordinates, each given as ``(M,2)``.

        r   r   c                    s    g | ]} t|j qS r   )r   r   ru   r&   re   r   r   r   r   r   .  s    z3LineStringsOnImage.to_xy_arrays.<locals>.<listcomp>)r   r   r  )r)   r   r   r"  r   to_xy_arrays  s   zLineStringsOnImage.to_xy_arraysr   Nrc   r   TFc                 C   s2   | j D ]}|j|||||||||	|
||d}q|S )az	  Draw all line strings onto a given image.

        Parameters
        ----------
        image : ndarray
            The ``(H,W,C)`` ``uint8`` image onto which to draw the line
            strings.

        color : iterable of int, optional
            Color to use as RGB, i.e. three values.
            The color of the lines and points are derived from this value,
            unless they are set.

        color_lines : None or iterable of int
            Color to use for the line segments as RGB, i.e. three values.
            If ``None``, this value is derived from `color`.

        color_points : None or iterable of int
            Color to use for the points as RGB, i.e. three values.
            If ``None``, this value is derived from ``0.5 * color``.

        alpha : float, optional
            Opacity of the line strings. Higher values denote more visible
            points.
            The alphas of the line and points are derived from this value,
            unless they are set.

        alpha_lines : None or float, optional
            Opacity of the line strings. Higher values denote more visible
            line string.
            If ``None``, this value is derived from `alpha`.

        alpha_points : None or float, optional
            Opacity of the line string points. Higher values denote more
            visible points.
            If ``None``, this value is derived from `alpha`.

        size : int, optional
            Size of the line strings.
            The sizes of the line and points are derived from this value,
            unless they are set.

        size_lines : None or int, optional
            Thickness of the line segments.
            If ``None``, this value is derived from `size`.

        size_points : None or int, optional
            Size of the points in pixels.
            If ``None``, this value is derived from ``3 * size``.

        antialiased : bool, optional
            Whether to draw the lines with anti-aliasing activated.
            This does currently not affect the point drawing.

        raise_if_out_of_image : bool, optional
            Whether to raise an error if a line string 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
        -------
        ndarray
            Image with line strings drawn on it.

        )r   r   r   r   r   r   r   r   r   r   r   )r  r   )r)   rC   r   r   r   r   r   r   r   r   r   r   r   rf   r   r   r   r   1  s   
H	z LineStringsOnImage.draw_on_imagec                    s    fddj D _ S )a  
        Remove all LS that are fully/partially outside of an image in-place.

        Added in 0.4.0.

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

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

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Reduced set of line strings. Those that are fully/partially
            outside of the given image plane are removed.
            The object and its items may have been modified in-place.

        c                    s"   g | ]}|j j d s|qS )rn   ro   )rp   r%   re   rn   ro   r)   r   r   r     s    z;LineStringsOnImage.remove_out_of_image_.<locals>.<listcomp>r  r)   rn   ro   r   r%  r   remove_out_of_image_  s   z'LineStringsOnImage.remove_out_of_image_c                 C   s   |   j||dS )aG  
        Remove all line strings that are fully/partially outside of an image.

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

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

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Reduced set of line strings. Those that are fully/partially
            outside of the given image plane are removed.

        r$  )ru   r'  r&  r   r   r   remove_out_of_image  s   z&LineStringsOnImage.remove_out_of_imagec                 C   s
   t | |S )a  Remove all LS with an OOI fraction of at least `fraction` in-place.

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

        Added in 0.4.0.

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

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Reduced set of line strings, 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   
z0LineStringsOnImage.remove_out_of_image_fraction_c                 C   r  )a{  Remove all LS with an out of image fraction of at least `fraction`.

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

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Reduced set of line strings, with those that had an out of image
            fraction greater or equal the given one removed.

        )ru   r+  r)  r   r   r   remove_out_of_image_fraction  s   z/LineStringsOnImage.remove_out_of_image_fractionc                    s    fdd j D  _  S )a  
        Clip off all parts of the LSs that are outside of an image in-place.

        .. note::

            The result can contain fewer line strings than the input did. That
            happens when a polygon is fully outside of the image plane.

        .. note::

            The result can also contain *more* line strings than the input
            did. That happens when distinct parts of a line string are only
            connected by line segments that are outside of the image plane and
            hence will be clipped off, resulting in two or more unconnected
            line string parts that are left in the image plane.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Line strings, clipped to fall within the image dimensions.
            The count of output line strings may differ from the input count.

        c                    s"   g | ]}|  jD ]}|q
qS r   )rh   r%   )r   rf   Z
ls_clippedr-   r   r   r     s    
z9LineStringsOnImage.clip_out_of_image_.<locals>.<listcomp>r  r-   r   r-   r   clip_out_of_image_  s   
z%LineStringsOnImage.clip_out_of_image_c                 C   s   |    S )as  
        Clip off all parts of the line strings that are outside of an image.

        .. note::

            The result can contain fewer line strings than the input did. That
            happens when a polygon is fully outside of the image plane.

        .. note::

            The result can also contain *more* line strings than the input
            did. That happens when distinct parts of a line string are only
            connected by line segments that are outside of the image plane and
            hence will be clipped off, resulting in two or more unconnected
            line string parts that are left in the image plane.

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Line strings, clipped to fall within the image dimensions.
            The count of output line strings may differ from the input count.

        )ru   r-  r-   r   r   r   rh     s   z$LineStringsOnImage.clip_out_of_imager   c                 C   s,   t | jD ]\}}|j||d| j|< q| S )a  Move the line strings 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.lines.LineStringsOnImage
            Shifted line strings.
            The object and its items may have been modified in-place.

        r   )rw   r  r   )r)   rR   rS   r   rf   r   r   r   r     s   zLineStringsOnImage.shift_c                 C   r   )a  Move the line strings 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.lines.LineStringsOnImage
            Shifted line strings.

        r   r   r   r   r   r   r   r   :  r   zLineStringsOnImage.shiftc                 C   s,   | j rtjdtjdS tdd | jD S )a  Convert all line string coordinates to one array of shape ``(N,2)``.

        Added in 0.4.0.

        Returns
        -------
        (N, 2) ndarray
            Array containing all xy-coordinates of all line strings within this
            instance.

        r   r   c                 S   rd   r   r0   re   r   r   r   r   u  rg   z2LineStringsOnImage.to_xy_array.<locals>.<listcomp>)r  r   r   r   r   r  r-   r   r   r   to_xy_arrayg  s   zLineStringsOnImage.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 d}| jD ]4}t|j}|| t|ksIJ dt|tdd | jD f ||||  |jd	d	d
f< ||7 }q(|t|ksmJ dt||f | S )a  Modify the corner coordinates of all line strings in-place.

        .. note::

            This currently expects that `xy` contains exactly as many
            coordinates as the line strings within this instance have corner
            points. Otherwise, an ``AssertionError`` will be raised.

        Added in 0.4.0.

        Parameters
        ----------
        xy : (N, 2) ndarray or iterable of iterable of number
            XY-Coordinates of ``N`` corner points. ``N`` must match the
            number of corner points in all line strings within this instance.

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

        r   r   r   r   z7Expected input array to have shape (N,2), got shape %s.zcReceived fewer points than there are corner points in all line strings. Got %d points, expected %d.c                 S   s   g | ]}t |jqS r   )r   r&   )r   Zls_r   r   r   r     r   z:LineStringsOnImage.fill_from_xy_array_.<locals>.<listcomp>N.zExpected to get exactly as many xy-coordinates as there are points in all line strings polygons within this instance. Got %d points, could only assign %d points.)	r   r   r   r%   r$   r  r   r&   r+   )r)   r  counterrf   Z	nb_pointsr   r   r   fill_from_xy_array_w  s2   (


z&LineStringsOnImage.fill_from_xy_array_c                 C   sJ   ddl m} | jr|g | jdS tjdd | jD dd}|j|| jdS )a  Convert the line strings to one ``KeypointsOnImage`` instance.

        Added in 0.4.0.

        Returns
        -------
        imgaug.augmentables.kps.KeypointsOnImage
            A keypoints instance containing ``N`` coordinates for a total
            of ``N`` points in the ``coords`` attributes of all line strings.
            Order matches the order in ``line_strings`` and ``coords``
            attributes.

        r   r   r   c                 S   rd   r   r0   re   r   r   r   r     rg   z<LineStringsOnImage.to_keypoints_on_image.<locals>.<listcomp>r   rE   )r   r   r  r%   r   r   r  r   )r)   r   r&   r   r   r   to_keypoints_on_image  s   z(LineStringsOnImage.to_keypoints_on_imagec           	      C   s   | j }dd |D }tdd |D }t|j|ks%J d|t|jf | }d}|D ]!}|j}|||t| ddf |ddddf< |t|7 }q-|j| _| S )aB  Invert the output of ``to_keypoints_on_image()`` in-place.

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

        Added in 0.4.0.

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

        Returns
        -------
        LineStringsOnImage
            Line strings container with updated coordinates.
            Note that the instance is also updated in-place.

        c                 S   rd   r   r0   re   r   r   r   r     rg   zDLineStringsOnImage.invert_to_keypoints_on_image_.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r   )r   r&   r   r   r   r         z Expected %d coordinates, got %d.r   N)r  r+   r   Z	keypointsr.  r&   r%   )	r)   r   r   ZcoordssZnb_points_expZxy_arrr/  rf   r&   r   r   r   invert_to_keypoints_on_image_  s    
,z0LineStringsOnImage.invert_to_keypoints_on_image_c                 C   s2   |du r| j dd }|du rt| j}t||S )a'  Create a shallow copy of this object.

        Parameters
        ----------
        line_strings : None or list of imgaug.augmentables.lines.LineString, optional
            List of line strings on the image.
            If not ``None``, then the ``line_strings`` attribute of the copied
            object will be set to this value.

        shape : None or tuple of int or ndarray, optional
            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.
            If not ``None``, then the ``shape`` attribute of the copied object
            will be set to this value.

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Shallow copy.

        Nr  rT   r%   r  r  r   r   r   ru     s
   

zLineStringsOnImage.copyc                 C   s4   |du rdd | j D }|du rt| j}t||S )a   Create a deep copy of the object.

        Parameters
        ----------
        line_strings : None or list of imgaug.augmentables.lines.LineString, optional
            List of line strings on the image.
            If not ``None``, then the ``line_strings`` attribute of the copied
            object will be set to this value.

        shape : None or tuple of int or ndarray, optional
            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.
            If not ``None``, then the ``shape`` attribute of the copied object
            will be set to this value.

        Returns
        -------
        imgaug.augmentables.lines.LineStringsOnImage
            Deep copy.

        Nc                 S   s   g | ]}|  qS r   rt   re   r   r   r   r   	  r2  z/LineStringsOnImage.deepcopy.<locals>.<listcomp>r4  r  r   r   r   r`   	  s
   

zLineStringsOnImage.deepcopyc                 C   r   )zGet the line string(s) with given indices.

        Added in 0.4.0.

        Returns
        -------
        list of imgaug.augmentables.lines.LineString
            Line string(s) with given indices.

        r  r   r   r   r   r   &	  r   zLineStringsOnImage.__getitem__c                 C   r   )a*  Iterate over the line strings in this container.

        Added in 0.4.0.

        Yields
        ------
        LineString
            A line string in this container.
            The order is identical to the order in the line string list
            provided upon class initialization.

        )r   r  r-   r   r   r   r   3	  s   
zLineStringsOnImage.__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__B	  r   zLineStringsOnImage.__len__c                 C   r   r   r   r-   r   r   r   r   O	  r  zLineStringsOnImage.__repr__c                 C   s   dt | j| jf S )Nz LineStringsOnImage(%s, shape=%s))r#   r  r%   r-   r   r   r   r   R	  s   zLineStringsOnImage.__str__r  )TFr   r  r  )$r  r	  r
  r  r*   r  r  setterr  r  r  classmethodr!  r   r   r#  r   r'  r(  r+  r,  r-  rh   r   r   r.  r0  r1  r3  ru   r`   r   r   r5  r   r   r   r   r   r   r  ~  sN    





T
 

-3
&
 r  rZ   c                 C   sr   t jt | t | }t jt | t | t jt |t |  }| ||   k o6|k S   S r   r   )r   r   rK   r|   Zdist_s2eZ
dist_s2p2er   r   r   _is_point_on_lineW	  s   r8  c                 c   sv    dd l }t| ts| g} | D ])}t|dr5t|jD ]}t||jjjr.|D ]}|V  q'qt|V  qq|V  qd S )Nr   geoms)	rO   rQ   r   hasattrr   r9  rI   baseZGeometrySequence)Z
collectionrN   r  subitemZsubsubelr   r   r   r   `	  s   

r   c                    s   dd l  t| tr j| d | d }|S t| tr`t| dks*J dt| f t| d tr9 j| }|S tdd | D rQ j	 fdd| D }|S t
ddd	d | D f t| trn j| j}|S t
d
t| f )Nr   r   zEExpected list to contain at least one coordinate, got %d coordinates.c                 S   r  r   r  r  r   r   r   r   {	  r   z4_convert_var_to_shapely_geometry.<locals>.<listcomp>c                    s   g | ]	} j |jqS r   )rI   r   r&   re   rN   r   r   r   |	  s    zdCould not convert list-input to shapely geometry. Invalid datatype. List elements had datatypes: %s.r  c                 S   r  r   r  r  r   r   r   r   	  r   zFCould not convert input to shapely geometry. Invalid datatype. Got: %s)rO   rQ   rT   rI   rJ   r   r   r   r"   ZMultiLineStringrU   r  r&   r!   )varr   r   r=  r   r   q	  s@   


r   r  )r  
__future__r   r   r   ru   r   numpyr   Zskimage.drawr   Zskimage.measurer   r   r   r   r;  r   utilsr	   r
   r   r   r   objectr   r  r8  r   r   r   r   r   r   <module>   s@                r     
^	