o
    ߥi"                     @   s   d dl Z d dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZmZ e	ddd	Zd
d Zdd Z		dddZ		dddZdS )    N)convolve)gamma)model_file_download)imresize)reorder_imageto_y_channelz3damo/cv_realbasicvsr_video-super-resolution_videolqzniqe_pris_params.npz)model_id	file_pathc                 C   s<  |   } tddd}t|}tt|d t|t|d   }tt| | dk  d }tt| | dk d }|| }tt| d t| d  }||d d  |d  }||d d d  }	t	||	 d }
||
 }|ttd| td|   }|ttd| td|   }|||fS )a+  Estimate AGGD (Asymmetric Generalized Gaussian Distribution) parameters.
    Args:
        block (ndarray): 2D Image block.
    Returns:
        tuple: alpha (float), beta_l (float) and beta_r (float) for the AGGD
            distribution (Estimating the parameters in Equation 7 in the paper).
    g?gn $@gMbP?      r      )
flattennparange
reciprocalsquarer   sqrtmeanabsargmin)blockgamgam_reciprocalr_gamleft_std	right_stdgammahatrhatrhat1rhatnormarray_positionalphabeta_lbeta_r r$   i/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/metrics/video_super_resolution_metric/niqe.pyestimate_aggd_param   s"   
"""
r&   c           	      C   s   g }t | \}}}|||| d g ddgddgddgddgg}tt|D ].}tj| || dd}t | | \}}}|| td| td|   }|||||g q(|S )zCompute features.
    Args:
        block (ndarray): 2D Image block.
    Returns:
        list: Features with length of 18.
    r
   r   r   )r   r   axis)r&   extendrangelenr   rollr   )	r   featr!   r"   r#   shiftsishifted_blockr   r$   r$   r%   compute_feature3   s    r2   `   c              
   C   s  | j dks	J d| j\}}t|| }t|| }	| d|| d|	| f } g }
dD ]t}t| |dd}tttt| |ddt| }| | |d  }g }t	|	D ].}t	|D ]'}||| | |d | | || | |d | | f }|
t| q`qZ|

t| |dkrt| d d	d
d} | d } q.tj|
dd}
tj|
dd}|
t|
jdd  }tj|dd}tj|| d }tt|| |t|| }t|}tt|}|S )a  Calculate NIQE (Natural Image Quality Evaluator) metric.
    ``Paper: Making a "Completely Blind" Image Quality Analyzer``
    This implementation could produce almost the same results as the official
    MATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zip
    Note that we do not include block overlap height and width, since they are
    always 0 in the official implementation.
    For good performance, it is advisable by the official implementation to
    divide the distorted image in to the same size patched as used for the
    construction of multivariate Gaussian model.
    Args:
        img (ndarray): Input image whose quality needs to be computed. The
            image must be a gray or Y (of YCbCr) image with shape (h, w).
            Range [0, 255] with float type.
        mu_pris_param (ndarray): Mean of a pre-defined multivariate Gaussian
            model calculated on the pristine dataset.
        cov_pris_param (ndarray): Covariance of a pre-defined multivariate
            Gaussian model calculated on the pristine dataset.
        gaussian_window (ndarray): A 7x7 Gaussian window used for smoothing the
            image.
        block_size_h (int): Height of the blocks in to which image is divided.
            Default: 96 (the official recommended value).
        block_size_w (int): Width of the blocks in to which image is divided.
            Default: 96 (the official recommended value).
    r
   zCInput image must be a gray or Y (of YCbCr) image with shape (h, w).r   )r   r
   nearest)moder        o@g      ?T)scaleantialiasingr(   F)rowvar)ndimshapemathfloorr   r   r   r   r   r+   appendr2   arrayr   concatenatenanmeanisnananycovlinalgpinvmatmul	transposefloatsqueeze)imgmu_pris_paramcov_pris_paramgaussian_windowblock_size_hblock_size_whwnum_block_hnum_block_w	distparamr7   musigmaimg_nomalizedr.   idx_widx_hr   mu_distparamdistparam_no_nancov_distparaminvcov_paramqualityr$   r$   r%   niqeL   sf   

r`   HWCyc           
      K   s   t t}|d }|d }|d }| t j} |dkr>t| |d} |dkr*t| } n|dkr9t| d tj	d } t 
| } |d	krN| || || f } |  } t| |||}	|	S )
aG  Calculate NIQE (Natural Image Quality Evaluator) metric.
    ``Paper: Making a "Completely Blind" Image Quality Analyzer``
    This implementation could produce almost the same results as the official
    MATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zip
    > MATLAB R2021a result for tests/data/baboon.png: 5.72957338 (5.7296)
    > Our re-implementation result for tests/data/baboon.png: 5.7295763 (5.7296)
    We use the official params estimated from the pristine dataset.
    We use the recommended block size (96, 96) without overlaps.
    Args:
        img (ndarray): Input image whose quality needs to be computed.
            The input image must be in range [0, 255] with float/int type.
            The input_order of image can be 'HW' or 'HWC' or 'CHW'. (BGR order)
            If the input order is 'HWC' or 'CHW', it will be converted to gray
            or Y (of YCbCr) image according to the ``convert_to`` argument.
        crop_border (int): Cropped pixels in each edge of an image. These
            pixels are not involved in the metric calculation.
        input_order (str): Whether the input order is 'HW', 'HWC' or 'CHW'.
            Default: 'HWC'.
        convert_to (str): Whether converted to 'y' (of MATLAB YCbCr) or 'gray'.
            Default: 'y'.
    Returns:
        float: NIQE result.
    rL   rM   rN   HW)input_orderrb   grayr6   r   )r   loaddownloaded_file_pathastypefloat32r   r   cv2cvtColorCOLOR_BGR2GRAYrJ   roundr`   )
rK   crop_borderrd   
convert_tokwargsniqe_pris_paramsrL   rM   rN   niqe_resultr$   r$   r%   calculate_niqe   s"   


rs   )r3   r3   )ra   rb   )r<   rj   numpyr   scipy.ndimager   scipy.specialr   modelscope.hub.file_downloadr   Amodelscope.metrics.video_super_resolution_metric.matlab_functionsr   <modelscope.metrics.video_super_resolution_metric.metric_utilr   r   rg   r&   r2   r`   rs   r$   r$   r$   r%   <module>   s(   
U