Ë
    ½Gìj•b  ã                   óä   — d dl mZ d dlZd dlZd dlZd dlZd dlm	Z	 d„ Z
d„ Zd„ Zd„ Zdd„Zd	„ Zdd
„Zdd„Zd d„Zd„ Zd!d„Zd„ Zd"d„Zd„ Zd„ Zd„ Zd„ Zd#d„Zd$d„Zd„ Zd„ Zd%d„Zd„ Z d„ Z!d„ Z"y)&é    )ÚImageN©Úwrapsc                 ó.   ‡ — t        ‰ «      ˆ fd„«       }|S )a�  Creates a new function which operates on each channel

    Parameters
    ----------
    single_channel_func: function
        Function that acts on a single color channel

    Returns
    -------
    channel_func: function
        The same function that operates on all color channels

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> from scipy.signal import convolve2d
    >>> single_channel_fun = lambda x: convolve2d(x, np.ones((3, 3)), 'valid')
    >>> multi_channel_fun = apply_to_channels(single_channel_fun)
    >>> I = np.random.rand(480, 320, 3)
    >>> multi_channel_fun(I).shape
    (478, 318, 3)
    c                 óÆ  •— t        | j                  «      dk(  r ‰| g|¢­i |¤ŽS | j                  }| j                  |d   |d   d«      } t        j                  t        | j                  d   «      D �cg c]&  } ‰| d d …d d …|f   j                  «       g|¢­i |¤Ž‘Œ( c}d¬«      }|j                  t        |j                  d d «      t        |dd  «      z   «      S c c}w )Né   r   é   éÿÿÿÿ©Úaxis)ÚlenÚshapeÚreshapeÚnpÚstackÚrangeÚcopyÚlist)ÚimageÚargsÚkwargsr   ÚcÚresultÚsingle_channel_funcs         €úWC:\Users\Stabi\Downloads\virtual-tryon(1)\venv\Lib\site-packages\pymatting/util/util.pyÚmulti_channel_funcz-apply_to_channels.<locals>.multi_channel_func"   sà   ø€ äˆu�{‰{Ó˜qÒ Ù& uÐ>¨tÒ>°vÑ>Ð>à—K‘KˆEØ—M‘M %¨¡(¨E°!©H°bÓ9ˆEä—X‘Xô # 5§;¡;¨q¡>Ô2óá2˜ñ (¨ªa²°A¨g©×(;Ñ(;Ó(=ÐOÀÒOÈÓOØ2ñð ôˆFð —>‘>¤$ v§|¡|°B°QÐ'7Ó"8¼4ÀÀaÀbÀ	»?Ñ"JÓKÐKùòs   Á4+Cr   )r   r   s   ` r   Úapply_to_channelsr   	   s'   ø€ ô2 ÐÓóLó  ðLð" Ðó    c                 ó0   — t        j                  d| |«      S )a0  Computes the dot product of two vectors.

    Parameters
    ----------
    a: numpy.ndarray
        First vector (if np.ndim(a) > 1 the function calculates the product for the two last axes)
    b: numpy.ndarray
        Second vector (if np.ndim(b) > 1 the function calculates the product for the two last axes)

    Returns
    -------
    product: scalar
        Dot product of `a` and `b`

    Example
    -------
    >>> import numpy as np
    >>> from pymatting import *
    >>> a = np.ones(2)
    >>> b = np.ones(2)
    >>> vec_vec_dot(a,b)
    2.0
    z...i,...i->...©r   Úeinsum©ÚaÚbs     r   Úvec_vec_dotr%   7   s   € ô0 �9‰9Ð% q¨!Ó,Ð,r   c                 ó0   — t        j                  d| |«      S )aK  Calculates the matrix vector product for two arrays.

    Parameters
    ----------
    A: numpy.ndarray
        Matrix (if np.ndim(A) > 2 the function calculates the product for the two last axes)
    b: numpy.ndarray
        Vector (if np.ndim(b) > 1 the function calculates the product for the two last axes)

    Returns
    -------
    product: numpy.ndarray
        Matrix vector product of both arrays

    Example
    -------
    >>> import numpy as np
    >>> from pymatting import *
    >>> A = np.eye(2)
    >>> b = np.ones(2)
    >>> mat_vec_dot(A,b)
    array([1., 1.])
    z...ij,...j->...ir    )ÚAr$   s     r   Úmat_vec_dotr(   R   s   € ô0 �9‰9Ð'¨¨AÓ.Ð.r   c                 ó0   — t        j                  d| |«      S )aV  Computes the outer product of two vectors

    a: numpy.ndarray
        First vector (if np.ndim(b) > 1 the function calculates the product for the two last axes)
    b: numpy.ndarray
        Second vector (if np.ndim(b) > 1 the function calculates the product for the two last axes)

    Returns
    -------
    product: numpy.ndarray
        Outer product of `a` and `b` as numpy.ndarray

    Example
    -------
    >>> import numpy as np
    >>> from pymatting import *
    >>> a = np.arange(1,3)
    >>> b = np.arange(1,3)
    >>> vec_vec_outer(a,b)
    array([[1, 2],
           [2, 4]])
    z	...i,...jr    r"   s     r   Úvec_vec_outerr*   m   s   € ô. �9‰9�[ ! QÓ'Ð'r   c                 óÒ   — |dk  s|dkD  rt        d«      ‚|dk  s|dkD  rt        d«      ‚||kD  rt        d«      ‚| |k  }| |kD  }dt        j                  | «      z  }d||<   d||<   |S )aŠ  Fixes broken trimap :math:`T` by thresholding the values

    .. math::
        T^{\text{fixed}}_{ij}=
        \begin{cases}
            0,&\text{if } T_{ij}<\text{lower\_threshold}\\
            1,&\text{if }T_{ij}>\text{upper\_threshold}\\
            0.5, &\text{otherwise}.\\
        \end{cases}


    Parameters
    ----------
    trimap: numpy.ndarray
        Possibly broken trimap
    lower_threshold: float
        Threshold used to determine background pixels, defaults to 0.1
    upper_threshold: float
        Threshold used to determine foreground pixels, defaults to 0.9

    Returns
    -------
    fixed_trimap: numpy.ndarray
        Trimap having values in :math:`\{0, 0.5, 1\}`

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> trimap = np.array([0,0.1, 0.4, 0.9, 1])
    >>> fix_trimap(trimap, 0.2, 0.8)
    array([0. , 0. , 0.5, 1. , 1. ])
    r   r	   zInvalid lower thresholdzInvalid upper thresholdz4Lower threshold must be smaller than upper thresholdg      à?)Ú
ValueErrorr   Ú	ones_like)ÚtrimapÚlower_thresholdÚupper_thresholdÚis_bgÚis_fgÚfixeds         r   Ú
fix_trimapr4   ‡   s�   € ðD ˜Ò˜o°Ò1ÜÐ2Ó3Ð3à˜Ò˜o°Ò1ÜÐ2Ó3Ð3à˜Ò(ÜÐOÓPÐPà�_Ñ$€EØ�_Ñ$€EØ”"—,‘,˜vÓ&Ñ&€EØ€Eˆ%�LØ€Eˆ%�LØ€Lr   c                 ó:   — 	 t        | «       y# t        $ r Y yw xY w)aD  Checks if an object is iterable

    Parameters
    ----------
    obj: object
        Object to check

    Returns
    -------
    is_iterable: bool
        Boolean variable indicating whether the object is iterable

    Example
    -------
    >>> from pymatting import *
    >>> l = []
    >>> isiterable(l)
    True
    TF)ÚiterÚ	TypeError)Úobjs    r   Ú
isiterabler9   º   s#   € ð(ÜˆSŒ	ØøÜò Ùðús   ‚ Ž	™c                 óš  — t         j                  t         j                  t         j                  t         j                  t         j
                  t         j                  t         j                  dœ}t        |«      s0t        | j                  |z  «      t        | j                  |z  «      f}| j                  |||j                  «          «      } | S )N)ÚbicubicÚbilinearÚboxÚhammingÚlanczosÚnearestÚnone)r   ÚBICUBICÚBILINEARÚBOXÚHAMMINGÚLANCZOSÚNEARESTr9   ÚintÚwidthÚheightÚresizeÚlower)r   ÚsizeÚresampleÚfilterss       r   Ú_resize_pil_imagerP   Õ   s‹   € ä—=‘=Ü—N‘NÜ�y‰yÜ—=‘=Ü—=‘=Ü—=‘=Ü—‘ñ€Gô �dÔÜ�E—K‘K $Ñ&Ó'¬¨U¯\©\¸DÑ-@Ó)AÐBˆà�L‰L˜˜w x§~¡~Ó'7Ñ8Ó9€Eà€Lr   c                 óÖ   — t        j                  | «      }|�*|j                  «       }|dk(  rdn|}|j                  |«      }|�t	        |||«      }t        j                  |«      dz  }|S )a   This function can be used to load an image from a file.

    Parameters
    ----------
    path: str
        Path of image to load.
    mode: str
        Can be "GRAY", "RGB" or something else (see PIL.convert())

    Returns
    -------
    image: numpy.ndarray
        Loaded image
    ÚGRAYÚLg     ào@)r   ÚopenÚupperÚconvertrP   r   Úarray)ÚpathÚmoderM   rN   r   s        r   Ú
load_imagerZ   è   si   € ô  �J‰J�tÓ€EàÐØ�z‰z‹|ˆØ˜f’n‰s¨$ˆØ—‘˜dÓ#ˆàÐÜ! %¨¨xÓ8ˆä�H‰H�U‹O˜eÑ#€Eà€Lr   c                 ó  — |j                   t        j                  t        j                  t        j                  fv sJ ‚|j                   t        j                  t        j                  fv r7t        j
                  |dz  dd«      j                  t        j                  «      }|rGt        j                  j                  | «      \  }}t        |«      dkD  rt        j                  |d¬«       t        j                  |«      j                  | «       y)a¤  Given a path, save an image there.

    Parameters
    ----------
    path: str
        Where to save the image.
    image: numpy.ndarray, dtype in [np.uint8, np.float32, np.float64]
        Image to save.
        Images of float dtypes should be in range [0, 1].
        Images of uint8 dtype should be in range [0, 255]
    make_directory: bool
        Whether to create the directories needed for the image path.
    éÿ   r   T)Úexist_okN)Údtyper   Úuint8Úfloat32Úfloat64ÚclipÚastypeÚosrX   Úsplitr   Úmakedirsr   Ú	fromarrayÚsave)rX   r   Úmake_directoryÚ	directoryÚ_s        r   Ú
save_imagerl     s±   € ð �;‰;œ2Ÿ8™8¤R§Z¡Z´·±Ð<Ñ<Ð<Ð<à‡{�{”r—z‘z¤2§:¡:Ð.Ñ.Ü—‘˜ ™ Q¨Ó,×3Ñ3´B·H±HÓ=ˆáÜ—w‘w—}‘} TÓ*‰ˆ	�1Üˆy‹>˜AÒÜ�K‰K˜	¨DÕ1ä	‡O�O�EÓ×Ñ Õ%r   c                 óÈ  — t        | j                  «      dv sJ ‚| j                  t        j                  t        j
                  t        j                  fv sJ ‚| j                  t        j
                  t        j                  fv r7t        j                  | dz  dd«      j                  t        j                  «      } t        | j                  «      dk(  rt        j                  | gdz  d¬«      S | j                  d   dk(  rt        j                  | gdz  d¬«      S | j                  d   dk(  r| S | j                  d   dk(  r| d	d	…d	d	…d	d…f   S t        d
| j                  «      ‚)a  Convertes an image to rgb8 color space

    Parameters
    ----------
    image: numpy.ndarray
        Image to convert

    Returns
    -------
    image: numpy.ndarray
        Converted image with same height and width as input image but with three color channels
    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> I = np.eye(2)
    >>> to_rgb8(I)
    array([[[255, 255, 255],
            [  0,   0,   0]],
           [[  0,   0,   0],
            [255, 255, 255]]], dtype=uint8)
    )r   é   r\   r   r   rn   r   r	   é   NzInvalid image shape:)r   r   r^   r   r_   r`   ra   rb   rc   r   Úconcatenater,   )r   s    r   Úto_rgb8rq   "  s  € ô. ˆu�{‰{Ó˜vÑ%Ð%Ð%Ø�;‰;œ2Ÿ8™8¤R§Z¡Z´·±Ð<Ñ<Ð<Ð<à‡{�{”r—z‘z¤2§:¡:Ð.Ñ.Ü—‘˜ ™ Q¨Ó,×3Ñ3´B·H±HÓ=ˆä
ˆ5�;‰;Ó˜1ÒÜ�x‰x˜˜ !™¨!Ô,Ð,à‡{�{�1�~˜ÒÜ�~‰~˜u˜g¨™k°Ô2Ð2à	�‰�Q‰˜1Ò	Øˆà	�‰�Q‰˜1Ò	Ø’Qš˜2˜A˜2�X‰Ðä
Ð+¨U¯[©[Ó
9Ð9r   c           	      óÆ  — | D ]3  }|€Œ|j                   t        j                  t        j                  fv rŒ3J ‚ t	        | «      }|dk(  ry|€?|€=t        t        j                  t        j                  |«      «      «      }||z   dz
  |z  }n|€||z   dz
  |z  }n|€||z   dz
  |z  }| D �cg c]  }|€Œ|j                  ‘Œ }}t        d„ |D «       «      }t        d„ |D «       «      }t        |D �	cg c]  }	t	        |	«      dkD  sŒ|	d   ‘Œ c}	d¬«      }
|
dkD  rÉt        | «      D ]»  \  }}|€Œ	t	        |j                  «      dk(  r|dd…dd…t        j                  f   }|j                  d   dk(  rt        j                  |g|
z  d¬«      }|j                  d   d	k(  r=|
d
k(  r8t        |t        j                  |j                  dd |j                   ¬«      «      }|| |<   Œ½ |€t        d„ | D «       «      }t        j                   ||z  ||z  |
f|¬«      }t#        |«      D ]–  }t#        |«      D ]†  }|||z  z   }|t	        | «      k\  r Œ)| |   }|€Œ#|j%                  |j                  d   |j                  d   d«      }||||z  ||z  |j                  d   z   …||z  ||z  |j                  d   z   …f<   Œˆ Œ˜ |j                  d   dk(  r|dd…dd…df   }|S c c}w c c}	w )aU  Plots a grid of images.

    Parameters
    ----------
    images : list of numpy.ndarray
        List of images to plot
    nx: int
        Number of rows
    ny: int
        Number of columns
    dtype: type
        Data type of output array

    Returns
    -------
    grid: numpy.ndarray
       Grid of images with datatype `dtype`
    Nr   r	   c              3   ó&   K  — | ]	  }|d    –— Œ y­w)r   N© ©Ú.0r   s     r   Ú	<genexpr>zmake_grid.<locals>.<genexpr>v  ó   è ø€ Ð)¡&˜ˆE�!�H¡&ùó   ‚c              3   ó&   K  — | ]	  }|d    –— Œ y­w)r	   Nrt   ru   s     r   rw   zmake_grid.<locals>.<genexpr>w  rx   ry   r   )Údefaultr   rn   ro   ©r^   c              3   ó:   K  — | ]  }|€Œ|j                   –— Œ y ­w)Nr|   )rv   r   s     r   rw   zmake_grid.<locals>.<genexpr>‹  s   è ø€ ÐJ©f U¸Ñ8I�U—[•[©fùs   ‚Šr
   )r^   r   r`   ra   r   rH   ÚceilÚsqrtr   ÚmaxÚ	enumerateÚnewaxisrp   Ústack_imagesÚonesÚnextÚzerosr   r   )ÚimagesÚnxÚnyr^   r   ÚnÚshapesÚhÚwr   ÚdÚir   ÚyÚxs                  r   Ú	make_gridr’   N  sä  € ó& ˆØÑØ—;‘;¤2§:¡:¬r¯z©zÐ":Ò:Ð:Ð:ð ô 	ˆF‹€AàˆA‚vØà	€z�b�jÜ”—‘œŸ™ ›Ó$Ó%ˆØ�"‰f�q‰j˜RÑ‰à	ˆØ�"‰f�q‰j˜RÑ‰à	ˆØ�"‰f�q‰j˜RÑˆá'-ÓC¡v˜e°Ñ1Bˆe�k‹k v€FÐCäÑ)¡&Ó)Ó)€AÜÑ)¡&Ó)Ó)€AÜ¡6Ó<¡6˜%¬S°«Z¸!«^ˆU�1‹X 6Ñ<ÀaÔH€Aàˆ1‚uÜ! &Ö)‰HˆAˆuØÑ Ü�u—{‘{Ó# qÒ(Ø!¢!¢Q¬¯
©
Ð"2Ñ3�Eà—;‘;˜q‘> QÒ&ÜŸN™N¨E¨7°Q©;¸QÔ?�Eà—;‘;˜q‘> QÒ&¨1°ª6Ü(ØœrŸw™w u§{¡{°2°A ¸e¿k¹kÔJó�Eð "��q’	ð *ð €}ÜÑJ©fÓJÓJˆä�X‰X�q˜2‘v˜q 2™v qÐ)°Ô7€Fä�2ŽYˆÜ�r–ˆAØ�A˜‘F‘
ˆAà”C˜“KÒÙà˜1‘IˆEàÑ ØŸ™ e§k¡k°!¡n°e·k±kÀ!±nÀbÓI�ð ð Ø˜‘E˜A ™E E§K¡K°¡NÑ2Ð2°A¸±E¸AÀ¹EÀEÇKÁKÐPQÁNÑ<RÐ4RÐRòñ ð ð  ‡|�|�A�˜!ÒØšš1˜a˜‘ˆà€Mùò] Dùò =s   Â*KÂ2KÃ/KÄKc                 óÒ   — t        | «      }t        j                  |dz  dd«      j                  t        j                  «      }t        j                  |«      }|j                  «        y)zÎPlot grid of images.

    Parameters
    ----------
    images : list of numpy.ndarray
        List of images to plot
    height : int, matrix
        Height in pixels the output grid, defaults to 512

    r\   r   N)r’   r   rb   rc   r_   r   rg   Úshow)r‡   Úgrids     r   Úshow_imagesr–   ¥  sJ   € ô �VÓ€Dä�7‰7�4˜#‘:˜q #Ó&×-Ñ-¬b¯h©hÓ7€DÜ�?‰?˜4Ó €DØ‡I�I…Kr   c                 ó6  — |r| j                  «       } | j                  «       }| j                  «       }|dk  rt        j                  d|z  d¬«       |dkD  rt        j                  d|z  d¬«       | j
                  t        j                  t        j                  fvr$t        j                  d| j
                  z  d¬«       | |k\  }| |k  }|j                  «       dk(  rt        d	|z  «      ‚|j                  «       dk(  rt        d
|z  «      ‚||z  }| }	||||	fS )a  This function splits the trimap into foreground pixels, background pixels, and unknown pixels.

    Foreground pixels are pixels where the trimap has values larger than or equal to `fg_threshold` (default: 0.9).
    Background pixels are pixels where the trimap has values smaller than or equal to `bg_threshold` (default: 0.1).
    Pixels with other values are assumed to be unknown.

    Parameters
    ----------
    trimap: numpy.ndarray
        Trimap with shape :math:`h \times w`
    flatten: bool
        If true np.flatten is called on the trimap

    Returns
    -------
    is_fg: numpy.ndarray
        Boolean array indicating which pixel belongs to the foreground
    is_bg: numpy.ndarray
        Boolean array indicating which pixel belongs to the background
    is_known: numpy.ndarray
        Boolean array indicating which pixel is known
    is_unknown: numpy.ndarray
        Boolean array indicating which pixel is unknown
    bg_threshold: float
        Pixels with smaller trimap values will be considered background.
    fg_threshold: float
        Pixels with larger trimap values will be considered foreground.


    Example
    -------
    >>> import numpy as np
    >>> from pymatting import *
    >>> trimap = np.array([[1,0],[0.5,0.2]])
    >>> is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
    >>> is_fg
    array([ True, False, False, False])
    >>> is_bg
    array([False,  True, False, False])
    >>> is_known
    array([ True,  True, False, False])
    >>> is_unknown
    array([False, False,  True,  True])
    ç        z:Trimap values should be in [0, 1], but trimap.min() is %s.rn   ©Ú
stacklevelç      ð?z:Trimap values should be in [0, 1], but trimap.max() is %s.zfUnexpected trimap.dtype %s. Are you sure that you do not want to use np.float32 or np.float64 instead?r   z7Trimap did not contain background values (values <= %f)z7Trimap did not contain foreground values (values >= %f))ÚflattenÚminr€   ÚwarningsÚwarnr^   r   r`   ra   Úsumr,   )
r.   rœ   Úbg_thresholdÚfg_thresholdÚ	min_valueÚ	max_valuer2   r1   Úis_knownÚ
is_unknowns
             r   Útrimap_splitr§   ·  s   € ñZ Ø—‘Ó!ˆà—
‘
“€IØ—
‘
“€Ià�3‚Ü�‰ØHÈ9ÑTØõ	
ð
 �3‚Ü�‰ØHÈ9ÑTØõ	
ð
 ‡|�|œBŸJ™J¬¯
©
Ð3Ñ3Ü�‰ØtØ�l‰lñàõ	
ð �lÑ"€EØ�lÑ"€Eà‡y�yƒ{�aÒÜØEÈÑTó
ð 	
ð ‡y�yƒ{�aÒÜØEÈÑTó
ð 	
ð �u‰}€HØ�€Jà�%˜ :Ð-Ð-r   c                 ó  — t        | j                  «      dk7  s| j                  d   dk7  r-t        j                  dt	        | j                  «      z  d¬«       | j                  «       }| j                  «       }|dk  rt        j                  d|z  d¬«       |dkD  rt        j                  d|z  d¬«       | j                  t        j                  t        j                  fvr%t        j                  d	| j                  z  d¬«       y
y
)a‹  Performs a sanity check for input images. Image values should be in the
    range [0, 1], the `dtype` should be `np.float32` or `np.float64` and the
    image shape should be `(?, ?, 3)`.

    Parameters
    ----------
    image: numpy.ndarray
        Image with shape :math:`h \times w \times 3`

    Example
    -------
    >>> import numpy as np
    >>> from pymatting import check_image
    >>> image = (np.random.randn(64, 64, 2) * 255).astype(np.int32)
    >>> sanity_check_image(image)
    __main__:1: UserWarning: Expected RGB image of shape (?, ?, 3), but image.shape is (64, 64, 2).
    __main__:1: UserWarning: Image values should be in [0, 1], but image.min() is -933.
    __main__:1: UserWarning: Image values should be in [0, 1], but image.max() is 999.
    __main__:1: UserWarning: Unexpected image.dtype int32. Are you sure that you do not want to use np.float32 or np.float64 instead?

    rn   r   z=Expected RGB image of shape (?, ?, 3), but image.shape is %s.r™   r˜   z8Image values should be in [0, 1], but image.min() is %s.r›   z8Image values should be in [0, 1], but image.max() is %s.zeUnexpected image.dtype %s. Are you sure that you do not want to use np.float32 or np.float64 instead?N)r   r   rž   rŸ   Ústrr�   r€   r^   r   r`   ra   )r   r£   r¤   s      r   Úsanity_check_imagerª     sÛ   € ô. ˆ5�;‰;Ó˜1Ò §¡¨A¡°!Ò 3Ü�‰ØKÜ�%—+‘+Óñàõ	
ð —	‘	“€IØ—	‘	“€Ià�3‚Ü�‰ØFÈÑRØõ	
ð
 �3‚Ü�‰ØFÈÑRØõ	
ð
 ‡{�{œ2Ÿ:™:¤r§z¡zÐ2Ñ2Ü�‰ØsØ�k‰kñàö	
ð 3r   c                 ó‚   — t        |j                  «      dk(  r|dd…dd…t        j                  f   }|| z  d|z
  |z  z   S )a  This function composes a new image for given foreground image, background image and alpha matte.

    This is done by applying the composition equation

    .. math::
        I = \alpha F + (1-\alpha)B.

    Parameters
    ----------
    foreground: numpy.ndarray
        Foreground image
    background: numpy.ndarray
        Background image
    alpha: numpy.ndarray
        Alpha matte

    Returns
    -------
    image: numpy.ndarray
        Composed image as numpy.ndarray

    Example
    -------
    >>> from pymatting import *
    >>> foreground = load_image("data/lemur/lemur_foreground.png", "RGB")
    >>> background = load_image("data/lemur/beach.png", "RGB")
    >>> alpha = load_image("data/lemur/lemur_alpha.png", "GRAY")
    >>> I = blend(foreground, background, alpha)
    r   Nr	   )r   r   r   r‚   )Ú
foregroundÚ
backgroundÚalphas      r   Úblendr¯   E  sC   € ô< ˆ5�;‰;Ó˜1ÒØ’ašœBŸJ™JÐ&Ñ'ˆà�:Ñ  U¡¨jÑ 8Ñ8Ð8r   c                  ó¼   — | D �cg c]6  }t        |j                  «      dk(  r|n|dd…dd…t        j                  f   ‘Œ8 } }t        j                  | d¬«      S c c}w )a  This function stacks images along the third axis.
    This is useful for combining e.g. rgb color channels or color and alpha channels.

    Parameters
    ----------
    *images: numpy.ndarray
        Images to be stacked.

    Returns
    -------
    image: numpy.ndarray
        Stacked images as numpy.ndarray

    Example
    -------
    >>> from pymatting.util.util import stack_images
    >>> import numpy as np
    >>> I = stack_images(np.random.rand(4,5,3), np.random.rand(4,5,3))
    >>> I.shape
    (4, 5, 6)
    rn   Nr   r   )r   r   r   r‚   rp   )r‡   r   s     r   rƒ   rƒ   i  sa   € ñ0 óáˆEô �e—k‘kÓ" aÒ'‰¨U²1²a¼¿¹Ð3CÑ-DÑ	DØð ð ô �>‰>˜& qÔ)Ð)ùò	s   …;Ac                 ó~   — | j                  t        j                  | j                  d   | j                  «      «      }|S )aæ  Calculate the sum of each row of a matrix

    Parameters
    ----------
    A: np.ndarray or scipy.sparse.spmatrix
        Matrix to sum rows of

    Returns
    -------
    row_sums: np.ndarray
        Vector of summed rows

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> A = np.random.rand(2,2)
    >>> A
    array([[0.62750946, 0.12917617],
           [0.8599449 , 0.5777254 ]])
    >>> row_sum(A)
    array([0.75668563, 1.4376703 ])
    r	   )Údotr   r„   r   r^   )r'   Úrow_sumss     r   Úrow_sumr´   †  s.   € ð0 �u‰u”R—W‘W˜QŸW™W Q™Z¨¯©Ó1Ó2€Hà€Or   c                 ó–   — t        | «      }d|||k  <   d|z  }t        j                  j                  |«      }|j	                  | «      } | S )a  Normalize the rows of a matrix

    Rows with sum below threshold are left as-is.

    Parameters
    ----------
    A: scipy.sparse.spmatrix
        Matrix to normalize
    threshold: float
        Threshold to avoid division by zero

    Returns
    -------
    A: scipy.sparse.spmatrix
        Matrix with normalized rows

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> A = np.arange(4).reshape(2,2)
    >>> normalize_rows(A)
    array([[0. , 1. ],
           [0.4, 0.6]])
    r›   )r´   ÚscipyÚsparseÚdiagsr²   )r'   Ú	thresholdr³   Úrow_normalization_factorsÚDs        r   Únormalize_rowsr¼   £  sO   € ô4 �q‹z€Hð &)€HˆX˜	Ñ!Ñ"à # h¡Ðä�‰×ÑÐ4Ó5€Aà	�‰ˆa‹€Aà€Hr   c                 ó@  — |rVt        j                  t        j                  | «      |«      }t        j                  t        j                  |«      | «      }||fS t        j                  | «      }t        j                  |«      }t        j                  ||«      \  }}||fS )ap  Calculates image pixel coordinates for an image with a specified shape

    Parameters
    ----------
    width: int
        Width of the input image
    height: int
        Height of the input image
    flatten: bool
        Whether the array containing the coordinates should be flattened or not, defaults to False

    Returns
    -------
    x: numpy.ndarray
        x coordinates
    y: numpy.ndarray
        y coordinates

    Example
    -------
    >>> from pymatting import *
    >>> x, y = grid_coordinates(2,2)
    >>> x
    array([[0, 1],
           [0, 1]])
    >>> y
    array([[0, 0],
           [1, 1]])
    )r   ÚtileÚarangeÚrepeatÚmeshgrid)rI   rJ   rœ   r‘   r�   s        r   Úgrid_coordinatesrÂ   Ë  s   € ñ< Ü�G‰G”B—I‘I˜eÓ$ fÓ-ˆÜ�I‰I”b—i‘i Ó'¨Ó/ˆð ˆaˆ4€Kô �I‰I�eÓˆÜ�I‰I�fÓˆä�{‰{˜1˜aÓ ‰ˆˆ1àˆaˆ4€Kr   c                 óÂ  — t        j                  |«      j                  «       }t        |«      }| |z  }t        j                  ||z  t         j
                  ¬«      }t        j                  ||z  t         j
                  ¬«      }	t        j                  ||z  t         j                  ¬«      }
d}t        | |d¬«      \  }}t        |||«      D ]i  \  }}}t        j                  ||z   d| dz
  «      }t        j                  ||z   d|dz
  «      }||| z  z   ||||z    ||| z  z   |	|||z    ||
|||z    ||z  }Œk t        j                  j                  |
||	ff||f¬«      }|S )aº  Calculates a convolution matrix that can be applied to a vectorized image

    Additionally, this function allows to specify which pixels should be used for the convoltion, i.e.

    .. math:: \left(I * K\right)_{ij} = \sum_k K_k I_{i+{\Delta_y}_k,j+{\Delta_y}_k},

    where :math:`K` is the flattened convolution kernel.

    Parameters
    ----------
    width: int
        Width of the input image
    height: int
        Height of the input image
    kernel: numpy.ndarray
        Convolutional kernel
    dx: numpy.ndarray
        Offset in x direction
    dy: nunpy.ndarray
        Offset in y direction

    Returns
    -------
    M: scipy.sparse.csr_matrix
        Convolution matrix
    r|   r   T©rœ   r	   )r   )r   Úasarrayrœ   r   r†   Úint32ra   rÂ   Úziprb   r¶   r·   Ú
csr_matrix)rI   rJ   ÚkernelÚdxÚdyÚweightsÚcountrŠ   Úi_indsÚj_indsÚvaluesÚkr‘   r�   Údx2Údy2ÚweightÚx2Úy2r'   s                       r   Úsparse_conv_matrix_with_offsetsr×   õ  sQ  € ô6 �j‰j˜Ó ×(Ñ(Ó*€GÜ�‹L€EØ�‰€Aä�X‰X�a˜%‘i¤r§x¡xÔ0€FÜ�X‰X�a˜%‘i¤r§x¡xÔ0€FÜ�X‰X�a˜%‘i¤r§z¡zÔ2€Fà	€AÜ˜E 6°4Ô8�D€A€qÜ  B¨Ö0ÑˆˆS�&Ü�W‰W�Q˜‘W˜a ¨¡Ó+ˆÜ�W‰W�Q˜‘W˜a ¨!¡Ó,ˆØ  E¡	™Mˆˆq�1�q‘5ÐØ  e¡™Oˆˆq�1�q‘5ÐØ"ˆˆq�1�q‘5ÐØ	ˆQ‰‰ð 1ô 	�‰×Ñ ¨&°&Ð)9Ð :À1ÀaÀ&ÐÓI€Aà€Hr   c                 ó€   — |j                   \  }}t        ||d¬«      \  }}||dz  z  }||dz  z  }t        | ||||«      S )aR  Calculates a convolution matrix that can be applied to a vectorized image

    Parameters
    ----------
    width: int
        Width of the input image
    height: int
        Height of the input image
    kernel: numpy.ndarray
        Convolutional kernel

    Returns
    -------
    M: scipy.sparse.csr_matrix
        Convolution matrix

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> sparse_conv_matrix(3,3,np.ones((3,3)))
    <9x9 sparse matrix of type '<class 'numpy.float64'>'
    with 49 stored elements in Compressed Sparse Row format>
    TrÄ   r   )r   rÂ   r×   )rI   rJ   rÉ   ÚkhÚkwr‘   r�   s          r   Úsparse_conv_matrixrÛ   '  sP   € ð2 �\‰\�F€BˆÜ˜B ¨DÔ1�D€A€qØˆˆq‰�L€AØˆˆq‰�L€Aä*¨5°&¸&À!ÀQÓGÐGr   c                 ó„   — |rt        | «      } |t        | «      z   }t        j                  j	                  |«      }|| z
  }|S )aÖ  Calculates the random walk normalized Laplacian matrix from the weight matrix

    Parameters
    ----------
    W: numpy.ndarray
        Array of weights
    normalize: bool
        Whether the rows of W should be normalized to 1, defaults to True
    regularization: float
        Regularization strength, defaults to 0, i.e. no regularizaion

    Returns
    -------
    L: scipy.sparse.spmatrix
        Laplacian matrix

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> weights_to_laplacian(np.ones((4,4)))
    matrix([[ 0.75, -0.25, -0.25, -0.25],
            [-0.25,  0.75, -0.25, -0.25],
            [-0.25, -0.25,  0.75, -0.25],
            [-0.25, -0.25, -0.25,  0.75]])
    )r¼   r´   r¶   r·   r¸   )ÚWÚ	normalizeÚregularizationrŽ   r»   rS   s         r   Úweights_to_laplacianrà   H  sA   € ñ6 Ü˜1Óˆàœ ›Ñ#€AÜ�‰×Ñ˜1Ó€Aà	ˆA‰€Aà€Hr   c                 ó‚   — t        j                  | «      } | j                  «       }| j                  «       }| |z
  ||z
  z  S )a€  Normalizes an array such that all values are between 0 and 1

    Parameters
    ----------
    values: numpy.ndarray
        Array to normalize

    Returns
    -------
    result: numpy.ndarray
        Normalized array

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> normalize(np.array([0, 1, 3, 10]))
    array([0. , 0.1, 0.3, 1. ])
    )r   rÅ   r�   r€   )rÐ   r#   r$   s      r   rÞ   rÞ   n  s;   € ô( �Z‰Z˜Ó€FØ�
‰
‹€AØ�
‰
‹€AØ�Q‰J˜1˜q™5Ñ!Ð!r   c                 ó   — | |z   dz
  |z  S )a1  Divides a number x by another integer n and rounds up the result

    Parameters
    ----------
    x: int
        Numerator
    n: int
        Denominator

    Returns
    -------
    result: int
        Result

    Example
    -------
    >>> from pymatting import *
    >>> div_round_up(3,2)
    2
    r	   rt   )r‘   rŠ   s     r   Údiv_round_uprã   ˆ  s   € ð* �‰E�A‰I˜!ÑÐr   c                 ó®  — ||z
  }t        j                  | |z
  |z  d¬«      t        j                  t        j                  |«      «      z  }t        j                  |dd«      }|dd…dd…df   }t        j                  | d|z
  |z  z
  |t        j
                  | «      |dk7  ¬«      }t        j                  |dd«      }t        j                  ||g«      }|S )a½  Remove background from image with at most two colors.
    Might not work if image has more than two colors.

    Parameters
    ----------
    image: numpy.ndarray
        RGB input image
    fg_color: numpy.ndarray
        RGB Foreground color
    bg_color: numpy.ndarray
        RGB Background color

    Returns
    -------
    output: numpy.ndarray
        RGBA output image

    Example
    -------
    >>> from pymatting import *
    >>> import numpy as np
    >>> image = np.random.rand(480, 320, 3)
    >>> fg_color = np.random.rand(3)
    >>> bg_color = np.random.rand(3)
    >>> output = remove_background_bicolor(image, fg_color, bg_color)
    >>> print(output.shape)
    (480, 320, 4)
    r
   r   r˜   r›   Nr	   )ÚoutÚwhere)r   r    Úsquarerb   ÚdivideÚ
zeros_likeÚdstack)	r   Úfg_colorÚbg_colorÚfg_bgÚur®   r#   Úactual_colorÚoutputs	            r   Úremove_background_bicolorrñ      sÃ   € ð< �xÑ€Eô 	�‰�˜Ñ  EÑ)°Ô3´b·f±f¼R¿Y¹YÀuÓ=MÓ6NÑN€AÜ�G‰G�A�s˜CÓ €Eð
 	Ša’�DˆjÑ€Aä—9‘9Ø	�!�a‘%˜8Ñ#Ñ	# a¬R¯]©]¸5Ó-AÈÈcÉô€Lô —7‘7˜<¨¨cÓ2€Lä�Y‰Y˜ eÐ,Ó-€Fà€Mr   )çš™™™™™¹?çÍÌÌÌÌÌì?)r;   )NNr=   )T)NNN)Trò   ró   )r˜   )F)Tr˜   )#ÚPILr   Únumpyr   Úscipy.sparser¶   rd   rž   Ú	functoolsr   r   r%   r(   r*   r4   r9   rP   rZ   rl   rq   r’   r–   r§   rª   r¯   rƒ   r´   r¼   rÂ   r×   rÛ   rà   rÞ   rã   rñ   rt   r   r   Ú<module>rø      s£   ðÝ Û Û Û 	Û Ý ò+ò\-ò6/ò6(ó40òfó6ó&ó>&ò6):óXTònó$V.òr2
òj!9òH*ò:ó:%óP'òT/òdHóB#òL"ò4ó01r   