§
    +Áôg•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"dS )-é    )Ú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‰¢R i ‰¤ŽS ‰ j        }‰                      |d         |d         d¦  «        Š t          j        ˆˆ ˆˆfd„t          ‰ j        d         ¦  «        D ¦   «         d¬¦  «        }|                     t          |j        d d…         ¦  «        t          |dd …         ¦  «        z   ¦  «        S )Né   r   é   éÿÿÿÿc                 óf   •— g | ]-} ‰‰d d …d d …|f                               ¦   «         g‰¢R i ‰¤Ž‘Œ.S ©N)Úcopy)Ú.0ÚcÚargsÚimageÚkwargsÚsingle_channel_funcs     €€€€ú\/var/www/html/bac/bac_backend/python/env/lib/python3.11/site-packages/pymatting/util/util.pyú
<listcomp>zAapply_to_channels.<locals>.multi_channel_func.<locals>.<listcomp>+   sb   ø€ ð ð ð àð (Ð'¨¨a¨a¨a°°°°A¨g¬×(;Ò(;Ñ(=Ô(=ÐOÀÐOÐOÐOÈÐOÐOðð ð ó    ©Úaxis)ÚlenÚshapeÚreshapeÚnpÚstackÚrangeÚlist)r   r   r   r   Úresultr   s   ```  €r   Úmulti_channel_funcz-apply_to_channels.<locals>.multi_channel_func"   sø   øøøø€ åˆuŒ{ÑÔ˜qÒ Ð Ø&Ð& uÐ>¨tÐ>Ð>Ð>°vÐ>Ð>Ð>à”KˆEØ—M’M %¨¤(¨E°!¬H°bÑ9Ô9ˆEå”Xðð ð ð ð ð ð å" 5¤;¨q¤>Ñ2Ô2ðñ ô ð ðñ ô ˆFð —>’>¥$ v¤|°B°Q°BÔ'7Ñ"8Ô"8½4ÀÀaÀbÀbÄ	¹?¼?Ñ"JÑKÔKÐKr   r   )r   r!   s   ` r   Úapply_to_channelsr"   	   s?   ø€ õ2 ÐÑÔðLð Lð Lð Lñ  ÔðLð" Ðr   c                 ó.   — 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Ð% q¨!Ñ,Ô,Ð,r   c                 ó.   — 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Ð'¨¨AÑ.Ô.Ð.r   c                 ó.   — 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�[ ! QÑ'Ô'Ð'r   çš™™™™™¹?çÍÌÌÌÌÌì?c                 óö   — |dk     s|dk    rt          d¦  «        ‚|dk     s|dk    rt          d¦  «        ‚||k    rt          d¦  «        ‚| |k     }| |k    }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_trimapr:   ‡   s¦   € ðD ˜ÒÐ˜o°Ò1Ð1ÝÐ2Ñ3Ô3Ð3à˜ÒÐ˜o°Ò1Ð1ÝÐ2Ñ3Ô3Ð3à˜Ò(Ð(ÝÐOÑPÔPÐPà�_Ò$€EØ�_Ò$€EØ•"”,˜vÑ&Ô&Ñ&€EØ€Eˆ%�LØ€Eˆ%�LØ€Lr   c                 óH   — 	 t          | ¦  «         dS # t          $ r Y dS 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   Ú
isiterabler?   º   s9   € ð(ÝˆS‰	Œ	ˆ	ØˆtøÝð ð ð Øˆuˆuðøøøs   ‚ “
! !Úbicubicc                 ó|  — t           j        t           j        t           j        t           j        t           j        t           j        t           j        dœ}t          |¦  «        s.t          | j	        |z  ¦  «        t          | j
        |z  ¦  «        f}|                      |||                     ¦   «                  ¦  «        } | S )N)r@   ÚbilinearÚboxÚhammingÚlanczosÚnearestÚnone)r   ÚBICUBICÚBILINEARÚBOXÚHAMMINGÚLANCZOSÚNEARESTr?   ÚintÚwidthÚheightÚresizeÚlower)r   ÚsizeÚresampleÚfilterss       r   Ú_resize_pil_imagerV   Õ   s“   € å”=Ý”NÝŒyÝ”=Ý”=Ý”=Ý”ðð €Gõ �dÑÔð CÝ�E”K $Ñ&Ñ'Ô'­¨U¬\¸DÑ-@Ñ)AÔ)AÐBˆà�LŠL˜˜w x§~¢~Ñ'7Ô'7Ô8Ñ9Ô9€Eà€Lr   rC   c                 óì   — t          j        | ¦  «        }|�3|                     ¦   «         }|dk    rdn|}|                     |¦  «        }|�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
    NÚGRAYÚLg     ào@)r   ÚopenÚupperÚconvertrV   r   Úarray)ÚpathÚmoderS   rT   r   s        r   Ú
load_imager`   è   sv   € õ  ŒJ�tÑÔ€EàÐØ�zŠz‰|Œ|ˆØ˜f’n�nˆsˆs¨$ˆØ—’˜dÑ#Ô#ˆàÐÝ! %¨¨xÑ8Ô8ˆåŒH�U‰OŒO˜eÑ#€Eà€Lr   Tc                 óð  — |j         t          j        t          j        t          j        fv sJ ‚|j         t          j        t          j        fv r6t          j        |dz  dd¦  «                             t          j        ¦  «        }|rKt          j         	                    | ¦  «        \  }}t          |¦  «        dk    rt          j        |d¬¦  «         t          j        |¦  «                             | ¦  «         dS )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Úosr^   Úsplitr   Úmakedirsr   Ú	fromarrayÚsave)r^   r   Úmake_directoryÚ	directoryÚ_s        r   Ú
save_imagerr     sÊ   € ð Œ;�2œ8¥R¤Zµ´Ð<Ð<Ð<Ð<Ð<à„{•r”z¥2¤:Ð.Ð.Ð.Ý”˜ ™ Q¨Ñ,Ô,×3Ò3µB´HÑ=Ô=ˆàð 2Ý”w—}’} TÑ*Ô*‰ˆ	�1Ýˆy‰>Œ>˜AÒÐÝŒK˜	¨DÐ1Ñ1Ô1Ð1å	„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 r6t          j        | dz  dd¦  «                             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   é   rb   r   r   rt   r   r	   é   NzInvalid image shape:)r   r   rd   r   re   rf   rg   rh   ri   r   Úconcatenater2   )r   s    r   Úto_rgb8rw   "  s.  € õ. ˆuŒ{ÑÔ˜vÐ%Ð%Ð%Ð%ØŒ;�2œ8¥R¤Zµ´Ð<Ð<Ð<Ð<Ð<à„{•r”z¥2¤:Ð.Ð.Ð.Ý”˜ ™ Q¨Ñ,Ô,×3Ò3µB´HÑ=Ô=ˆå
ˆ5Œ;ÑÔ˜1ÒÐÝŒx˜˜ !™¨!Ð,Ñ,Ô,Ð,à„{�1„~˜ÒÐÝŒ~˜u˜g¨™k°Ð2Ñ2Ô2Ð2à	Œ�QŒ˜1Ò	Ð	Øˆà	Œ�QŒ˜1Ò	Ð	Ø�Q�Q�Q˜˜˜˜2˜A˜2�XŒÐå
Ð+¨U¬[Ñ
9Ô
9Ð9r   c           	      ó’  — | D ]%}|�!|j         t          j        t          j        fv sJ ‚Œ&t	          | ¦  «        }|dk    rdS |€A|€?t          t          j        t          j        |¦  «        ¦  «        ¦  «        }||z   dz
  |z  }n|€||z   dz
  |z  }n|€||z   dz
  |z  }d„ | D ¦   «         }t          d„ |D ¦   «         ¦  «        }t          d„ |D ¦   «         ¦  «        }t          d„ |D ¦   «         d¬¦  «        }	|	dk    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    r6t          |t          j        |j
        dd	…         |j         ¬¦  «        ¦  «        }|| |
<   Œ¶|€t          d„ | D ¦   «         ¦  «        }t          j        ||z  ||z  |	f|¬¦  «        }t#          |¦  «        D ]›}t#          |¦  «        D ]‰}|||z  z   }
|
t	          | ¦  «        k    r nk| |
         }|�`|                     |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 )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                 ó    — g | ]}|®|j         ‘ŒS r   ©r   ©r   r   s     r   r   zmake_grid.<locals>.<listcomp>t  s   € ÐCÐCÐC˜e°Ð1BˆeŒkÐ1BÐ1BÐ1Br   c              3   ó&   K  — | ]}|d          V — ŒdS )r   N© ©r   r   s     r   ú	<genexpr>zmake_grid.<locals>.<genexpr>v  ó&   è è € Ð)Ð)˜ˆE�!ŒHÐ)Ð)Ð)Ð)Ð)Ð)r   c              3   ó&   K  — | ]}|d          V — ŒdS )r	   Nr}   r~   s     r   r   zmake_grid.<locals>.<genexpr>w  r€   r   c                 óD   — g | ]}t          |¦  «        d k    ¯|d          ‘ŒS )r   )r   r~   s     r   r   zmake_grid.<locals>.<listcomp>x  s'   € Ð<Ð<Ð<˜%­S°©Z¬Z¸!ª^¨^ˆU�1ŒX¨^¨^¨^r   )Údefaultr   r   rt   ru   ©rd   c              3   ó(   K  — | ]}|®|j         V — Œd S r   r„   r{   s     r   r   zmake_grid.<locals>.<genexpr>‹  s)   è è € ÐJÐJ U¸Ð8I�U”[Ð8IÐ8IÐ8IÐ8IÐJÐJr   r
   )rd   r   rf   rg   r   rN   ÚceilÚsqrtÚmaxÚ	enumerater   Únewaxisrv   Ústack_imagesÚonesÚnextÚzerosr   r   )ÚimagesÚnxÚnyrd   r   ÚnÚshapesÚhÚwÚdÚir    ÚyÚxs                 r   Ú	make_gridrš   N  s:  € ð& ð ;ð ;ˆØÐØ”;¥2¤:­r¬zÐ":Ð:Ð:Ð:Ð:øåˆF‰Œ€AàˆA‚v€vØˆà	€z�b�jÝ•”�œ ™œÑ$Ô$Ñ%Ô%ˆØ�"‰f�q‰j˜RÑˆˆà	ˆØ�"‰f�q‰j˜RÑˆˆà	ˆØ�"‰f�q‰j˜RÑˆàCÐC vÐCÑCÔC€FåÐ)Ð) &Ð)Ñ)Ô)Ñ)Ô)€AÝÐ)Ð) &Ð)Ñ)Ô)Ñ)Ô)€AÝÐ<Ð< 6Ð<Ñ<Ô<ÀaÐHÑHÔH€Aàˆ1‚u€uÝ! &Ñ)Ô)ð 	"ð 	"‰HˆAˆuØÐ Ý�u”{Ñ#Ô# qÒ(Ð(Ø! ! ! ! Q Q Q­¬
Ð"2Ô3�Eà”;˜q”> QÒ&Ð&ÝœN¨E¨7°Q©;¸QÐ?Ñ?Ô?�Eà”;˜q”> QÒ&Ð&¨1°ª6¨6Ý(Ø�rœw u¤{°2°A°2¤¸e¼kÐJÑJÔJñô �Eð "��q‘	øà€}ÝÐJÐJ¨fÐJÑJÔJÑJÔJˆåŒX�q˜2‘v˜q 2™v qÐ)°Ð7Ñ7Ô7€Få�2‰YŒYð ð ˆÝ�r‘”ð 	ð 	ˆAØ�A˜‘F‘
ˆAà•C˜‘K”KÒÐØ�à˜1”IˆEàÐ ØŸš e¤k°!¤n°e´kÀ!´nÀbÑIÔI�ð ð Ø˜‘E˜A ™E E¤K°¤NÑ2Ð2°A¸±E¸AÀ¹EÀEÄKÐPQÄNÑ<RÐ4RÐRñøøð „|�A„˜!ÒÐØ˜˜˜˜1˜1˜1˜a˜”ˆà€Mr   c                 óà   — t          | ¦  «        }t          j        |dz  dd¦  «                             t          j        ¦  «        }t          j        |¦  «        }|                     ¦   «          dS )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

    rb   r   N)rš   r   rh   ri   re   r   rm   Úshow)r�   Úgrids     r   Úshow_imagesrž   ¥  sX   € õ �VÑÔ€DåŒ7�4˜#‘:˜q #Ñ&Ô&×-Ò-­b¬hÑ7Ô7€DÝŒ?˜4Ñ Ô €DØ‡I‚I�K„K€K€K€Kr   c                 óP  — |r|                       ¦   «         } |                      ¦   «         }|                      ¦   «         }|dk     rt          j        d|z  d¬¦  «         |dk    rt          j        d|z  d¬¦  «         | j        t          j        t          j        fvrt          j        d| j        z  d¬¦  «         | |k    }| |k    }| 	                    ¦   «         dk    rt          d	|z  ¦  «        ‚| 	                    ¦   «         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.rt   ©Ú
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Úwarnrd   r   rf   rg   Úsumr2   )
r4   r¤   Úbg_thresholdÚfg_thresholdÚ	min_valueÚ	max_valuer8   r7   Úis_knownÚ
is_unknowns
             r   Útrimap_splitr¯   ·  sf  € ðZ ð "Ø—’Ñ!Ô!ˆà—
’
‘”€IØ—
’
‘”€Ià�3‚€ÝŒØHÈ9ÑTØð	
ñ 	
ô 	
ð 	
ð
 �3‚€ÝŒØHÈ9ÑTØð	
ñ 	
ô 	
ð 	
ð
 „|�BœJ­¬
Ð3Ð3Ð3ÝŒØtØŒlñàð	
ñ 	
ô 	
ð 	
ð �lÒ"€EØ�lÒ"€Eà‡y‚y�{„{�aÒÐÝØEÈÑTñ
ô 
ð 	
ð ‡y‚y�{„{�aÒÐÝØEÈÑTñ
ô 
ð 	
ð �u‰}€HØ�€Jà�%˜ :Ð-Ð-r   c                 óø  — t          | j        ¦  «        dk    s| j        d         dk    r+t          j        dt	          | j        ¦  «        z  d¬¦  «         |                      ¦   «         }|                      ¦   «         }|dk     rt          j        d|z  d¬¦  «         |dk    rt          j        d|z  d¬¦  «         | j        t          j	        t          j
        fvr t          j        d	| j        z  d¬¦  «         d
S d
S )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?

    rt   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ˆ   rd   r   rf   rg   )r   r«   r¬   s      r   Úsanity_check_imager²     s%  € õ. ˆ5Œ;ÑÔ˜1ÒÐ ¤¨A¤°!Ò 3Ð 3ÝŒØKÝ�%”+ÑÔñàð	
ñ 	
ô 	
ð 	
ð —	’	‘”€IØ—	’	‘”€Ià�3‚€ÝŒØFÈÑRØð	
ñ 	
ô 	
ð 	
ð
 �3‚€ÝŒØFÈÑRØð	
ñ 	
ô 	
ð 	
ð
 „{�2œ:¥r¤zÐ2Ð2Ð2ÝŒØsØŒkñàð	
ñ 	
ô 	
ð 	
ð 	
ð 	
ð 3Ð2r   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  sM   € õ< ˆ5Œ;ÑÔ˜1ÒÐØ�a�a�a˜˜˜�BœJÐ&Ô'ˆà�:Ñ  U¡¨jÑ 8Ñ8Ð8r   c                  óF   — d„ | D ¦   «         } t          j        | d¬¦  «        S )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)
    c                 ót   — g | ]5}t          |j        ¦  «        d k    r|n|dd…dd…t          j        f         ‘Œ6S )rt   Nr´   r{   s     r   r   z stack_images.<locals>.<listcomp>  sV   € ð ð ð àõ �e”kÑ"Ô" aÒ'Ð'ˆˆ¨U°1°1°1°a°a°a½¼Ð3CÔ-Dðð ð r   r   r   )r   rv   )r�   s    r   r‹   r‹   i  s7   € ð,ð àðñ ô €Fõ Œ>˜& qÐ)Ñ)Ô)Ð)r   c                 óv   — |                       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   rd   )r+   Úrow_sumss     r   Úrow_sumr¾   †  s.   € ð0 �uŠu•R”W˜QœW QœZ¨¬Ñ1Ô1Ñ2Ô2€Hà€Or   r    c                 ó¨   — t          | ¦  «        }d|||k     <   d|z  }t          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Æ   £  sT   € õ4 �q‰zŒz€Hð &)€HˆX˜	Ò!Ñ"à # h¡ÐåŒ×ÒÐ4Ñ5Ô5€Aà	�Šˆa‰Œ€Aà€Hr   Fc                 ó,  — |rOt          j        t          j        | ¦  «        |¦  «        }t          j        t          j        |¦  «        | ¦  «        }n@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)rO   rP   r¤   r™   r˜   s        r   Úgrid_coordinatesrÌ   Ë  s€   € ð< ð !ÝŒG•B”I˜eÑ$Ô$ fÑ-Ô-ˆÝŒI•b”i Ñ'Ô'¨Ñ/Ô/ˆˆåŒI�eÑÔˆÝŒI�fÑÔˆåŒ{˜1˜aÑ Ô ‰ˆˆ1àˆaˆ4€Kr   c                 óÆ  — t          j        |¦  «                             ¦   «         }t          |¦  «        }| |z  }t          j        ||z  t           j        ¬¦  «        }t          j        ||z  t           j        ¬¦  «        }	t          j        ||z  t           j        ¬¦  «        }
d}t          | |d¬¦  «        \  }}t          |||¦  «        D ]m\  }}}t          j	        ||z   d| dz
  ¦  «        }t          j	        ||z   d|dz
  ¦  «        }||| z  z   ||||z   …<   ||| z  z   |	|||z   …<   ||
|||z   …<   ||z  }Œnt          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	   rz   )r   Úasarrayr¤   r   rŽ   Úint32rg   rÌ   Úziprh   rÀ   rÁ   Ú
csr_matrix)rO   rP   ÚkernelÚdxÚdyÚweightsÚcountr’   Úi_indsÚj_indsÚvaluesÚkr™   r˜   Údx2Údy2ÚweightÚx2Úy2r+   s                       r   Úsparse_conv_matrix_with_offsetsrá   õ  st  € õ6 Œj˜Ñ Ô ×(Ò(Ñ*Ô*€GÝ�‰LŒL€EØ�‰€AåŒX�a˜%‘i¥r¤xÐ0Ñ0Ô0€FÝŒX�a˜%‘i¥r¤xÐ0Ñ0Ô0€FÝŒX�a˜%‘i¥r¤zÐ2Ñ2Ô2€Fà	€AÝ˜E 6°4Ð8Ñ8Ô8�D€A€qÝ  B¨Ñ0Ô0ð ð ÑˆˆS�&ÝŒW�Q˜‘W˜a ¨¡Ñ+Ô+ˆÝŒW�Q˜‘W˜a ¨!¡Ñ,Ô,ˆØ  E¡	™Mˆˆq�1�q‘5ˆyÑØ  e¡™Oˆˆq�1�q‘5ˆyÑØ"ˆˆq�1�q‘5ˆyÑØ	ˆQ‰ˆˆåŒ×Ò ¨&°&Ð)9Ð :À1ÀaÀ&ÐÑIÔ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á   )rO   rP   rÓ   ÚkhÚkwr™   r˜   s          r   Úsparse_conv_matrixrå   '  sW   € ð2 Œ\�F€BˆÝ˜B ¨DÐ1Ñ1Ô1�D€A€qØˆˆq‰�L€AØˆˆq‰�L€Aå*¨5°&¸&À!ÀQÑGÔGÐGr   c                 ó”   — |rt          | ¦  «        } |t          | ¦  «        z   }t          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Å   rY   s         r   Úweights_to_laplacianrê   H  sL   € ð6 ð Ý˜1ÑÔˆà� ™œÑ#€AÝŒ×Ò˜1ÑÔ€Aà	ˆA‰€Aà€Hr   c                 ó�   — t          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˜ÑÔ€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	   r}   )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k    ¬¦  «        }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¨   Úsquarerh   Ú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Ñ3Ô3µb´f½R¼YÀuÑ=MÔ=MÑ6NÔ6NÑN€AÝŒG�A�s˜CÑ Ô €Eð
 	ˆaˆaˆa����DˆjÔ€Aå”9Ø	�!�a‘%˜8Ñ#Ñ	# a­R¬]¸5Ñ-AÔ-AÈÈcÊðñ ô €Lõ ”7˜<¨¨cÑ2Ô2€LåŒY˜ eÐ,Ñ-Ô-€Fà€Mr   )r/   r0   )r@   )NNrC   )T)NNN)Tr/   r0   )r    )F)Tr    )#ÚPILr   Únumpyr   Úscipy.sparserÀ   rj   r¦   Ú	functoolsr   r"   r)   r,   r.   r:   r?   rV   r`   rr   rw   rš   rž   r¯   r²   r¸   r‹   r¾   rÆ   rÌ   rá   rå   rê   rè   rí   rû   r}   r   r   ú<module>r      s  ðØ Ð Ð Ð Ð Ð Ø Ð Ð Ð Ø Ð Ð Ð Ø 	€	€	€	Ø €€€Ø Ð Ð Ð Ð Ð ð+ð +ð +ð\-ð -ð -ð6/ð /ð /ð6(ð (ð (ð40ð 0ð 0ð 0ðfð ð ð6ð ð ð ð&ð ð ð ð>&ð &ð &ð &ð6):ð ):ð ):ðXTð Tð Tð Tðnð ð ð$V.ð V.ð V.ð V.ðr2
ð 2
ð 2
ðj!9ð !9ð !9ðH*ð *ð *ð:ð ð ð:%ð %ð %ð %ðP'ð 'ð 'ð 'ðT/ð /ð /ðdHð Hð HðB#ð #ð #ð #ðL"ð "ð "ð4ð ð ð01ð 1ð 1ð 1ð 1r   