
    bi5                       d Z ddlm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 ddlZddlZdd	lmZmZmZmZmZ dd
lmZ ddlmZ ddlmZ ddlmZ g dZedd       Z eedd              Z!e	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z"ddZ#d dZ$eed!d              Z%d"dZ&d#d$dZ'd%d&dZ(	 	 	 	 	 	 	 	 	 	 	 	 d'dZ)d(dZ*d%d)dZ+d%d)dZ,d*dZ-y)+aO  Functional implementations of various blur operations for image processing.

This module provides a collection of low-level functions for applying different blur effects
to images, including standard blur, median blur, glass blur, defocus, and zoom effects.
These functions form the foundation for the corresponding transform classes.
    )annotationsN)Sequence)product)ceil)Literal)warn)clipped
float32_iomaybe_process_in_chunkspreserve_channel_dimuint8_io)ValidationInfo)scale)convolve)EIGHT)box_blurcentral_zoomdefocus
glass_blurmedian_blur	zoom_blurc                L    t        t        j                  ||f      } ||       S )zBlur an image.

    This function applies a blur to an image.

    Args:
        img (np.ndarray): Input image.
        ksize (int): Kernel size.

    Returns:
        np.ndarray: Blurred image.

    ksize)r   cv2blurimgr   blur_fns      g/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/albumentations/augmentations/blur/functional.pyr   r      s"     &chhuenEG3<    c                H    t        t        j                  |      } ||       S )zMedian blur an image.

    This function applies a median blur to an image.

    Args:
        img (np.ndarray): Input image.
        ksize (int): Kernel size.

    Returns:
        np.ndarray: Median blurred image.

    r   )r   r   
medianBlurr   s      r    r   r   /   s     &cnnEBG3<r!   c                   t        j                  t        j                  |       |d      }|dk(  rt        j                  | j
                  d   |z
  |d      }t        j                  | j
                  d   |z
  |d      }t        j                  ||j
                  d         }	t        j                  ||j
                  d         }
t        |      D ];  }|dd|df   }|dd|df   }||	|z   |
|z   f   ||	|
f   c||	|
f<   ||	|z   |
|z   f<   = n|dk(  rt        t        t        |      t        | j
                  d   |z
  |d      t        | j
                  d   |z
  |d                  D ]\  \  }\  }}	}
|t        |      k  r|n|t        |      z  }|||df   }|||df   }||	|z   |
|z   f   ||	|
f   c||	|
f<   ||	|z   |
|z   f<   ^ nt        d	| d
      t        j                  ||d      S )a|  Glass blur an image.

    This function applies a glass blur to an image.

    Args:
        img (np.ndarray): Input image.
        sigma (float): Sigma.
        max_delta (int): Maximum delta.
        iterations (int): Number of iterations.
        dxy (np.ndarray): Dxy.
        mode (Literal["fast", "exact"]): Mode.

    Returns:
        np.ndarray: Glass blurred image.

    )r   r   )sigmaXr   fastr      NexactzUnsupported mode `z$`. Supports only `fast` and `exact`.)r   GaussianBlurnparrayarangeshapetilerepeatrange	enumerater   len
ValueError)r   sigma	max_delta
iterationsdxymodexhswshwidydxindidxs                   r    r   r   B   s   2 	#uFCAv~YYsyy|i/B?YYsyy|i/B? ggb"((1+6 iiBHHQK8z" 	DAQ1WBQ1WB)*1r61r6>):AadG&AadGQq2vq2v~&	D
 
'j!ciilY.	2>ciilY.	2>
 
	DNC!Q s3x#S3s8^CS!QYBS!QYB)*1r61r6>):AadG&AadGQq2vq2v~&
	D -dV3WXYYAe6::r!   c                   t        j                  t        d|       t        d|      dz         }|t        k  rdnd}t        j                  ||      \  }}t        j
                  |dz  |dz  z   |dz  k  t         j                        }|t        j                  |      z  }t        j                  |||f|      }t        | |      S )	zDefocus an image.

    This function defocuses an image.

    Args:
        img (np.ndarray): Input image.
        radius (int): Radius.
        alias_blur (float): Alias blur.

    Returns:
        np.ndarray: Defocused image.

       r(            dtype)r%   )kernel)r+   r-   maxr   meshgridr,   float32sumr   r*   r   )	r   radius
alias_blurlengthr   r:   yaliased_diskrK   s	            r    r   r   z   s     YYAvAv(:;F5AaE;;vv&DAq88QTAqD[VQY6bjjILBFF<((LlUEN:NFC''r!   c                H   | j                   dd \  }}t        ||z        t        ||z        }}||z
  dz  ||z
  dz  }}t        | |||z   |||z   f   |t        j                        } | j                   d   |z
  dz  | j                   d   |z
  dz  }	}| |||z   |	|	|z   f   S )zCentral zoom an image.

    This function zooms an image.

    Args:
        img (np.ndarray): Input image.
        zoom_factor (int): Zoom factor.

    Returns:
        np.ndarray: Zoomed image.

    NrH   r   r(   )r.   r   r   r   INTER_LINEAR)
r   zoom_factorheightwidthh_chw_chh_topw_top
h_trim_top
w_trim_tops
             r    r   r      s     IIbqMMFEf{*+T%+2E-F$DTMa'%$,1)<5E
EEDL(%%$,*>>?cN^N^
_C!iilV39CIIaL5<PUV;V
JzJ//j5>P1PPQQr!   c                    t        j                  | t         j                        }|D ]  }|t        | |      z  } | |z   t	        |      dz   z  S )zZoom blur an image.

    This function zooms and blurs an image.

    Args:
        img (np.ndarray): Input image.
        zoom_factors (np.ndarray | Sequence[int]): Zoom factors.

    Returns:
        np.ndarray: Zoomed and blurred image.

    rI   r(   )r+   
zeros_likerN   r   r3   )r   zoom_factorsoutrW   s       r    r   r      sS     --2::
.C# .|C--. #I#l+a/00r!   c           
         | d   |k  s| d   |k  r>t        || d         t        || d         f}t        | d|  d| d| dt        d       |S | S )	Nr   r(   z: Invalid kernel size range z. Values less than z2 are not allowed. Range automatically adjusted to .rH   
stacklevel)rL   r   UserWarning)result	min_value
field_name
new_results       r    _ensure_min_valuerm      s}    ay9q	I 5)VAY/Yq	1JK
l6vh ?  ){ +//9l!= 	
 Mr!   c                    | d   dk(  s| d   dz  dk(  r| d   n| d   dz   | d   dk(  s| d   dz  dk(  r| d   n| d   dz   f}|| k7  rt        | d|  d| dt        d       |S )Nr   rH   r(   z+: Non-zero kernel sizes must be odd. Range z automatically adjusted to re   rf   )r   rh   )ri   rk   rl   s      r    _ensure_odd_valuesro      s    AY!^vay1}'9q	vay1}AY!^vay1}'9q	vay1}J VlEfXMhishttuv	

 r!   c                ~   t        | t              r6t        |       dk7  rt        d      t	        | d         t	        | d         f}n|t	        |       f}t        |||j                        }t        ||j                        }|d   |d   kD  r1|d   |d   f}t        |j                   d| d| dt        d       |S |S )	z0Process blur limit to ensure valid kernel sizes.rH   z(Sequence must contain exactly 2 elementsr   r(   z: Invalid range z. (min > max). Range automatically adjusted to re   rf   )

isinstancer   r3   r4   intrm   rk   ro   r   rh   )valueinforj   ri   final_results        r    process_blur_limitrv      s     %"u:?GHHeAh-U1X/SZ(vy$//BF8Fay6!9q	6!9-/x7efresstu	

 Mr!   c                :   t        j                  |dd      }t        j                  | | ft         j                        }| dz  }t        j                  |      }t        j
                  |      }t        j                  |      }	| dz  }
|dk  r t        |      }t        |
       }|
d|z
  z  }n3|dkD  r|}|
 d|z
  z  }t        |
      }nt        |
       }t        |
      }t        j                  |||       }|||z  z   }||	|z  z   }|r:|j                  dd      |
z  dz  }|j                  dd      |
z  dz  }||z  }||z  }t        j                  t        j                  |      d| dz
        j                  t              }t        j                  t        j                  |      d| dz
        j                  t              }t        j                  t        j                  ||g      d      }d||d	d	df   |d	d	df   f<   |j!                         sd|||f<   |S )
a  Create a motion blur kernel.

    Args:
        kernel_size (int): Size of the kernel (must be odd)
        angle (float): Angle in degrees (counter-clockwise)
        direction (float): Blur direction (-1.0 to 1.0)
        allow_shifted (bool): Allow kernel to be randomly shifted from center
        random_state (random.Random): Python's random.Random instance

    Returns:
        np.ndarray: Motion blur kernel

    g      g      ?rI   rH   r   r(   r'   )axisN)r+   clipzerosrN   deg2radcossinabsfloatlinspaceuniformroundastyperr   uniquecolumn_stackany)kernel_sizeangle	directionallow_shiftedrandom_staterK   center	angle_radrA   r@   line_lengthbias_factort_startt_endtr:   rS   shift_xshift_ypointss                       r    create_motion_kernelr      s   * 	4-IXX{K0

CFAF 

5!I 
		B			B "K 1} )n%q;/	Q  ,!k/2k" %k" 	GUK0A 	aAaA &&r1-;a?&&r1-;a?	W	W 	Qa077<A
Qa077<A YYr1v.Q7F)*F6!Q$<1%& ::<!"vv~Mr!   c                    t        d||dz  dk(  z         }t        d||dz  dk(  z         }t        ||      }||k(  r|S ||z
  dz  dz   }| j                  d|dz
        }|d|z  z   S )ab  Sample an odd number from the range [low, high] (inclusive).

    Args:
        random_state (random.Random): instance of random.Random
        low (int): lower bound (will be converted to nearest valid odd number)
        high (int): upper bound (will be converted to nearest valid odd number)

    Returns:
        int: Randomly sampled odd number from the range

    Note:
        - Input values will be converted to nearest valid odd numbers:
          * Values less than 3 will become 3
          * Even values will be rounded up to next odd number
        - After normalization, high must be >= low

    rF   rH   r   r(   )rL   randint)r   lowhighnum_odd_valuesrand_idxs        r    sample_odd_from_ranger   I  s    & aa1%
&Cq$$(a-()D tS>D
d{
 SjQ&*N##A~'9:H!h,r!   c                R   |dk(  rt        | dz        dz  dz   n|}|dz  dk(  r|dz   n|}t        j                  |dz   |dz  |      }t        j                  d|| z  dz  z        }||j	                         z  }|ddt        j
                  f   |t        j
                  ddf   z  S )ak  Create a Gaussian kernel following PIL's approach.

    Args:
        sigma (float): Standard deviation for Gaussian kernel.
        ksize (int): Kernel size. If 0, size is computed as int(sigma * 3.5) * 2 + 1
               to match PIL's implementation. Otherwise, must be positive and odd.

    Returns:
        np.ndarray: 2D normalized Gaussian kernel.

    r         @rH   r(         N)rr   r+   r   exprO   newaxisr5   r   sizer:   	kernel_1ds        r    create_gaussian_kernelr   m  s     (-z3us{a!#uD ax1}4!8$D 	daiL$!)T2A tq5yQ../IIMMO+I Q

]#i

A&>>>r!   c                    |dk(  rt        | dz        dz  dz   n|}|dz  dk(  r|dz   n|}t        |      }t        j                  d|| z  dz  z        }||j	                         z  S )an  Create a 1D Gaussian kernel following PIL's approach.

    Args:
        sigma (float): Standard deviation for Gaussian kernel.
        ksize (int): Kernel size. If 0, size is computed as int(sigma * 3.5) * 2 + 1
               to match PIL's implementation. Otherwise, must be positive and odd.

    Returns:
        np.ndarray: 1D normalized Gaussian kernel.

    r   r   rH   r(   r   r   )rr   "create_gaussian_kernel_input_arrayr+   r   rO   r   s        r    create_gaussian_kernel_1dr     sv     (-z3us{a!#uD ax1}4!8$D 	+5A tq5yQ../Iy}}&&r!   c           	         | dk  r3t        j                  t        t        | dz   | dz  dz   d                  S t        j                  | dz   | dz  |       S )a  Creates a 1-D array which will create an array of x-coordinates which will be input for the
    gaussian function (values from -size/2 to size/2 with step size of 1)

    Piecewise function is needed as equivalent python list comprehension is faster than np.linspace
    for values of size < 100

    Args:
        size (int): kernel size

    Returns:
        np.ndarray: x-coordinate array which will be input for gaussian function that will be used for
        separable gaussian blur

    d   rH   r(   )r+   r,   listr1   r   r   s    r    r   r     sS     czxxUTQY<$!)q!DEFF;;|TQY55r!   )r   
np.ndarrayr   rr   returnr   )r   r   r5   r   r6   rr   r7   rr   r8   r   r9   zLiteral['fast', 'exact']r   r   )r   r   rP   rr   rQ   r   r   r   )r   r   rW   rr   r   r   )r   r   rb   znp.ndarray | Sequence[int]r   r   )ri   tuple[int, int]rj   rr   rk   
str | Noner   r   )N)ri   r   rk   r   r   r   )r   )rs   zint | tuple[int, int]rt   r   rj   rr   r   r   )r   rr   r   r   r   r   r   boolr   random.Randomr   r   )r   r   r   rr   r   rr   r   rr   )r5   r   r   rr   r   r   )r   rr   r   r   ).__doc__
__future__r   randomcollections.abcr   	itertoolsr   mathr   typingr   warningsr   r   numpyr+   albucorer	   r
   r   r   r   pydanticr   1albumentations.augmentations.geometric.functionalr   -albumentations.augmentations.pixel.functionalr   $albumentations.core.type_definitionsr   __all__r   r   r   r   r   r   rm   ro   rv   r   r   r   r   r    r!   r    <module>r      sU   #  $     
  a a # C B 6
[  " 	 
 " 4;	4;4; 4; 	4;
 
4; #4; 4; 4;n(4R, 1 	 1*2PPP P 	P
  P Pf! H?:'46r!   