Ë
    ÷Gìj›(  ã                   ó¸  — d dl Z d dlmZ d dlmZmZmZmZmZm	Z	 d dl
Zd dlZd dlmZmZmZmZmZmZ d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
l m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'  ejP                  d«        eed«      Z) G d„ de«      Z*dedede+de+de+defd„Z,dededefd„Z-dededefd„Z.dee   defd„Z/dededefd „Z0dejb                  dejb                  fd!„Z2ded"ee+e+e+e+f   defd#„Z3dedefd$„Z4d2d%„Z5	 	 	 	 	 	 	 	 d3d&ee6eejb                  f   d'e7d(e+d)e+d*e+d+ee'   d,e7d-e7d.eee+e+e+e+f      d/ee   d0ee   dee6eejb                  f   fd1„Z8y)4é    N)ÚEnum)ÚAnyÚListÚOptionalÚTupleÚUnionÚcast)ÚBORDER_DEFAULTÚMORPH_ELLIPSEÚ
MORPH_OPENÚGaussianBlurÚgetStructuringElementÚmorphologyEx)ÚImageÚImageOps)r   )Úestimate_alpha_cf)Úestimate_foreground_ml)Ústack_images)Úbinary_erosioné   )Únew_session)Úsessions_class)ÚBaseSessioné   )r   r   c                   ó   — e Zd ZdZdZdZy)Ú
ReturnTyper   r   é   N)Ú__name__Ú
__module__Ú__qualname__ÚBYTESÚPILLOWÚNDARRAY© ó    úLC:\Users\Stabi\Downloads\virtual-tryon(1)\venv\Lib\site-packages\rembg/bg.pyr   r      s   „ Ø€EØ€FØ�Gr%   r   ÚimgÚmaskÚforeground_thresholdÚbackground_thresholdÚerode_structure_sizeÚreturnc                 óÆ  — | j                   dk(  s| j                   dk(  r| j                  d«      } t        j                  | «      }t        j                  |«      }||kD  }||k  }d}	|dkD  r't        j                  ||ft        j
                  ¬«      }	t        ||	¬«      }t        ||	d¬	«      }t        j                  |j                  t        j
                  d
¬«      }
d|
|<   d|
|<   |dz  }|
dz  }t        ||«      }t        ||«      }t        ||«      }t        j                  |dz  dd«      j                  t        j
                  «      }t        j                  |«      }|S )a  
    Perform alpha matting on an image using a given mask and threshold values.

    This function takes a PIL image `img` and a PIL image `mask` as input, along with
    the `foreground_threshold` and `background_threshold` values used to determine
    foreground and background pixels. The `erode_structure_size` parameter specifies
    the size of the erosion structure to be applied to the mask.

    The function returns a PIL image representing the cutout of the foreground object
    from the original image.
    ÚRGBAÚCMYKÚRGBNr   )Údtype)Ú	structurer   )r2   Úborder_valueé€   )r1   Ú
fill_valueéÿ   g     ào@)ÚmodeÚconvertÚnpÚasarrayÚonesÚuint8r   ÚfullÚshaper   r   r   ÚclipÚastyper   Ú	fromarray)r'   r(   r)   r*   r+   Ú	img_arrayÚ
mask_arrayÚis_foregroundÚis_backgroundr2   ÚtrimapÚimg_normalizedÚtrimap_normalizedÚalphaÚ
foregroundÚcutouts                   r&   Úalpha_matting_cutoutrL   %   sB  € ð$ ‡x�x�6Ò˜SŸX™X¨Ò/Ø�k‰k˜%Ó ˆä—
‘
˜3“€IÜ—‘˜DÓ!€JàÐ!5Ñ5€MØÐ!5Ñ5€Mà€IØ˜aÒÜ—G‘GØ!Ð#7Ð8ÄÇÁô
ˆ	ô # =¸IÔF€MÜ" =¸IÐTUÔV€Mä�W‰W�Z×%Ñ%¬R¯X©XÀ#ÔF€FØ€Fˆ=ÑØ€Fˆ=Ñà Ñ&€NØ ™Ðä˜nÐ.?Ó@€EÜ'¨¸Ó>€JÜ˜* eÓ,€Fä�W‰W�V˜c‘\ 1 cÓ*×1Ñ1´"·(±(Ó;€FÜ�_‰_˜VÓ$€Fà€Mr%   c                 óv   — t        j                  d| j                  d«      }t        j                  | ||«      }|S )ac  
    Perform a simple cutout operation on an image using a mask.

    This function takes a PIL image `img` and a PIL image `mask` as input.
    It uses the mask to create a new image where the pixels from `img` are
    cut out based on the mask.

    The function returns a PIL image representing the cutout of the original
    image using the mask.
    r.   r   )r   ÚnewÚsizeÚ	composite)r'   r(   ÚemptyrK   s       r&   Únaive_cutoutrR   Z   s1   € ô �I‰I�f˜sŸx™x¨!Ó,€EÜ�_‰_˜S %¨Ó.€FØ€Mr%   c                 ó(   — | j                  |«       | S )a  
    Apply the specified mask to the image as an alpha cutout.

    Args:
        img (PILImage): The image to be modified.
        mask (PILImage): The mask to be applied.

    Returns:
        PILImage: The modified image with the alpha cutout applied.
    )Úputalpha)r'   r(   s     r&   Úputalpha_cutoutrU   j   s   € ð ‡L�L�ÔØ€Jr%   Úimgsc                 óN   — | j                  d«      }| D ]  }t        ||«      }Œ |S )zº
    Concatenate multiple images vertically.

    Args:
        imgs (List[PILImage]): The list of images to be concatenated.

    Returns:
        PILImage: The concatenated image.
    r   )ÚpopÚget_concat_v)rV   ÚpivotÚims      r&   Úget_concat_v_multir\   y   s,   € ð �H‰H�Q‹K€EÛˆÜ˜U BÓ'‰ð à€Lr%   Úimg1Úimg2c                 óØ   — t        j                  d| j                  | j                  |j                  z   f«      }|j	                  | d«       |j	                  |d| j                  f«       |S )zí
    Concatenate two images vertically.

    Args:
        img1 (PILImage): The first image.
        img2 (PILImage): The second image to be concatenated below the first image.

    Returns:
        PILImage: The concatenated image.
    r.   )r   r   r   )r   rN   ÚwidthÚheightÚpaste)r]   r^   Údsts      r&   rY   rY   ‰   sT   € ô �)‰)�F˜TŸZ™Z¨¯©°t·{±{Ñ)BÐCÓ
D€CØ‡I�Iˆd�FÔØ‡I�Iˆd�Q˜Ÿ™Ð$Ô%Ø€Jr%   c                 óÆ   — t        | t        t        «      } t        | dddt        ¬«      } t        j                  | dk  dd«      j                  t
        j                  «      } | S )zå
    Post Process the mask for a smooth boundary by applying Morphological Operations
    Research based on paper: https://www.sciencedirect.com/science/article/pii/S2352914821000757
    args:
        mask: Binary Numpy Mask
    )é   re   r   )ÚsigmaXÚsigmaYÚ
borderTypeé   r   r6   )	r   r   Úkernelr   r
   r9   Úwherer@   r<   ©r(   s    r&   Úpost_processrm   š   sN   € ô ˜œj¬&Ó1€DÜ˜˜f¨Q°qÄ^ÔT€DÜ�8‰8�D˜3‘J  3Ó'×.Ñ.¬r¯x©xÓ8€DØ€Kr%   Úcolorc                 ó„   — |\  }}}}t        j                  d| j                  ||||f«      }|j                  | | ¬«       |S )a  
    Apply the specified background color to the image.

    Args:
        img (PILImage): The image to be modified.
        color (Tuple[int, int, int, int]): The RGBA color to be applied.

    Returns:
        PILImage: The modified image with the background color applied.
    r.   rl   )r   rN   rO   rb   )r'   rn   ÚrÚgÚbÚaÚcolored_images          r&   Úapply_background_colorru   §   sH   € ð �J€A€qˆ!ˆQÜ—I‘I˜f c§h¡h°°A°q¸!°Ó=€MØ×Ñ˜ #ÐÔ&àÐr%   c                 óH   — t        t        t        j                  | «      «      S )z­
    Fix the orientation of the image based on its EXIF data.

    Args:
        img (PILImage): The image to be fixed.

    Returns:
        PILImage: The fixed image.
    )r	   ÚPILImager   Úexif_transpose)r'   s    r&   Úfix_image_orientationry   ¹   s   € ô ”œ(×1Ñ1°#Ó6Ó7Ð7r%   c                  ó:   — t         D ]  } | j                  «        Œ y)z/
    Download models for image processing.
    N)r   Údownload_models)Úsessions    r&   r{   r{   Æ   s   € ÷ "ˆØ×ÑÕ!ñ "r%   ÚdataÚalpha_mattingÚ"alpha_matting_foreground_thresholdÚ"alpha_matting_background_thresholdÚalpha_matting_erode_sizer|   Ú	only_maskÚpost_process_maskÚbgcolorÚargsÚkwargsc	                 óÚ  — t        | t        «      rt        j                  }| }n¬t        | t        «      r9t        j
                  }t        j                  t        j                  | «      «      }nct        | t        j                  «      r&t        j                  }t        j                  | «      }n#t        dj                  t!        | «      «      «      ‚|
j#                  dd«      }t%        |«      }|€t'        dg|	¢­i |
¤Ž} |j(                  |g|	¢­i |
¤Ž}g }|D ]y  }|r1t        j                  t+        t        j,                  |«      «      «      }|r|}n.|r	 t/        |||||«      }n|rt1        ||«      }nt3        ||«      }|j5                  |«       Œ{ |}t7        |«      dkD  rt9        |«      }|�|st;        ||«      }t        j                  |k(  r|S t        j                  |k(  rt        j<                  |«      S t        j                  «       }|j?                  |d«       |jA                  d«       |jC                  «       S # t        $ r |rt1        ||«      }nt3        ||«      }Y Œèw xY w)añ  
    Remove the background from an input image.

    This function takes in various parameters and returns a modified version of the input image with the background removed. The function can handle input data in the form of bytes, a PIL image, or a numpy array. The function first checks the type of the input data and converts it to a PIL image if necessary. It then fixes the orientation of the image and proceeds to perform background removal using the 'u2net' model. The result is a list of binary masks representing the foreground objects in the image. These masks are post-processed and combined to create a final cutout image. If a background color is provided, it is applied to the cutout image. The function returns the resulting cutout image in the format specified by the input 'return_type' parameter.

    Parameters:
        data (Union[bytes, PILImage, np.ndarray]): The input image data.
        alpha_matting (bool, optional): Flag indicating whether to use alpha matting. Defaults to False.
        alpha_matting_foreground_threshold (int, optional): Foreground threshold for alpha matting. Defaults to 240.
        alpha_matting_background_threshold (int, optional): Background threshold for alpha matting. Defaults to 10.
        alpha_matting_erode_size (int, optional): Erosion size for alpha matting. Defaults to 10.
        session (Optional[BaseSession], optional): A session object for the 'u2net' model. Defaults to None.
        only_mask (bool, optional): Flag indicating whether to return only the binary masks. Defaults to False.
        post_process_mask (bool, optional): Flag indicating whether to post-process the masks. Defaults to False.
        bgcolor (Optional[Tuple[int, int, int, int]], optional): Background color for the cutout image. Defaults to None.
        *args (Optional[Any]): Additional positional arguments.
        **kwargs (Optional[Any]): Additional keyword arguments.

    Returns:
        Union[bytes, PILImage, np.ndarray]: The cutout image with the background removed.
    zInput type {} is not supported.rT   FÚu2netr   ÚPNG)"Ú
isinstancerw   r   r"   Úbytesr!   r   ÚopenÚioÚBytesIOr9   Úndarrayr#   rA   Ú
ValueErrorÚformatÚtyperX   ry   r   Úpredictrm   ÚarrayrL   rU   rR   ÚappendÚlenr\   ru   r:   ÚsaveÚseekÚread)r}   r~   r   r€   r�   r|   r‚   rƒ   r„   r…   r†   Úreturn_typer'   rT   ÚmasksÚcutoutsr(   rK   Úbios                      r&   Úremoverž   Î   s  € ôD �$œÔ!Ü ×'Ñ'ˆØ‰Ü	�Dœ%Ô	 Ü ×&Ñ&ˆÜ�j‰jœŸ™ DÓ)Ó*‰Ü	�Dœ"Ÿ*™*Ô	%Ü ×(Ñ(ˆÜ�o‰o˜dÓ#‰äÐ:×AÑAÄ$ÀtÃ*ÓMÓNÐNà�z‰z˜* eÓ,€Hô   Ó
$€Cà€Ü˜gÐ7¨Ò7°Ñ7ˆàˆG�O‰O˜CÐ1 $Ò1¨&Ñ1€EØ€GãˆÙÜ—?‘?¤<´·±¸³Ó#?Ó@ˆDáØ‰Fáð5Ü-ØØØ6Ø6Ø,ó‘ñ Ü(¨¨dÓ3‘ä% c¨4Ó0�à�‰�vÕð7 ð: €FÜ
ˆ7ƒ|�aÒÜ# GÓ,ˆàÐ¡9Ü'¨°Ó8ˆä×Ñ˜KÒ'Øˆä×Ñ˜[Ò(Ü�z‰z˜&Ó!Ð!ä
�*‰*‹,€CØ
‡K�K��UÔØ‡H�HˆQ„Kà�8‰8‹:Ðøô= ò 5ÙÜ,¨S°$Ó7‘Fä)¨#¨tÓ4�Fùð	5ús   ÅIÉ$I*É)I*)r,   N)Féð   é
   r    NFFN)9r�   Úenumr   Útypingr   r   r   r   r   r	   Únumpyr9   ÚonnxruntimeÚortÚcv2r
   r   r   r   r   r   ÚPILr   r   Ú	PIL.Imagerw   Ú!pymatting.alpha.estimate_alpha_cfr   Ú+pymatting.foreground.estimate_foreground_mlr   Úpymatting.util.utilr   Úscipy.ndimager   Úsession_factoryr   Úsessionsr   Úsessions.baser   Úset_default_logger_severityrj   r   ÚintrL   rR   rU   r\   rY   r�   rm   ru   ry   r{   r‹   Úboolrž   r$   r%   r&   Ú<module>r³      sD  ðÛ 	Ý ß :× :ã Û ÷÷ ÷  Ý 'Ý ?Ý NÝ ,Ý (å (Ý $Ý &à €× Ñ  Ô "á	˜}¨fÓ	5€ô�ô ð2Ø	ð2à
ð2ð ð2ð ð	2ð
 ð2ð ó2ðj�hð  hð °8ó ð ˜ð ¨ð °hó ð˜T (™^ð °ó ð �xð  xð °Hó ð"
�r—z‘zð 
 b§j¡jó 
ð ð °°s¸CÀÀcÐ7IÑ1Jð Èxó ð$
8˜xð 
8¨Hó 
8ó"ð  Ø.1Ø.0Ø$&Ø%)ØØ#Ø37ñgØ
��x §¡Ð+Ñ
,ðgàðgð ),ðgð ),ð	gð
 "ðgð �kÑ"ðgð ðgð ðgð �e˜C  c¨3Ð.Ñ/Ñ0ðgð �C‰=ðgð �s‰mðgð ˆ5�(˜BŸJ™JÐ&Ñ'ôgr%   