
    #
3j-                        S SK r S SKrS SKJr  S SKJrJrJrJrJ	r	J
r
  S SKr S SKrS S
KJrJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJrJr  S SK J!r!J"r"  S	SK#J$r$  S	SK%J%r%J&r&  S	SK'J(r(  \RR                  " S5        \!" S	5      r* " S S\5      r+S\S\S\,S\,S\,S\4S jr-S\S\S\4S jr.S\S\S\4S jr/S \\   S\4S! jr0S"\S#\S\4S$ jr1S\Rd                  S\Rd                  4S% jr3S\S&\\,\,\,\,4   S\4S' jr4S\S\4S( jr5S)\6\7S*4   SS4S+ jr8         S9S,\	\9\\Rd                  4   S-\:S.\,S/\,S0\,S1\\(   S2\:S3\:S4\\\,\,\,\,4      S5\:S6\\   S7\\   S\	\9\\Rd                  4   4S8 jjr;g! \ aL    \" S5        \" S5        \" 5         \" S5        \" S5        \" 5         \" S5        \R"                  " S	5         GNf = f):    N)Enum)AnyListOptionalTupleUnioncastzNo onnxruntime backend found.z-Please install rembg with CPU or GPU support:z'    pip install "rembg[cpu]"  # for CPUz3    pip install "rembg[gpu]"  # for NVIDIA/CUDA GPUzLFor more information, see: https://github.com/danielgatis/rembg#installation   )ImageImageOps)r   )estimate_alpha_cf)estimate_foreground_ml)stack_images)binary_erosiongaussian_filter)diskopening)new_session)sessionssessions_names)BaseSession   c                        \ rS rSrSrSrSrSrg)
ReturnType'   r   r
       N)__name__
__module____qualname____firstlineno__BYTESPILLOWNDARRAY__static_attributes__r       B/home/wildlama/miniconda3/lib/python3.13/site-packages/rembg/bg.pyr   r   '   s    EFGr&   r   imgmaskforeground_thresholdbackground_thresholderode_structure_sizereturnc                    U R                   S:X  d  U R                   S:X  a  U R                  S5      n [        R                  " U 5      n[        R                  " U5      nXb:  nXc:  nSn	US:  a$  [        R                  " XD4[        R
                  S9n	[        XyS9n[        XSS	9n[        R                  " UR                  [        R
                  S
S9n
SX'   SX'   US-  nU
S-  n[        X5      n[        X5      n[        X5      n[        R                  " US-  SS5      R                  [        R
                  5      n[        R                  " U5      nU$ )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
   )r3   border_value   )r2   
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_backgroundr3   trimapimg_normalizedtrimap_normalizedalpha
foregroundcutouts                   r'   alpha_matting_cutoutrM   -   s*   $ xx6SXX/kk% 

3ID!J5M5MIaGG!8
	 #=FM"=TUVMWWZ%%RXX#FFFF&Nn@E'>J*,FWWVc\1c*11"((;F__V$FMr&   c                 x    [         R                  " SU R                  S5      n[         R                  " XU5      nU$ )aG  
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)   emptyrL   s       r'   naive_cutoutrS   b   s/     IIfsxx!,E__S.FMr&   c                 (    U R                  U5        U $ )z
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_cutoutrV   r   s     LLJr&   imgsc                 P    U R                  S5      nU  H  n[        X5      nM     U$ )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)rW   pivotims      r'   get_concat_v_multir]      s*     HHQKEU' Lr&   img1img2c                     [         R                  " SU R                  U R                  UR                  -   45      nUR	                  U S5        UR	                  USU R                  45        U$ )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   rO   widthheightpaste)r^   r_   dsts      r'   rZ   rZ      sT     ))FTZZt{{)BC
DCIIdFIIdQ$%Jr&   c                     [        U [        5      n [        U R                  [        R
                  5      SS9n [        R                  " U S:  SS5      R                  [        R                  5      n U $ )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
r   )sigma   r   r7   )r   kernelr   rA   r:   float64wherer=   )r)   s    r'   post_processrk      sS     4 D4;;rzz2!<D88D3J3'..rxx8DKr&   colorc                     [         R                  " SU R                  [        U5      5      n[         R                  " X 5      nU$ )z
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/   )r   rO   rP   tuplealpha_composite)r(   rl   
backgroundcolored_images       r'   apply_background_colorrr      s4     6388U5\:J))*:Mr&   c                 J    [        [        [        R                  " U 5      5      $ )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_orientationrv      s     (11#677r&   models.c                 p   [        U 5      S:X  a  [        S5        [        [        5      n U  Ha  n[        R
                  " U5      nUc&  [        SU 35        [        R                  " S5        MB  [        SU 35         UR                  5         Mc     g! [         a  n[        SU 35         SnAM  SnAff = f)z'
Download models for image processing.
r   z+No models specified, downloading all modelsNzError: no model found: r
   zDownloading model: zError downloading model: )
lenprintrn   r   r   getsysexitdownload_models	Exception)rw   modelsessiones       r'   r~   r~      s     6{a;<~&,,u%?+E734HHQK'w/07'')   71!5667s   =B
B5B00B5dataalpha_matting"alpha_matting_foreground_threshold"alpha_matting_background_thresholdalpha_matting_erode_sizer   	only_maskpost_process_maskbgcolorforce_return_bytesargskwargsc
                    [        U [        5      (       d  U	(       aW  [        R                  n[	        [
        [        R                  " [        R                  " [	        [        U 5      5      5      5      nO[        U [
        5      (       a!  [        R                  n[	        [
        U 5      nOw[        U [        R                  5      (       a5  [        R                  n[	        [
        [        R                  " U 5      5      nO#[        SR!                  [#        U 5      5      5      eUR%                  SS5      n['        U5      nUc  [)        S/U
Q70 UD6nUR*                  " U/U
Q70 UD6n/ nU H  nU(       a3  [        R                  " [-        [        R.                  " U5      5      5      nU(       a  UnO8U(       a   [1        UUUUU5      nO U(       a  [3        UU5      nO[5        UU5      nUR7                  U5        M     Un[9        U5      S:  a  [;        U5      nUb  U(       d  [=        UU5      n[        R                  U:X  a  U$ [        R                  U:X  a  [        R>                  " U5      $ [        R                  " 5       nURA                  US5        URC                  S5        URE                  5       $ ! [         a$    U(       a  [3        UU5      n N[5        UU5      n Nf = f)aW  
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 or as python bytes if force_return_bytes is true.

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.
    force_return_bytes (bool, optional): Flag indicating whether to return the cutout image as bytes. Defaults to False.
    *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. Try using force_return_bytes=True to force python bytes outputrU   Fu2netr   PNG)#
isinstancebytesr   r"   r	   rt   r   openioBytesIOr#   r:   ndarrayr$   rB   
ValueErrorformattyperY   rv   r   predictrk   arrayrM   rV   rS   appendry   r]   rr   r;   saveseekread)r   r   r   r   r   r   r   r   r   r   r   r   return_typer(   rU   maskscutoutsr)   rL   bios                       r'   remover      sG   H $"4 &&8UZZ

4t3D(EFG	D(	#	# ''8T"	D"**	%	% ((8U__T23lssT

 	
 zz*e,H  
$Cg777OOC1$1&1EG??<#?@DF5-66, (d3%c40v7 : F
7|a#G,9'8K'[(zz&!!
**,C
KKUHHQK88:=  5,S$7F)#t4F	5s   9J88K&K&%K&)	F   
   r   NFFNF)<r   r|   enumr   typingr   r   r   r   r   r	   numpyr:   onnxruntimeortImportErrorrz   r}   PILr   r   	PIL.Imagert   !pymatting.alpha.estimate_alpha_cfr   +pymatting.foreground.estimate_foreground_mlr   pymatting.util.utilr   scipy.ndimager   r   skimage.morphologyr   r   session_factoryr   r   r   sessions.baser   set_default_logger_severityrh   r   intrM   rS   rV   r]   rZ   r   rk   rr   rv   rn   strr~   r   boolr   r   r&   r'   <module>r      s   	 
  : :    ' ? N , 9 , ( . &    "	a 2	2
2 2 	2
 2 2jh h 8    h T(^   x x H "
rzz 
bjj 
 sCc7I1J x "
8x 
8H 
87E#s(O 7 7.  .1.0$&%)#37$m
x+
,mm ),m ),	m
 "m k"m m m eCc3./0m m C=m smm 5(BJJ&'mq  
	
)*	
9:	G	
34	
?@	G	V HHQK
s   E3 3AGG