o
    'jQ                     @   s   d Z ddlZddlmZmZ ddlZddlmZ ddl	Z	ddl
mZ G dd dZG dd	 d	ZG d
d dZG dd dZG dd dZdS )zo
This code is refer from:
https://github.com/open-mmlab/mmocr/blob/main/mmocr/datasets/pipelines/transforms.py
    N)Image	ImageDraw)Polygon)poly_intersectionc                   @   s   e Zd ZdddZdd ZdS )	RandomScaling   g      ?g      @c                 K   sV   t |tsJ t |tst |tsJ || _t |tr || _dS d| d| f| _dS )zRandom scale the image while keeping aspect.

        Args:
            size (int) : Base size before scaling.
            scale (tuple(float)) : The range of scaling.
           N)
isinstanceintfloattuplesizescale)selfr   r   kwargs r   c/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddleocr/ppocr/data/imaug/fce_aug.py__init__   s   zRandomScaling.__init__c           
      C   s  |d }|d }|j \}}}tjt| jt| j}| jd t|| | }t||g}t	||d  t	||d  f}	t
||	d d d }||d< |d d d d dd df |d  |d d d d dd df< |d d d d dd df |d  |d d d d dd df< ||d< |S )Nimagepolysg      ?r	   r      )shapenprandomuniformminr   maxr   arrayr   cv2resize)
r   datar   
text_polyshw_Zaspect_ratioscalesout_sizer   r   r   __call__(   s    <<zRandomScaling.__call__N)r   r   )__name__
__module____qualname__r   r)   r   r   r   r   r      s    
r   c                   @   s6   e Zd Z				dddZdd Zd	d
 Zdd ZdS )RandomCropFlip皙?      ?r	   皙?c                 K   sL   t |tsJ t |tsJ t |tsJ || _d| _|| _|| _|| _dS )a  Random crop and flip a patch of the image.

        Args:
            crop_ratio (float): The ratio of cropping.
            iter_num (int): Number of operations.
            min_area_ratio (float): Minimal area ratio between cropped patch
                and original image.
        g{Gz?N)r
   r   r   	pad_ratioepsilon
crop_ratioiter_nummin_area_ratio)r   r1   r3   r4   r5   r   r   r   r   r   <   s   
zRandomCropFlip.__init__c                 C   s   t | jD ]}| |}q|S N)ranger4   random_crop_flip)r   resultsir   r   r   r)   T   s   zRandomCropFlip.__call__c           &      C   s  |d }|d }|d }t |dkr|S tj | jkr|S |j\}}}|| }t|| j }	t|| j }
| |||	|
\}}t |dksLt |dkrN|S d}|dk r7|d7 }g }g }g }g }tjj|dd}t	||
 }t
||
 }t|d|d }t|d|d }tjj|dd}t	||	 }t
||	 }t|d|d }t|d|d }|| ||  || j k rqPt||||g||||ggjtj}t|}d	}t||D ]S\}}t|d
d}t||dd\}}t|t|j | jkrt|| jkrd} n$t|t|j | jk r'|| || q|| || q|r6qP	 |||||d d f }tjd} | dkr^t|d d d d d
f }!n#| dkrrt|d d d
d d f }!nt|d d d
d d d
f }!|!|||||d d f< ||d< t |dkrJ|j\}"}#}| dkrt|D ]#\}$}|d
d}%|#|%d d df  d|  |%d d df< |%||$< qnj| dkrt|D ]#\}$}|d
d}%|"|%d d df  d|  |%d d df< |%||$< qn<t|D ]7\}$}|d
d}%|#|%d d df  d|  |%d d df< |"|%d d df  d|  |%d d df< |%||$< q|| }|| }t||d< ||d< |S )Nr   r   ignore_tagsr   2   r	   r   )r   Fr   )bufferT   img)lenr   r   r3   r   r   r1   generate_crop_targetchoicer   r   clipr5   stackTastypeint32r   zipreshaper   absr   arear2   appendrandintZascontiguousarray	enumerater   )&r   r9   r   polygonsr;   r$   r%   r&   rK   pad_hpad_wh_axisw_axisattemptZ
polys_keepZ	polys_newZignore_tags_keepZignore_tags_newxxZxminZxmaxyyZyminZymaxZptsppZ	fail_flagpolygonZ
ignore_tagZppiZppiouZcroppedZselect_typer?   heightwidthidxpolyr   r   r   r8   Z   s   








(
(((zRandomCropFlip.random_crop_flipc                 C   sv  |j \}}}tj||d  tjd}tj||d  tjd}	g }
|D ]*}t|tjdd}t|}t	|}|

|d |d |d |d g q"tj|
tjd}|D ]M}tj|ddtj}t|dddf }t|dddf }d|	|| || < t|dddf }t|dddf }d||| || < qWt|dkd }t|	dkd }||fS )	a  Generate crop target and make sure not to crop the polygon
        instances.

        Args:
            image (ndarray): The image waited to be crop.
            all_polys (list[list[ndarray]]): All polygons including ground
                truth polygons and ground truth ignored polygons.
            pad_h (int): Padding length of height.
            pad_w (int): Padding length of width.
        Returns:
            h_axis (ndarray): Vertical cropping range.
            w_axis (ndarray): Horizontal cropping range.
        r   Zdtyper   r   r	   r>   )ZdecimalsN)r   r   ZzerosrG   r    ZminAreaRectrF   rI   Z	boxPointsZint64rL   r   roundr   r   where)r   r   Z	all_polysrP   rQ   r$   r%   r&   Zh_arrayZw_arrayr#   rX   rectboxr   r\   ZminxZmaxxZminyZmaxyrR   rS   r   r   r   rA      s*   

$z#RandomCropFlip.generate_crop_targetN)r.   r/   r	   r0   )r*   r+   r,   r   r)   r8   rA   r   r   r   r   r-   ;   s    
cr-   c                       sJ   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Zdd Zdd Z	  Z
S )RandomCropPolyInstanceszORandomly crop images and make sure to contain at least one intact
    instance.      ?皙?c                    s   t    || _|| _d S r6   )superr   r3   min_side_ratio)r   r3   rf   r   	__class__r   r   r      s   

z RandomCropPolyInstances.__init__c                 C   sN  t |tsJ t||ksJ | }tt|| |}d||d < d|d< td|gt|dg }t|dk d }t|dkd }tj	dt|}	tj	||	 ||	 }
| }t
|
| |}d|d |< d|d< td|gt|dg }t|dk d }t|dkd }tj	dt|}	tj	||	 ||	 }|
|fS )Nr   r	   r   )r
   r   r@   copyr   r   Zhstackr_   r   rM   r   )r   Zvalid_arrayZmin_lenZ	max_startZmin_endZstart_arrayZ
diff_arrayZregion_startsZregion_endsZ
region_indstart	end_arrayendr   r   r   sample_valid_start_end   s2   z.RandomCropPolyInstances.sample_valid_start_endc                 C   s  t |tsJ |dd \}}|d }tj|tjd}tj|tjd}|tjdt| }|d	tj}t
t|dddf d d}	tt
|dddf d |d }
t
t|dddf d d}tt
|dddf d |d }|D ]S}|d	tj}t|dddf d|d }t|dddf d|d }t|t
|}}t|t
|}}d||d |d < d||d |d < q}t|| j }t|| j }| |||	|
\}}| ||||\}}t||||gS )	zGenerate crop box and make sure not to crop the polygon instances.

        Args:
            img_size (tuple(int)): The image size (h, w).
            results (dict): The results dict.
        Nr   r   r]   r   )r   r   r>   r	   )r
   r   r   onesrG   r   rM   r@   rI   rF   r   r   rC   r   rf   rm   r   )r   Zimg_sizer9   r$   r%   Z	key_masksZx_valid_arrayZy_valid_arrayZselected_maskZmax_x_startZ	min_x_endZmax_y_startZ	min_y_endmaskZclip_xZclip_yZmin_xZmax_xZmin_yZmax_yZmin_wZmin_hx1x2y1y2r   r   r   sample_crop_box
  s8    $ $

z'RandomCropPolyInstances.sample_crop_boxc                 C   s   |j dksJ |j\}}}d|d   kr!|d   k r!|ks$J  J d|d   kr8|d   k r8|ks;J  J ||d |d |d |d f S )Nr>   r   r	   r   )ndimr   )r   r?   Zbboxr$   r%   r&   r   r   r   crop_img5  s
   ..$z RandomCropPolyInstances.crop_imgc                 C   s,  |d }|d }|d }t |dk r|S tj | jk r| |j|}| ||}||d< |\}}}	}
t|	| d}t|
| d}|d d d d dd df | |d d d d dd df< |d d d d dd df | |d d d d dd df< g }g }t	|D ]\}}|d d d d df dk
 r|d d d d df |d k 
 r|d d dd df dk
 r|d d dd df |d k 
 rt|d d d d df d||d d d d df< t|d d dd df d||d d dd df< || |||  qt||d< ||d< |S )	Nr   r   r;   r	   r   r      )r@   r   r   random_sampler3   rt   r   rv   r   rN   allrC   rL   r   )r   r9   r   rO   r;   Zcrop_boxr?   rp   rr   rq   rs   r%   r$   Zvalid_masks_listZvalid_tags_listindrX   r   r   r   r)   <  s@   88   22
z RandomCropPolyInstances.__call__c                 C      | j j}|S r6   rh   r*   r   repr_strr   r   r   __repr__`     z RandomCropPolyInstances.__repr__)rc   rd   )r*   r+   r,   __doc__r   rm   rt   rv   r)   r   __classcell__r   r   rg   r   rb      s    +$rb   c                   @   sP   e Zd Z				dddZddd	Zd
d Zdd Zdd Zdd Zdd Z	dS )RandomRotatePolyInstancesr/   
   Fr   r   r   c                 K   s   || _ || _|| _|| _dS )a  Randomly rotate images and polygon masks.

        Args:
            rotate_ratio (float): The ratio of samples to operate rotation.
            max_angle (int): The maximum rotation angle.
            pad_with_fixed_color (bool): The flag for whether to pad rotated
               image with fixed value. If set to False, the rotated image will
               be padded onto cropped image.
            pad_value (tuple(int)): The color value for padding rotated image.
        N)rotate_ratio	max_anglepad_with_fixed_color	pad_value)r   r   r   r   r   r   r   r   r   r   f  s   
z"RandomRotatePolyInstances.__init__r   r   c                 C   s   |\}}| }|d d d d df |d d dd df }}| }|d t j }t |}	t |}
|| }|| }|||	  ||
  |d  }|||
  ||	   |d  }|||d d d d df< |d d dd df< |S )Nr   r	      r   )mathpicossin)r   centerpointsthetacenter_shiftZcenter_xZcenter_yxyr   r   Z_xZ_yr   r   r   rotate{  s   .

.z RandomRotatePolyInstances.rotatec                 C   s   t |tsJ |tj d }|d d \}}t|}t|}t|t| |t|  }t|t| |t|  }	||	f}
|
S )Ng     f@r   )r
   r   r   r   r   r   r   fabs)r   Zori_sizeZdegreeangler$   r%   r   r   Zcanvas_hZcanvas_wcanvas_sizer   r   r   cal_canvas_size  s   

  z)RandomRotatePolyInstances.cal_canvas_sizec                 C   s   t j d | | }|S )Nr   )r   r   ry   )r   r   r   r   r   r   sample_angle  s   z&RandomRotatePolyInstances.sample_anglec                 C   sb  |j d d \}}t|d |d f|d}|d  t|d | d 7  < |d  t|d | d 7  < | jrMtj|||d |d ftj| jd}|S t	|}tj
d|d d tj
d|d d }	}
||	|	|d	  |
|
|d	  f }t||d |d f}tj|||d |d fg d
d}tj|||d |d fg dd}|||  }|S )Nr   r	   )r   r   )r	   r   r   )flagsborderValue      	   )r	   r	   r	   )r   r   )r   r    ZgetRotationMatrix2Dr   r   Z
warpAffineZINTER_NEARESTr   r   Z
zeros_liker   rM   r!   )r   r?   r   r   r$   r%   Zrotation_matrixZ
target_imgro   h_indw_indimg_cutr   r   r   
rotate_img  s<     
$z$RandomRotatePolyInstances.rotate_imgc                 C   s   t j | jk rg|d }|d }|jd d \}}| | j}| ||f|}t|d | d t|d | d f}| 	|||}||d< g }	|D ]}
| 
|d |d f|
||}|	| qJt |	|d< |S )Nr   r   r   r	   r   )r   r   ry   r   r   r   r   r   r   r   r   rL   r   )r   r9   r   rO   r$   r%   r   r   r   Zrotated_masksro   Zrotated_maskr   r   r   r)     s&   z"RandomRotatePolyInstances.__call__c                 C   r|   r6   r}   r~   r   r   r   r     r   z"RandomRotatePolyInstances.__repr__N)r/   r   Fr   )r   )
r*   r+   r,   r   r   r   r   r   r)   r   r   r   r   r   r   e  s    

r   c                   @   sF   e Zd Z			dddZdddZd	d
 Zdd Zdd Zdd ZdS )SquareResizePad333333?Fr   c                 K   sT   t |tsJ t |tsJ t |tsJ t |tsJ || _|| _|| _|| _dS )a  Resize or pad images to be square shape.

        Args:
            target_size (int): The target size of square shaped image.
            pad_with_fixed_color (bool): The flag for whether to pad rotated
               image with fixed value. If set to False, the rescales image will
               be padded onto cropped image.
            pad_value (tuple(int)): The color value for padding rotated image.
        N)	r
   r   r   boolr   target_sizer1   r   r   )r   r   r1   r   r   r   r   r   r   r     s   
zSquareResizePad.__init__Tc                 C   sx   |j \}}}|r)||kr| jnt|| j | }||kr| jnt|| j | }n| j }}t|||f}|||ffS r6   )r   r   r   r    r!   )r   r?   
keep_ratior$   r%   r&   Zt_hZt_wr   r   r   
resize_img  s    "
zSquareResizePad.resize_imgc                 C   s  |j d d \}}||kr|dfS t||}| jr,tj||dftjd}| j|d d < n1tjd|d d tjd|d d }}||||d  |||d  f }t	
|||f}||krkd|| d }	}
n	|| d d}	}
|||	|	| |
|
| f< |
|	f}||fS )	Nr   r   r>   r]   r   r   r   r   )r   r   r   r   rn   Zuint8r   r   rM   r    r!   )r   r?   r$   r%   Zpad_sizeZ
expand_imgr   r   r   y0x0offsetr   r   r   
square_pad  s$   
$zSquareResizePad.square_padc                 C   sL   |\}}|  }|d d d | |d d d< |dd d | |dd d< |S )Nr   r	   )ri   )r   r   r   r   r   Z
pad_pointsr   r   r   square_pad_mask  s
   zSquareResizePad.square_pad_maskc                 C   s  |d }|d }|j d d \}}tj | jk r*| j|dd\}}| |\}}n| j|dd\}}d}||d< zJ|d d d d dd df |d	  | |d  |d d d d dd df< |d d d d d	d df |d  | |d	  |d d d d d	d df< W n   Y ||d< |S )
Nr   r   r   T)r   Fr   r   r	   )r   r   r   ry   r1   r   r   )r   r9   r   rO   r$   r%   r(   r   r   r   r   r)     s8    zSquareResizePad.__call__c                 C   r|   r6   r}   r~   r   r   r   r   2  r   zSquareResizePad.__repr__N)r   Fr   )T)	r*   r+   r,   r   r   r   r   r)   r   r   r   r   r   r     s    


r   )r   numpyr   ZPILr   r   r    Zshapely.geometryr   r   Zppocr.utils.poly_nmsr   r   r-   rb   r   r   r   r   r   r   <module>   s   ! + u