o
    :ήc                     @   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vr#td| d ttdd	||}
ttdd	||}g g g }}}t||D ]c\}}tj	|||||
 || gd	tj
|	d
ftjdd}t|||d\}}|tt|	| ||  t||	 }|dkr|t||d  ||d   jd	d|j d	  8 }|| qFt|| }t|| }t|| }tj|||ff|	|	f}t|}tj|	}|| }|S )a*  
    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         )dtype)axisout)kr
   )r   )shapereshapeT
ValueErrornptilelinspacerepeatzipstackzerosfloat32r   appendarangeravelonesabssumconcatenatescipysparse
csr_matrixr   identity)imagen_neighborsdistance_weightskernelhwrgbnxyijcoo_datar   distance_weightf_neighbor_indicesW_ijijjiWIL rB   H/tmp/pip-target-vg8gfxp4/lib/python/pymatting/laplacian/knn_laplacian.pyknn_laplacian   s:   4rD   )	numpyr   scipy.sparser%   pymatting.util.kdtreer   pymatting.util.utilr   rD   rB   rB   rB   rC   <module>   s    