o
    oi                     @   sJ   d dl Z de jde jde jfddZde jde jd	e jde jfd
dZdS )    Nsourcetemplatereturnc                 C   s   | j }|  } | }tj| ddd\}}}tj|dd\}}tj|d| jd}||d  }tj|d| jd}	|	|	d  }	t||	|}
|
| |S )a  Adjust the pixel values of an image to match its histogram towards a target image.

    `Histogram matching <https://en.wikipedia.org/wiki/Histogram_matching>`_ is the transformation
    of an image so that its histogram matches a specified histogram. In this implementation, the
    histogram is computed over the flattened image array. Code referred to
    `here <https://stackoverflow.com/questions/32655686/histogram-matching-of-two-images-in-python-2-x>`_.

    Args:
        source: Image to transform.
        template: Template image. It can have different dimensions to source.

    Returns:
        The transformed output image as the same shape as the source image.

    Note:
        This function does not matches histograms element-wisely if input a batched tensor.

    T)return_inversereturn_counts)r   r   )dimdtype)shaperaveltorchuniquecumsumr   interpreshape)r   r   oldshape_bin_idxs_countst_valuest_countss_quantilest_quantilesinterp_t_values r   U/home/ubuntu/.local/lib/python3.10/site-packages/kornia/contrib/histogram_matching.pyhistogram_matching   s   r   xxpfpc                 C   sf   t t j|| dddt|d }||d  || |   || | ||d     || ||d    S )a  One-dimensional linear interpolation for monotonically increasing sample points.

    Returns the one-dimensional piecewise linear interpolant to a function with
    given discrete data points :math:`(xp, fp)`, evaluated at :math:`x`.

    This is confirmed to be a correct implementation.
    See https://github.com/pytorch/pytorch/issues/1552#issuecomment-979998307

    Args:
        x: the :math:`x`-coordinates at which to evaluate the interpolated
            values.
        xp: the :math:`x`-coordinates of the data points, must be increasing.
        fp: the :math:`y`-coordinates of the data points, same length as `xp`.

    Returns:
        the interpolated values, same size as `x`.

    T)right   )r   clipsearchsortedlen)r   r   r   ir   r   r   r   @   s   "Dr   )r   Tensorr   r   r   r   r   r   <module>   s   &+