o
    0jG                     @   s   d dl Z d dlmZ d dlZddlmZ ddlmZm	Z	 ddl
mZ e	dr*d dlZe	d	r2d dlZejedG d
d dZejedG dd dZejedd	G dd dZdS )    N)Union   )logging)class_requires_depsis_dep_available   )	benchmarkzopencv-contrib-python	pyclipperc                	   @   s   e Zd Zd ZdddZ			ddeedf deedf deedf fdd	Z	ddeedf deedf deedf fd
dZ	dddZ
dd Z	ddeedf deedf deedf fddZdd Zdd ZdS )DetResizeForTestN  c                 K   s   d| _ d| _|d ur|| _d| _ n<d|v r'|d | _d| _ d|v r&|d | _n&d|v r8|d | _|dd	| _nd
|v rGd| _ |d
d| _nd| _d	| _|| _d S )Nr   Fr   image_shape   
keep_ratiolimit_side_len
limit_typeminresize_long   i  i  )	resize_typer   input_shaper   r   getr   r   max_side_limit)selfr   r   kwargs r   s/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/models/text_detection/processors.py__init__#   s(   



zDetResizeForTest.__init__r   r   r   c           
      C   sV   |dur|n| j }g g }}|D ]}| ||||\}}	|| ||	 q||fS )applyN)r   resizeappend)
r   imgsr   r   r   Zresize_imgs
img_shapesZori_imgimgshaper   r   r   __call__:   s   	

zDetResizeForTest.__call__c           
      C   s   |j \}}}t||gdk r| |}| jdkr%| ||||\}\}}	n'| jdkr4| |\}\}}	n| jdkrC| |\}\}}	n	| |\}\}}	|t	||||	gfS )N@   r   r   r   )
r#   sumimage_paddingr   resize_image_type0resize_image_type2resize_image_type3resize_image_type1nparray)
r   r"   r   r   r   src_hsrc_w_ratio_hratio_wr   r   r   r   N   s   



zDetResizeForTest.resizer   c                 C   sN   |j \}}}ttd|td||ftj| }||d|d|ddf< |S )zpadding image    N)r#   r,   zerosmaxuint8)r   ZimvaluehwcZim_padr   r   r   r'   g   s   $zDetResizeForTest.image_paddingc           	      C   s   | j \}}|jdd \}}| jdu r$|| | }t|d }|d }||kr2||kr2|ddgfS t|| }t|| }t|t|t|f}|||gfS )resize the imageNr   Tr3         ?)	r   r#   r   mathceilfloatcv2r   int)	r   r"   resize_hresize_wori_hori_wNr1   r2   r   r   r   r+   n   s   

z#DetResizeForTest.resize_image_type1c              	   C   s  |p| j }|p	| j}|j\}}}|dkr0t|||kr-||kr&t|| }n<t|| }n5d}n2|dkrPt|||k rM||k rFt|| }nt|| }nd}n|dkr^t|t|| }ntdt|| }	t|| }
t|	|
|krt	d|
 d|	 d| d	 t|t|	|
 }t|	| t|
| }	}
ttt
|	d
 d
 d
}	ttt
|
d
 d
 d
}
|	|kr|
|kr|ddgfS zt|
dkst|	dkrW dS t|t|
t|	f}W n   t|j|
|	  |	t| }|
t| }|||gfS )z
        resize image to a size multiple of 32 which is required by the network
        args:
            img(array): array with shape [h, w, c]
        return(tuple):
            img, (ratio_h, ratio_w)
        r5   r<   r   r   znot support limit type, image zResized image size (xz) exceeds max_side_limit of z. Resizing to fit within limit.r3   r   )N)NN)r   r   r#   r5   r?   r   	ExceptionrA   r   warningroundr@   r   info)r   r"   r   r   r   r8   r9   r:   ratiorB   rC   r1   r2   r   r   r   r(   ~   sP   

z#DetResizeForTest.resize_image_type0c                 C   s   |j \}}}|}|}||krt| j| }nt| j| }t|| }t|| }d}|| d | | }|| d | | }||krM||krM|ddgfS t|t|t|f}|t| }	|t| }
||	|
gfS )zresize image size   r   r<   )r#   r?   r   rA   r@   r   )r   r"   r8   r9   r0   rC   rB   rL   Z
max_strider1   r2   r   r   r   r)      s"   z#DetResizeForTest.resize_image_type2c           	      C   sv   | j \}}}|jdd \}}||kr||kr|ddgfS t|| }t|| }t|t|t|f}|||gfS )r;   Nr   r<   )r   r#   r?   r@   r   rA   )	r   r"   Zresize_crB   rC   rD   rE   r1   r2   r   r   r   r*      s   z#DetResizeForTest.resize_image_type3)Nr   NNN)N)r   )__name__
__module____qualname____doc__r   r   rA   strr$   r   r'   r+   r(   r)   r*   r   r   r   r   r
      sB    













Dr
   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )	NormalizeImagez1normalize image such as subtract mean, divide stdNchwc                    s   t    ttrt|| _d urnd d ur ng d d ur)ng dfddttD | _ fddttD | _	d S )Ngp?)g
ףp=
?gv/?gCl?)gZd;O?gy&1?g?c                    s   g | ]} |  qS r   r   .0i)scalestdr   r   
<listcomp>   s    z+NormalizeImage.__init__.<locals>.<listcomp>c                    s   g | ]} |  |  qS r   r   rV   )meanrZ   r   r   r[      s    )
superr   
isinstancerS   evalorderrangelenalphabeta)r   rY   r\   rZ   r`   	__class__)r\   rY   rZ   r   r      s   

"zNormalizeImage.__init__c                    s   fdd  fdd|D S )r   c                    s   | j d dkrt| tj}  jdkrt| d} tt| }t	| j d D ]"}|| 
tj||< ||   j| 9  < ||   j| 7  < q't|} jdkrZt|d}|S )Nr   r   rU   )r   r   r   )r   r   r   )r#   r@   ZcvtColorZCOLOR_RGBA2RGBr`   r,   Z	transposelistsplitra   astypeZfloat32rc   rd   merge)r"   Zsplit_imr:   res)r   r   r   _norm   s   


z&NormalizeImage.__call__.<locals>._normc                    s   g | ]} |qS r   r   )rW   r"   )rl   r   r   r[     s    z+NormalizeImage.__call__.<locals>.<listcomp>r   )r   r    r   )rl   r   r   r$      s   zNormalizeImage.__call__)NNNrU   )rO   rP   rQ   rR   r   r$   __classcell__r   r   re   r   rT      s    rT   c                	       s   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	dd Z
			d deedf deedf deedf fddZdd Z  ZS )!DBPostProcessz@
    The post process for Differentiable Binarization (DB).
    333333?ffffff?         @Ffastquadc           	         sT   t    || _|| _|| _|| _d| _|| _|| _|dv s%J d	||| _
d S )Nr   )Zslowrs   z.Score mode must be in [slow, fast] but got: {})r]   r   thresh
box_threshmax_candidatesunclip_ratiomin_size
score_modebox_typeformatuse_dilation)	r   ru   rv   rw   rx   r}   rz   r{   r   re   r   r   r     s   


zDBPostProcess.__init__c              	   C   s  |}|j \}}	||	 }
|| }g }g }t|d tjtjtj\}}|d| j D ]}dt	|d }t
||d}|d}|j d dk rIq+| ||dd	}||krXq+|j d d	krm| ||}t|d
krlq+nq+|dd	}t|dkr| |d\}}|| jd	 k rq+nq+t|}t|j d D ]*}tdtt||df |
 |||df< tdtt||d
f | |||d
f< q|| || q+||fS )N_bitmap: single map with shape (1, H, W), whose values are binarized as {0, 1}   NgMb`?Tr   r   r   r   r   r   )r   r   r   )r#   r@   findContoursri   r,   r6   	RETR_LISTCHAIN_APPROX_SIMPLErw   	arcLengthZapproxPolyDPreshapebox_score_fastuncliprb   get_mini_boxesry   r-   ra   r5   r   rJ   r   )r   pred_bitmap
dest_widthdest_heightrv   rx   bitmapheightwidthwidth_scaleheight_scaleboxesscorescontoursr0   contourepsilonZapproxpointsscoreboxssiderX   r   r   r   polygons_from_bitmap5  sL   


(*
z"DBPostProcess.polygons_from_bitmapc              	   C   s  |}|j \}}	||	 }
|| }t|d tjtjtj}t|dkr3|d |d |d }}}nt|dkrB|d |d }}t	t|| j
}g }g }t|D ]}|| }| |\}}|| jk reqRt|}| jdkrz| ||dd}n| ||}||krqR| ||ddd}| |\}}|| jd k rqRt|}t|j d D ]*}tdt	t||df |
 |||df< tdt	t||df | |||df< q||tj || qRtj|tjd|fS )	r~   r   r   r   r   r   rs   r   Zdtype)r#   r@   r   ri   r,   r6   r   r   rb   r   rw   ra   r   ry   r-   rz   r   r   box_score_slowr   r5   rJ   r   Zint16)r   r   r   r   r   rv   rx   r   r   r   r   r   Zoutsr"   r   r0   Znum_contoursr   r   indexr   r   r   r   r   rX   r   r   r   boxes_from_bitmapn  sH   




(*zDBPostProcess.boxes_from_bitmapc                 C   s|   t |}t |d}|| | }t }||tjtj zt	|
|}W |S  ty=   t	|
|d }Y |S w )r   Tr   )r@   ZcontourArear   r	   ZPyclipperOffsetZAddPathZJT_ROUNDZET_CLOSEDPOLYGONr,   r-   ZExecute
ValueError)r   r   rx   ZarealengthZdistanceoffsetexpandedr   r   r   r     s   
zDBPostProcess.unclipc           	      C   s   t |}ttt |dd d}d\}}}}|d d |d d kr)d}d}nd}d}|d d |d d kr>d}d}nd}d}|| || || || g}|t|d fS )	zget mini boxesc                 S   s   | d S )Nr   r   )rG   r   r   r   <lambda>  s    z.DBPostProcess.get_mini_boxes.<locals>.<lambda>)key)r   r   r   r   r   r   r   r   )r@   ZminAreaRectsortedrg   Z	boxPointsr   )	r   r   Zbounding_boxr   Zindex_1Zindex_2Zindex_3Zindex_4r   r   r   r   r     s   
zDBPostProcess.get_mini_boxesc                 C   sn  |j dd \}}| }tdtt|dddf  |d }tdtt|dddf  |d }tdtt|dddf  |d }tdtt|dddf  |d }	tj|	| d || d ftj	d}
|dddf | |dddf< |dddf | |dddf< t
|
|dddtjd t
|||	d ||d f |
d S )z5box_score_fast: use bbox mean score as the mean scoreNr   r   r   r   r   )r#   copyr5   r   r=   floorr>   r,   r4   r6   r@   fillPolyr   ri   int32r\   )r   r   _boxr8   r9   r   xminxmaxyminymaxmaskr   r   r   r     s   ****$   (zDBPostProcess.box_score_fastc           
      C   sb  |j dd \}}| }t|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 }tt|dddf d|d }tj|| d || d ftjd}	|dddf | |dddf< |dddf | |dddf< t	
|	|dddtjd t	|||d ||d f |	d S )z8box_score_slow: use polygon mean score as the mean scoreNr   r   r   r   r   r   )r#   r   r,   r   Zclipr   r5   r4   r6   r@   r   ri   r   r\   )
r   r   r   r8   r9   r   r   r   r   r   r   r   r   r     s   $$$$$   (zDBPostProcess.box_score_slowNru   rv   rx   c                 C   sf   g g }}t |d |D ]"\}}	| ||	|p| j|p| j|p | j\}
}||
 || q||fS )r   r   )zipprocessru   rv   rx   r   )r   predsr!   ru   rv   rx   r   r   r   	img_shaper   r   r   r   r   r$     s   
	
zDBPostProcess.__call__c                 C   s   |dd d d d f }||k}| j sd n
tddgddgg}|\}}	}
}|d ur7tt|tj|}n|}| jdkrN| |||	|||\}}||fS | jdkrc| 	|||	|||\}}||fS t
d)Nr   r   Zpolyrt   z,box_type can only be one of ['quad', 'poly'])r}   r,   r-   r@   Zdilateri   r6   r{   r   r   r   )r   r   r   ru   rv   rx   ZsegmentationZdilation_kernelr.   r/   r1   r2   r   r   r   r   r   r   r      s*    
	
zDBPostProcess.process)ro   rp   rq   rr   Frs   rt   rN   )rO   rP   rQ   rR   r   r   r   r   r   r   r   r   r?   r$   r   rm   r   r   re   r   rn     s6    97



rn   )r=   typingr   numpyr,   utilsr   Z
utils.depsr   r   Zutils.benchmarkr   r@   r	   Ztimeitr
   rT   rn   r   r   r   r   <module>   s(    K)