o
    ߥi&                     @   sf  d dl Z d dlmZmZmZmZmZ d dlZd dlZ	d dl
Z
d dlm  mZ d dlmZ g dZd'ddZdd	 Zd
d Zdd Zdd Zd(ddZd(ddZdd Zd)ddZd*ddZ		d+deeef de	jdee	j d ee	j d!eeee	jeeeeef f f f
d"d#Z 			d,d$eeeeef dee	j dee	j d ee	j d!eee	jf f
d%d&Z!dS )-    N)DictListOptionalTupleUnion	rearrange)
gen_diffuse_maskget_crop_bboxget_roi_without_paddingpatch_aggregation_overlappatch_partition_overlappreprocess_roiresize_on_long_sideroi_to_tensorsmooth_border_mg
whiten_img   c                 C   s   | j d }| j d }||kr'|d | }tj| t|| |ftjd}||fS |d | }tj| |t|| ftjd}||fS )Nr            ?)interpolation)shapecv2resizeintINTER_LINEAR)img	long_side
src_height	src_widthscale_img r"   ^/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/cv/skin_retouching/utils.pyr      s   

	r   c                 C   sT  g }| D ]$}|d dkr n| |d d |d d |d d |d d d qt|}g }t|D ]t}|| }t|d	 |d
  }t|d |d  }|d
 |d	  d |d |d  d f}	||krg|n|}
d}t||
 }
d}t|	d ||
 d  t|	d ||
 d  t|	d ||
 d  t|	d ||
 d  d}| | q3|S )Nscorebboxr   r         )x1y1x2y2r+   r)   r,   r*   g      ?)r)   r+   r*   r,   )appendlenrangeabsr   )detecting_resultsboxesanno
face_countsuitable_bboxesi	face_bboxface_bbox_widthface_bbox_heightface_bbox_centersquare_bbox_lengthenlarge_ratio	sideScalesquare_bboxr"   r"   r#   r
   $   s<   





r
   c                 C   sj   t |d d}t|d | jd }t |d d}t|d | jd }| ||||f }|d||||gfS )Nr*   r   r,   r)   r+   r   )maxminr   )r   r&   crop_tcrop_bcrop_lcrop_rroir"   r"   r#   r   P   s   r   c                 C   s   t | dd } | S )N)r'   r   r   N.)torch
from_numpy	transposer   r"   r"   r#   r   Y   s   r   c                 C   s   |   d } | d d } | S )N     o@      ?r'   )floatrJ   r"   r"   r#   r   _   s   r       c              
   C   s   |   \}}}}|| || }}	tj| ||||ddfddd} g }
t|D ]2}t|	D ]+}| d d d d || ||d  |d  || ||d  |d  f }|
| q,q&tj|
dd}|S )Nr   constant)padmodevaluer   r'   dim)sizeFrP   r/   r-   rG   cat)imagep1p2paddingBCHWhw
patch_listr6   jpatchoutputr"   r"   r#   r   f   s(   (r   c                 C   s8   | d d d d || || f } t | d||d}|S )Nz$(b h w) c p1 p2 -> b c (h p1) (w p2))r`   ra   r   )rX   r`   ra   r[   re   r"   r"   r#   r   |   s   $r   c                 C   sD   |d }t j| |jd d ddd ddd} ||  }|d }|S )NrL   r'   bilinearrQ   r   r   )rV   interpolater   permute)diffuse_maskmgr"   r"   r#   r      s   
r   Fc           	      C   sx  d}|rd}t t j||f}t t j||f}t|jdkr*|dddddf }t ||d}t ||d}t |dd }| }t	
|| j}t	j|||gd	d
d }|ddddddddf  d9  < |d | d }t|jdks~J tj|| jdd ddd	 ddd	 }|  }|d }d| d | | d| |  }|d }| }|  }|S )z
    image: rgb
       P   r(   Nr%   r   )   rn   rK   r   rS   rF   g      ?g?rL      r'   rf   rg   )r   getStructuringElementMORPH_ELLIPSEr.   r   dilateerodeblursqueezerG   rH   todevicestackrV   rh   ri   halfbytecpunumpy)	rX   	skin_maskwhitening_degreeflag_bigKernaldilate_kernalsizenew_kernel1new_kernel2	whiten_mgoutput_predr"   r"   r#   r      sV   

(

r   r(   c                 C   s>  d}d}t j||ft jd}t|D ]E}t|D ]>}||kr5||| kr5||kr5||| kr5d|||f< q||krD|d | |||f< q||| krV|| d | |||f< qqt|D ]8}t|D ]1}||krzt|||f |d | |||f< qb||| krt|||f || d | |||f< qbq\t |g|  }|S )Ni  rn   )r   dtyper   )nponesfloat32r/   r@   dstack)out_channels	mask_sizediffuse_withar6   rc   r"   r"   r#   r	      s8   


$&r	   target_sizerX   bboxes	keypointsreturnc              	   C   s~  | \}}|j dd \}}||k rtd| d| ||k r)td| d| ||kr2d}d}	n|| }
|
d }|
| }	||krGd}d}n|| }|d }|| }||||	ft|||	||tjd}|dur|dddf  |7  < |dddf  |7  < |dddf  |7  < |ddd	f  |7  < ||d
< |dur|dddf  |7  < |dddf  |7  < ||d< |S )a  Pads the image on the sides to the target_size

    Args:
        target_size: (target_height, target_width)
        image:
        bboxes: np.array with shape (num_boxes, 4). Each row: [x_min, y_min, x_max, y_max]
        keypoints: np.array with shape (num_keypoints, 2), each row: [x, y]

    Returns:
        {
            "image": padded_image,
            "pads": (x_min_pad, y_min_pad, x_max_pad, y_max_pad),
            "bboxes": shifted_boxes,
            "keypoints": shifted_keypoints
        }

    Nr'   z2Target width should bigger than image_widthWe got  z4Target height should bigger than image_heightWe got r   )padsrX   r   r(   r   r   )r   
ValueErrorr   copyMakeBorderBORDER_CONSTANT)r   rX   r   r   target_heighttarget_widthimage_heightimage_width	y_min_pad	y_max_pady_pad	x_min_pad	x_max_padx_padresultr"   r"   r#   pad_to_size   sT   
r   r   c                 C   s   | \}}}}i }|dur%|j dd \}	}
|||	| ||
| f |d< |dur]|dddf  |8  < |dddf  |8  < |dddf  |8  < |dddf  |8  < ||d< |dur}|dddf  |8  < |dddf  |8  < ||d< |S )	a  Crops patch from the center so that sides are equal to pads.

    Args:
        image:
        pads: (x_min_pad, y_min_pad, x_max_pad, y_max_pad)
        bboxes: np.array with shape (num_boxes, 4). Each row: [x_min, y_min, x_max, y_max]
        keypoints: np.array with shape (num_keypoints, 2), each row: [x, y]

    Returns: cropped image

    {
            "image": cropped_image,
            "bboxes": shifted_boxes,
            "keypoints": shifted_keypoints
        }

    Nr'   rX   r   r   r(   r   r   )r   )r   rX   r   r   r   r   r   r   r   heightwidthr"   r"   r#   unpad_from_size  s$   

r   )r   )rN   )F)r(   )NN)NNN)"timetypingr   r   r   r   r   r   r}   r   rG   torch.nn.functionalnn
functionalrV   einopsr   __all__r   r
   r   r   r   r   r   r   r   r	   r   arrayndarraystrr   r   r"   r"   r"   r#   <module>   sZ   
,	

	
	
'
 
M