
    9i'                         S SK Jr  S SKrS SKrS SKrS SKJr  S SKJ	r	  SSK
Jr  SSKJrJr  \R                  " \	\R                   S9 " S	 S
\5      5       rSS jrSS jrSS jrS rS rS rS rg)    )DictN)Metrics)default_group   )Metric)METRICS
MetricKeys)	group_keymodule_namec                   b   ^  \ rS rSrSrSrSrU 4S jrS\S\4S jr	S	 r
SS
 jrS rS rSrU =r$ )ImageDenoiseMetric   z<The metric computation class for image denoise classes.
    predtargetc                 F   > [         [        U ]  5         / U l        / U l        g N)superr   __init__predslabels)self	__class__s    g/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/metrics/image_denoise_metric.pyr   ImageDenoiseMetric.__init__   s     $02
    outputsinputsc                     U[         R                     nU[         R                     nU R                  R	                  U5        U R
                  R	                  U5        g r   )r   
label_name	pred_namer   appendr   )r   r   r   ground_truthseval_resultss        r   addImageDenoiseMetric.add   sH     2 = =>1;;<

,'=)r   c           	      n   / / p![        U R                  U R                  5       HE  u  p4UR                  [	        US   US   SS95        UR                  [        US   US   SS95        MG     [        R                  [        R                  " U5      [        R                  [        R                  " U5      0$ )Nr   )crop_border)zipr   r   r!   calculate_psnrcalculate_ssimr	   PSNRnpmeanSSIM)r   	psnr_list	ssim_listr   labels        r   evaluateImageDenoiseMetric.evaluate%   s    !29 T[[9MT^E!Hd1g1MN^E!Hd1g1MN : OORWWY/OORWWY/
 	
r   c                     U R                   R                  UR                   5        U R                  R                  UR                  5        g r   )r   extendr   )r   others     r   mergeImageDenoiseMetric.merge/   s.    

%++&5<<(r   c                 2    U R                   U R                  4$ r   )r   r   )r   s    r   __getstate__ImageDenoiseMetric.__getstate__3   s    zz4;;&&r   c                 B    U R                  5         Uu  U l        U l        g r   )r   r   r   )r   states     r   __setstate__ImageDenoiseMetric.__setstate__6   s    "'
DKr   )r   r   )r6   r   )__name__
__module____qualname____firstlineno____doc__r    r   r   r   r$   r2   r7   r:   r>   __static_attributes____classcell__)r   s   @r   r   r      sC    IJ
*4 * *
)'( (r   r   c                     US;  a  [        SU S35      e[        U R                  5      S:X  a  U S   n US:X  a  U R                  SSS5      n U $ )	a  Reorder images to 'HWC' order.
If the input_order is (h, w), return (h, w, 1);
If the input_order is (c, h, w), return (h, w, c);
If the input_order is (h, w, c), return as it is.
Args:
    img (ndarray): Input image.
    input_order (str): Whether the input order is 'HWC' or 'CHW'.
        If the input image shape is (h, w), input_order will not have
        effects. Default: 'HWC'.
Returns:
    ndarray: reordered image.
HWCCHWWrong input_order z,. Supported input_orders are 'HWC' and 'CHW'   ).NrJ   r   r   )
ValueErrorlenshape	transpose)imginput_orders     r   reorder_imagerS   ;   s`     .( -YZ
 	
 399~)nemmAq!$Jr   c                    U R                   UR                   :X  d"   SU R                    SUR                    S35       eUS;  a  [        SU S35      e[        U 5      [        R                  :X  ag  [        U R                   5      S:X  a  U R                  S5      n U R                  5       R                  5       R                  5       R                  S	S
S5      n [        U5      [        R                  :X  ag  [        UR                   5      S:X  a  UR                  S5      nUR                  5       R                  5       R                  5       R                  S	S
S5      n[        XS9n [        XS9nU R                  [        R                  5      n UR                  [        R                  5      nUS:w  a  XU* 2X"* 2S4   n XU* 2X"* 2S4   nS nU" X5      $ )a.  Calculate PSNR (Peak Signal-to-Noise Ratio).
Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
Args:
    img1 (ndarray/tensor): Images with range [0, 255]/[0, 1].
    img2 (ndarray/tensor): Images with range [0, 255]/[0, 1].
    crop_border (int): Cropped pixels in each edge of an image. These
        pixels are not involved in the PSNR calculation.
    input_order (str): Whether the input order is 'HWC' or 'CHW'.
        Default: 'HWC'.
    test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
Returns:
    float: psnr result.
Image shapes are different: , .rH   rK   ,. Supported input_orders are "HWC" and "CHW"   r   r   rL   rR   .c                     [         R                  " X-
  S-  5      nUS:X  a  [        S5      $ U R                  5       S::  a  SOSnS[         R                  " U[         R
                  " U5      -  5      -  $ )NrL   r   infr   g      ?g     o@g      4@)r,   r-   floatmaxlog10sqrt)img1img2mse	max_values       r   _psnrcalculate_psnr.<locals>._psnr{   s\    ggt{Q&'!8<((*/Bt	RXXi"''#,6777r   rO   rM   typetorchTensorrN   squeezedetachcpunumpyrP   rS   astyper,   float64)ra   rb   r'   rR   re   s        r   r)   r)   T   s    ::# D
&tzzl"TZZLBD#.(  .  	 DzU\\!tzz?a<<?D{{}  "((*44Q1=DzU\\!tzz?a<<?D{{}  "((*44Q1=7D7D;;rzz"D;;rzz"Da,k,.FKL,k,.FKL8 r   c                   ^ U R                   UR                   :X  d"   SU R                    SUR                    S35       eUS;  a  [        SU S35      e[        U 5      [        R                  :X  ag  [        U R                   5      S:X  a  U R                  S5      n U R                  5       R                  5       R                  5       R                  S	S
S5      n [        U5      [        R                  :X  ag  [        UR                   5      S:X  a  UR                  S5      nUR                  5       R                  5       R                  5       R                  S	S
S5      n[        XS9n [        XS9nU R                  [        R                  5      n UR                  [        R                  5      nUS:w  a  XU* 2X"* 2S4   n XU* 2X"* 2S4   nU4S jnU" X5      $ )a  Calculate SSIM (structural similarity).
Ref:
Image quality assessment: From error visibility to structural similarity
The results are the same as that of the official released MATLAB code in
https://ece.uwaterloo.ca/~z70wang/research/ssim/.
For three-channel images, SSIM is calculated for each channel and then
averaged.
Args:
    img1 (ndarray): Images with range [0, 255].
    img2 (ndarray): Images with range [0, 255].
    crop_border (int): Cropped pixels in each edge of an image. These
        pixels are not involved in the SSIM calculation.
    input_order (str): Whether the input order is 'HWC' or 'CHW'.
        Default: 'HWC'.
    test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
Returns:
    float: ssim result.
rU   rV   rW   rH   rK   rX   rY   r   r   rL   rZ   .c                 >  > / nU R                  5       S::  a  SOSn[        R                  " 5          T(       a  [        XU5      O[	        XU5      nUR                  U5        S S S 5        [        R                  " U5      R                  5       $ ! , (       d  f       N2= f)Nr      )	r^   ri   no_grad_ssim_3d_ssimr!   r,   arrayr-   )ra   rb   ssimsrd   
final_ssimssim3ds        r   	_cal_ssim!calculate_ssim.<locals>._cal_ssim   sq    qAc	]]_<B$i8II'JLL$ 
 xx##%% _s   1B
Brg   )ra   rb   r'   rR   rz   r{   s       ` r   r*   r*      s   ( ::# D
&tzzl"TZZLBD#.(  .  	 DzU\\!tzz?a<<?D{{}  "((*44Q1=DzU\\!tzz?a<<?D{{}  "((*44Q1=7D7D;;rzz"D;;rzz"Da,k,.FKL,k,.FKL	& T  r   c                    SU-  S-  nSU-  S-  nU R                  [        R                  5      n UR                  [        R                  5      n[        R                  " SS5      n[        R
                  " XUR                  5       5      n[        R                  " U SU5      SS2SS24   n[        R                  " USU5      SS2SS24   nUS-  n	US-  n
Xx-  n[        R                  " U S-  SU5      SS2SS24   U	-
  n[        R                  " US-  SU5      SS2SS24   U
-
  n[        R                  " X-  SU5      SS2SS24   U-
  nSU-  U-   SU-  U-   -  nX-   U-   X-   U-   -  nUU-  nUR                  5       $ )	a  Calculate SSIM (structural similarity) for one channel images.
It is called by func:`calculate_ssim`.
Args:
    img (ndarray): Images with range [0, 255] with order 'HWC'.
    img2 (ndarray): Images with range [0, 255] with order 'HWC'.
Returns:
    float: SSIM result.
{Gz?rL   Q?         ?   )	ro   r,   rp   cv2getGaussianKernelouterrP   filter2Dr-   )rQ   rb   rd   c1c2kernelwindowmu1mu2mu1_sqmu2_sqmu1_mu2	sigma1_sq	sigma2_sqsigma12tmp1tmp2ssim_maps                     r   rv   rv      s    
Q	B

Q	B
**RZZ
 C;;rzz"D""2s+FXXf..01F
,,sB
'"()")- .C
,,tR
(2qt
4C!VF!VFiGS!VR02qt<vEIT1Wb&1!B$"*=FIll3:r621R42:>HGK"Wr!12DOb Y%:R%?@Dd{H==?r   c                     U" U R                  S5      R                  S5      5      R                  S5      R                  S5      nU$ )Nr   )	unsqueezerk   )rQ   conv3douts      r   _3d_gaussian_calculatorr      s;    
q!++A.
/
7
7
:
B
B1
ECJr   c            
         [         R                  " SS5      n [        R                  " X R	                  5       5      n[         R                  " SS5      n[
        R                  " [        R                  " U Vs/ s H  o1U-  PM	     snSS95      n [
        R                  R                  SSSSSSS	S
9nSUR                  l        XR                  SSS S 2S S 2S S 24'   U$ s  snf )Nr   r   r   )axisr   )r   r   r   )r   r   r   F	replicate)stridepaddingbiaspadding_mode)r   r   r,   r   rP   ri   tensorstacknnConv3dweightrequires_grad)r   r   kernel_3kr   s        r   _generate_3d_gaussian_kernelr      s    ""2s+FXXf..01F$$R-H\\"((#A1QJ#AJKFXX__		<   "F #(FMM#)MM!Q1a- M $Bs   7Cc                 ,   [        U R                  5      S:X  a  [        UR                  5      S:X  d   e SU-  S-  nSU-  S-  nU R                  [        R                  5      n UR                  [        R                  5      n[        5       R                  5       n[        R                  " U 5      R                  5       R                  5       n [        R                  " U5      R                  5       R                  5       n[        X5      n[        X5      nUS-  nUS-  n	Xg-  n
[        U S-  U5      U-
  n[        US-  U5      U	-
  n[        X-  U5      U
-
  nSU
-  U-   SU-  U-   -  nX-   U-   X-   U-   -  nX-  n[        UR                  5       5      $ )N   r~   rL   r   )rN   rO   ro   r,   rp   r   cudari   r   r]   r   r-   )ra   rb   rd   C1C2r   r   r   r   r   r   r   r   r   r   r   r   s                    r   ru   ru      sx   tzz?aC

Oq$888 
Q	B

Q	B;;rzz"D;;rzz"D)+002F<<##%**,D<<##%**,D
!$
/C
!$
/C!VF!VFiG'a86AI'a86AI%dk6:WDGK"Wr!12DOb Y%:R%?@D{H!!r   )rI   )rI   T)typingr   r   rn   r,   ri   modelscope.metainfor   modelscope.utils.registryr   baser   builderr   r	   register_moduleimage_denoise_metricr   rS   r)   r*   rv   r   r   ru    r   r   <module>r      sy     
   ' 3  ( 	)E)EG$( $(G$(N2/d9!xD
"!"r   