U
    !?h¯  ã                   @   sD   d dl Zd dlZd dlmZ d dlmZ ddgddgdfd	d
„ZdS )é    N)Úknn)Únormalize_rowsé   é
   g       @gš™™™™™¹?Úbinaryc                 C   sº  | j dd… \}}|  dd¡j\}}}|| }	|dkrFtd| d ƒ‚t t dd	|¡|¡}
t t dd	|¡|¡}g g g   }}}t||ƒD ]È\}}tj	|||||
 || gd	tj
|	d
ftjdd}t|||d\}}| t t |	¡|¡¡ | | ¡ ¡ t ||	 ¡}|dkrJ|t ||d  ||d   ¡jd	d|j d	  8 }| |¡ qŒt || ¡}t || ¡}t || ¡}tj |||ff|	|	f¡}t|ƒ}tj |	¡}|| }|S )aX  
    This function calculates the KNN matting Laplacian matrix similar to
    :cite:`chen2013knn`.
    We use a kernel of 1 instead of a soft kernel by default since the former is
    faster to compute and both produce almost identical results in all our
    experiments, which is to be expected as the soft kernel is very close to 1
    in most cases.

    Parameters
    ----------
    image: numpy.ndarray
        Image with shape :math:`h\times w \times 3`
    n_neighbors: list of ints
        Number of neighbors to consider. If :code:`len(n_neighbors)>1` multiple
        nearest neighbor calculations are done and merged, defaults to
        `[20, 10]`, i.e. first 20 neighbors are considered and in the second run
        :math:`10` neighbors. The pixel distances are then weighted by the
        :code:`distance_weights`.
    distance_weights: list of floats
        Weight of distance in feature vector, defaults to `[2.0, 0.1]`.
    kernel: str
        Must be either "binary" or "soft". Default is "binary".

    Returns
    -------
    L: scipy.sparse.spmatrix
        Matting Laplacian matrix
    Né   éÿÿÿÿé   )r   Úsoftz$kernel must be binary/soft, but not Ú.r   é   é   )Zdtype)ÚaxisÚout)Úkr
   )r   )ÚshapeZreshapeÚTÚ
ValueErrorÚnpZtileZlinspaceÚrepeatÚzipÚstackZzerosZfloat32r   ÚappendZarangeZravelZonesÚabsÚsumZconcatenateÚscipyÚsparseZ
csr_matrixr   Úidentity)ÚimageZn_neighborsZdistance_weightsZkernelÚhÚwÚrÚgÚbÚnÚxÚyÚiÚjZcoo_datar   Zdistance_weightÚfÚ_Zneighbor_indicesZW_ijZijZjiÚWÚIÚL© r.   úS/var/www/html/venv/lib/python3.8/site-packages/pymatting/laplacian/knn_laplacian.pyÚknn_laplacian   s:    "ý
4r0   )	Únumpyr   Zscipy.sparser   Zpymatting.util.kdtreer   Zpymatting.util.utilr   r0   r.   r.   r.   r/   Ú<module>   s   ü