a
    aDf                     @   s	  d dl mZ d dlmZmZmZmZmZmZm	Z	 d dl
mZ 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mZmZmZmZmZmZmZmZ d dlmZm Z m!Z!m"Z" g d	Z#d
Z$dZ%dZ&d
Z'dZ(dZ)dZ*ej+ej+ej+ej+dddZ,ej+ej+ej+ej+dddZ-edej+eee.ej+dddZ/eej+ed ej+dddZ0ej+ej+ej+ej+ej+dddZ1ej+ej+ej+ej+ej+ddd Z2eej+ej+ej+ej+ej+dd!d"Z3dej+e4ej+d$d%d&Z5eej+e4ej+d'd(d)Z6dej+eej+ ej+d*d+d,Z7dej+eej+ ej+d*d-d.Z8ej+eej+ e9dd/d0d1Z:deej+ ej+e9ee4 eej+ d2d3d4Z;edej+eej+ e e9ej+d7d8d9Z<eej+e.e.ej+d:d;d<Z=eej+e.e.e.ej+d=d>d?Z>ej+ej+ej+d@dAdBZ?eej+e!e!e!ej+d=dCdDZ@ej+e!e!e!ej+d=dEdFZAeej+ej+ej+dGdHdIZBedej+e.ee4e4f ej+dLdMdNZCeej+ej+ej+dOdPdQZDeej+e4edR ej+dSdTdUZEeej+e.e.ej+dVdWdXZFeej+e4e4e4ee4e4e4f e4e.eee4e4f  ej+dY	dZd[ZGeej+e.e.eee4e4f  ej+d\d]d^ZHeej+e.e.e4eee ej+d_d`daZIeeej+eej+ ej+dbdcddZJeeej+ee ej+dedfdgZKej+ej+dhdidjZLej+ej+ej+dkdldmZMeej+e.ej+dndodpZNeej+ej+ej+dqdrdsZOedej+e.e.e9ej+dvdwdxZPedej+e.e.e9ej+dvdydzZQdej+e.e.e9ej+dvd{d|ZRedej+e.e.ee4 eej+dddZSej+ej+dhddZTej+ej+dhddZUeejVejWfej+e.e4e4ej+dddZXdej+ee. ej+dddZYdej+ejZee. ej+dddZ[eeedddZ\dej+ej+eee4  ej+dddZ]eej+ej+ej+dddZ^eej+ej+ej+dddZ_eej+ej+ej+dddZ`ej+ej+ej+dddZaej+ee4e4e4e4f dddZbej+ee4e4e4e4f ej+dddZcdej+e.ej+dddZdej+e.ej+dddZeeej+ej+edddZfej+e.ej+ej+dddZgeej+e.ej+dddZhedej+e.e.ej+dddZiej+e.ej+dddZjej+e.ej+dddZkeej+e4ee9 ee4 e4ej+dddZleeej+e.ej+e.ej+dddZmeedej+e4e.e.e4ej+dddĄZneej+ej+e	e.ee. f ej+dŜddǄZoeeej+eej+ eej+ eej+ e"ej+dȜddʄZpe4e4ej+d˜dd̈́Zqde4e4eejrjs ej+dΜddЄZtdee4e4f ee4e4f eejrjs ej+dќddӄZuej+eee4e4f ee4 f dԜddքZvdeee4e4f ee4 f eejrjs ee4 dלddلZwej+e.e.e.e.e4ej+dڜdd܄Zxej+ej+ej+e4e4e4ej+dݜdd߄Zyeej+ej+ej+dOddZzeej+ej+ej+dOddZ{ej+ej+e|ej+dddZ}dS )    )defaultdict)AnyDictListOptionalSequenceTupleUnion)warnN)Literal)random_utils)	MAX_VALUES_BY_DTYPE_maybe_process_in_chunksclipclippedensure_contiguousis_grayscale_imageis_rgb_imagenon_rgb_warningpreserve_channel_dim)	ColorType	ImageMode
ScalarTypeSpatterMode),add_fogadd_rain
add_shadow
add_graveladd_snowadd_sun_flareadd_weightedadjust_brightness_torchvisionadjust_contrast_torchvisionadjust_hue_torchvisionadjust_saturation_torchvisionbrightness_contrast_adjustchannel_shuffleclaheconvolve	downscaleequalize	fancy_pca
from_floatgamma_transformgauss_noiseimage_compressioninvert	iso_noiselinear_transformation_rgbmove_tone_curvemultiplynoop	normalize	posterize	shift_hsv	shift_rgbsolarizesuperpixelsswap_tiles_on_imageto_floatto_graygray_to_rgbunsharp_maskr   split_uniform_gridchromatic_aberrationerodedilate            h  )imgmeandenominatorreturnc                 C   s   |j rDt|tkrD|j | j krDtj| dgdt|   tjd}|j sftj| gd tjd}n>t|tkr|j | j krtj| dgdt|   tjd}t| d} t	
| |tj|  t	| |tj|  | S )Nr   rG   dtype   float32)shapelenFOURnparraytolistfloat64Zascontiguousarrayastypecv2subtractr4   rJ   rK   rL    r]   t/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/albumentations/augmentations/functional.pynormalize_cv2U   s    &&r_   c                 C   s    |  tj} | |8 } | |9 } | S N)rY   rU   rQ   r\   r]   r]   r^   normalize_numpyc   s    ra        o@)rJ   rK   stdmax_pixel_valuerM   c                 C   s`   t j|t jd}||9 }t j|t jd}||9 }t j|t jd}t| rTt| ||S t| ||S )NrN   )rU   rV   rQ   Z
reciprocalr   r_   ra   )rJ   rK   rc   rd   Zmean_npZstd_nprL   r]   r]   r^   r6   j   s    r6   )imageimage_per_channelmin_maxmin_max_per_channel)rJ   normalizationrM   c           	      C   s(  |  tj} | jtkr$tj| dd} |dkrZ|  }|  d }| | | }|dd}n|dkr| jdd}| jddd }| |d	d	d	d	f  |d	d	d	d	f  }|dd}np|d
kr| 	 }| 
 }| | ||  }nF|dkr| j	ddd}| j
ddd}| | ||  }ntd| |S )a  Apply per-image normalization based on the specified strategy.

    Args:
        img (np.ndarray): The image to be normalized, expected to be in HWC format.
        normalization (str): The normalization strategy to apply. Options include:
                             "image", "image_per_channel", "min_max", "min_max_per_channel".

    Returns:
        np.ndarray: The normalized image.

    Reference:
        https://github.com/ChristofHenkel/kaggle-landmark-2021-1st-place/blob/main/data/ch_ds_1.py
    axisre   g-C6?i   rf   )r   rP   Nrg   rh   T)rl   ZkeepdimszUnknown normalization method: )rY   rU   rQ   ndimGRAYSCALE_SHAPE_LENGTHexpand_dimsrK   rc   r   minmax
ValueError)	rJ   ri   rK   rc   Znormalized_imgZ
pixel_meanZ	pixel_stdZimg_minZimg_maxr]   r]   r^   normalize_per_imagez   s.    
(
rt   )rJ   	hue_shift	sat_shift	val_shiftrM   c                 C   s   | j }t| tj} t| \}}}|dkr`tjddtjd}t|| d	|}t
||}|dkrtjddtjd}	t|	| dd	|}	t
||	}|dkrtjddtjd}
t|
| dd	|}
t
||
}t|||f	|} t| tjS )Nr      rN         )rO   rZ   cvtColorCOLOR_RGB2HSVsplitrU   arangeint16modrY   LUTr   mergeCOLOR_HSV2RGB)rJ   ru   rv   rw   rO   huesatvalZlut_hueZlut_satZlut_valr]   r]   r^   _shift_hsv_uint8   s"    r   c                 C   s   | j }t| tj} t| \}}}|dkrDt||}t|d}|dkr`tt|||d}|dkr|tt|||d}t	|||f} t| tj
S )Nr   rI         ?)rO   rZ   r{   r|   r}   addrU   r   r   r   r   )rJ   ru   rv   rw   rO   r   r   r   r]   r]   r^   _shift_hsv_non_uint8   s    r   c                 C   s   |dkr|dkr|dkr| S t | }|rV|dks8|dkrHd}d}td t| tj} | jtjkrrt| |||} nt	| |||} |rt| tj
S | S )Nr   zqHueSaturationValue: hue_shift and sat_shift are not applicable to grayscale image. Set them to 0 or use RGB image)r   r
   rZ   r{   COLOR_GRAY2RGBrO   rU   uint8r   r   COLOR_RGB2GRAY)rJ   ru   rv   rw   Zis_grayr]   r]   r^   r8      s"    r8      )rJ   	thresholdrM   c                    s   | j }t|  |t dkrz fddtt d D }| j}t| tj||d} t	|t	| jkrvt
| d} | S |  }| k} ||  ||< |S )zInvert all pixel values above a threshold.

    Args:
        img: The image to solarize.
        threshold: All pixels above this grayscale level are inverted.

    Returns:
        Solarized image.

    r   c                    s    g | ]}|k r|n | qS r]   r]   .0iZmax_valr   r]   r^   
<listcomp>      zsolarize.<locals>.<listcomp>rP   rN   rj   )rO   r   rU   rangeintrR   rZ   r   rV   rS   rp   copy)rJ   r   rO   lutZ
prev_shape
result_imgZcondr]   r   r^   r:     s     r:   )rJ   bitsrM   c           	      C   s  t |}| jt jkr"d}t|t |dk |tkB rDd}t||jrVt|dkr|dkrht 	| S |tkrx| 
 S t jddt jd}t dd|  d  }||M }t| |S t| sd	}t|t | }t|D ]\}}|dkr
t 	| d
|f |d
|f< q|tkr.| d
|f 
 |d
|f< qt jddt jd}t dd|  d  }||M }t| d
|f ||d
|f< q|S )zReduce the number of bits for each color channel.

    Args:
        img: image to posterize.
        bits: number of high bits. Must be in range [0, 8]

    Returns:
        Image with reduced color channels.

    "Image must have uint8 channel typer   zbits must be in range [0, 8]rP   rx   rN   rE   rH   z%If bits is iterable image must be RGB.)rU   r   rO   	TypeErroranyEIGHTrs   rR   rS   
zeros_liker   r~   rZ   r   r   
empty_like	enumerate)	rJ   r   Z
bits_arraymsgr   maskr   r   Zchannel_bitsr]   r]   r^   r7     s<    




r7   )rJ   r   rM   c                 C   s   t | gdg|dgd }dd |D }t|dkr>|  S t|d d d }|s`|  S tjdtjd	}|d
 }t	dD ]"}t
|| d||< ||| 7 }qt | t|S )Nr   rx   r   rx   c                 S   s   g | ]}|r|qS r]   r]   )r   _fr]   r]   r^   r   V  r   z!_equalize_pil.<locals>.<listcomp>rP   rj   rz   rN   rE   )rZ   calcHistravelrS   r   rU   sumemptyr   r   rq   r   rV   )rJ   r   	histogramhstepr   nr   r]   r]   r^   _equalize_pilT  s    r   c           
      C   s   |d u rt | S t | gdg|dgd }d}|D ]}|dkrF qP|d7 }q6t|d}t|}|| |kr|t| |S d|||   }d}tjdtj	d}t
|d t|D ].}	|||	 7 }tt|| tdd||	< qt | |S )	Nr   rx   r   rP   rz   rb   rN   r   )rZ   ZequalizeHistr   r   rq   rU   r   	full_likezerosr   r   rS   r   roundrO   r   )
rJ   r   r   r   r   totalscaleZ_sumr   idxr]   r]   r^   _equalize_cvh  s&    



 r   )rJ   r   by_channelsrM   c                 C   sl   | j tjkrd}t||d urht|rHt| rHtd| j d|j |sht|shd|j }t|d S )Nr   zWrong mask shape. Image shape: z. Mask shape: zAWhen by_channels=False only 1-channel mask supports. Mask shape: )rO   rU   r   r   r   r   rs   rR   )rJ   r   r   r   r]   r]   r^   _check_preconditions  s    r   )r   rJ   r   r   rM   c                 C   s8   | d u rd S |  tj} t| s(|d u r,| S | d|f S N.)rY   rU   r   r   )r   rJ   r   r   r]   r]   r^   _handle_mask  s    r   cvT)rJ   r   moder   rM   c                 C   s   t | || |dkrtnt}t| r6|| t|| |S |spt| tj}||d t|| ||d< t|tjS t	
| }tdD ],}t|| ||}|| d|f ||d|f< q|S )NZpil.r   rF   .)r   r   r   r   r   rZ   r{   ZCOLOR_RGB2YCrCbZCOLOR_YCrCb2RGBrU   r   r   )rJ   r   r   r   functionr   r   Z_maskr]   r]   r^   r*     s    
r*   )rJ   low_yhigh_yrM   c           	         s   | j }d  krdks(n d}t|d   kr<dksJn d}t||tjkrbtd| tddd}tjtjd	 fd
d}t|}t||d tj}t	t
j|d}|| S )a  Rescales the relationship between bright and dark areas of the image by manipulating its tone curve.

    Args:
        img: RGB or grayscale image.
        low_y: y-position of a Bezier control point used
            to adjust the tone curve, must be in range [0, 1]
        high_y: y-position of a Bezier control point used
            to adjust image tone curve, must be in range [0, 1]

    r   rP   z!low_shift must be in range [0, 1]z"high_shift must be in range [0, 1]zUnsupported image type         r   rx   )trM   c                    s8   dd|  d  |   dd|   | d     | d  S )NrF   rP   rE   r]   )r   r   r   r]   r^   evaluate_bez  s    z%move_tone_curve.<locals>.evaluate_bezrz   r   )rO   rs   rU   r   linspacendarrayZ	vectorizeZrintrY   r   rZ   r   )	rJ   r   r   input_dtyper   r   r   Z	remappingZlut_fnr]   r   r^   r3     s    

r3   )rJ   r_shiftg_shiftb_shiftrM   c                 C   sb   ||  kr|kr n n| | S t | }|||g}t|D ] \}}| d|f | |d|f< q<|S r   )rU   r   r   )rJ   r   r   r   r   shiftsr   shiftr]   r]   r^   _shift_rgb_non_uint8  s    

r   )rJ   valuerM   c                 C   sJ   t | j }td|d d}||7 }t|d|| j}t| |S )Nr   rP   rQ   )r   rO   rU   r~   rY   r   rZ   r   )rJ   r   	max_valuer   r]   r]   r^   _shift_image_uint8  s
    
r   c                 C   s   ||  kr|kr@n n(| j \}}}| ||| g} t| |S t| }|||g}t|D ]"\}	}
t| d|	f |
|d|	f< q\|S r   )rR   reshaper   rU   r   r   )rJ   r   r   r   heightwidthchannelsr   r   r   r   r]   r]   r^   _shift_rgb_uint8  s    


r   c                 C   s(   | j tjkrt| |||S t| |||S r`   )rO   rU   r   r   r   )rJ   r   r   r   r]   r]   r^   r9     s    r9   )rJ   transformation_matrixrM   c                 C   s   t | |S r`   )rZ   Z	transform)rJ   r   r]   r]   r^   r2     s    r2          @rH   rH   )rJ   
clip_limittile_grid_sizerM   c                 C   s   | j tjkrd}t|tj|dd |D d}t| rB|| S t| tj	} || d d d d df | d d d d df< t| tj
S )Nz clahe supports only uint8 inputsc                 S   s   g | ]}t |qS r]   )r   )r   xr]   r]   r^   r     r   zclahe.<locals>.<listcomp>)Z	clipLimitZtileGridSizer   )rO   rU   r   r   rZ   ZcreateCLAHEr   applyr{   ZCOLOR_RGB2LABZCOLOR_LAB2RGB)rJ   r   r   r   Z	clahe_matr]   r]   r^   r'     s    
.r'   )rJ   kernelrM   c                 C   s   t tjd|d}|| S )Nrj   )Zddepthr   )r   rZ   Zfilter2D)rJ   r   Zconv_fnr]   r]   r^   r(   #  s    r(   ).jpg.webp)rJ   quality
image_typerM   c                 C   s   |dkrt j}n|dkr t j}ntd | j}d}|tjkrftd| dt t	| tdd} d	}n |tj
tjfvrtd
| dt || t||f\}}t |t j} |rt| dd} | S )Nr   r   z@Only '.jpg' and '.webp' compression transforms are implemented. FzDImage compression augmentation is most effective with uint8 inputs, z is used as input.r   rN   TUnexpected dtype z for image augmentationrz   r   )rZ   ZIMWRITE_JPEG_QUALITYZIMWRITE_WEBP_QUALITYNotImplementedErrorrO   rU   rQ   r
   UserWarningr,   r   rs   Zimencoder   ZimdecodeZIMREAD_UNCHANGEDr=   )rJ   r   r   Zquality_flagr   needs_float_Zencoded_imgr]   r]   r^   r/   )  s.    
r/   )rJ   
snow_pointbrightness_coeffrM   c                 C   s   t |  | j}d}|d9 }|d7 }|tjkrDt| tdd} d}n |tjtjfvrdtd| dt| tj	}tj
|tjd}|d	d	d	d	d
f |d	d	d	d	d
f |k   |9  < t|d	d	d	d	d
f tjd|d	d	d	d	d
f< tj
|tjd}t|tj}|rt|dd}|S )a  Bleaches out pixels, imitation snow.

    From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library

    Args:
        img: Image.
        snow_point: Number of show points.
        brightness_coeff: Brightness coefficient.

    Returns:
        Image.

    Fg     _@U   r   rN   Tr   z for RandomSnow augmentationNrP   rz   r   )r   rO   rU   rQ   r,   r   rs   rZ   r{   COLOR_RGB2HLSrV   r   COLOR_HLS2RGBr=   )rJ   r   r   r   r   	image_hls	image_rgbr]   r]   r^   r   I  s&    
82r   )	rJ   slantdrop_length
drop_width
drop_color
blur_valuebrightness_coefficient
rain_dropsrM   c                 C   s  t |  | j}d}	|tjkr4t| tdd} d}	n |tjtjfvrTtd| d|  }
|D ]2\}}|| }|| }t	|
||f||f|| q`t
|
||f}
t|
tjtj}|dddddf  |9  < t|tjtj}|	rt|d	d
S |S )aR  From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library

    Args:
        img: Image.
        slant:
        drop_length:
        drop_width:
        drop_color:
        blur_value: Rainy view are blurry.
        brightness_coefficient: Rainy days are usually shady.
        rain_drops:

    Returns:
        Image

    Fr   rN   Tr   z for RandomRain augmentationNrE   rz   r   )r   rO   rU   rQ   r,   r   rs   r   rZ   lineblurr{   r|   rY   r   r=   )rJ   r   r   r   r   r   r   r   r   r   re   Zrain_drop_x0Zrain_drop_y0Zrain_drop_x1Zrain_drop_y1Z	image_hsvr   r]   r]   r^   r   w  s4    
r   )rJ   fog_coef
alpha_coef	haze_listrM   c              	   C   s"  t |  | j}d}|tjkr4t| tdd} d}n |tjtjfvrTtd| d| jd }tt	|d | d	}|D ]z}|\}	}
| 
 }| 
 }|| }|d
 }|	|d
  |
|d
  f}t||t	|dd t|||d| d| |
 } qxt| |d	 |d	 f}|rt|dd}|S )a  Add fog to the image.

    From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library

    Args:
        img: Image.
        fog_coef: Fog coefficient.
        alpha_coef: Alpha coefficient.
        haze_list:

    Returns:
        Image.

    Fr   rN   Tr   z for RandomFog augmentationrP   rF   
   rE   )rz   rz   rz   rj   r   rz   r   )r   rO   rU   rQ   r,   r   rs   rR   rr   r   r   rZ   circleaddWeightedr   r=   )rJ   r   r   r   r   r   r   ZhwZhaze_pointsr   yoverlayoutputalpharadpointr   r]   r]   r^   r     s0    


r   )rJ   flare_center_xflare_center_y
src_radius	src_colorcirclesrM   c              	   C   s~  t |  | j}d}|tjkr4t| tdd} d}n |tjtjfvrTtd| d|  }|  }	|D ]J\}
\}}}\}}}t	|||f||||fd t
||
|	d|
 d	|	 qht|t|f}|	 }|d
 }tjdd|d}
tjd||d}t|D ]f}t	||t|| |d |
|| d  |
|| d   |
|| d   }t
|||	d| d	|	 q|	}|rzt|dd}|S )a>  Add sun flare.

    From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library

    Args:
        img (numpy.ndarray):
        flare_center_x (float):
        flare_center_y (float):
        src_radius:
        src_color (int, int, int):
        circles (list):

    Returns:
        numpy.ndarray:

    Fr   rN   Tr   z for RandomSunFlareaugmentationrj   rP   r   r   r   )numrz   r   )r   rO   rU   rQ   r,   r   rs   r   rZ   r   r   r   r   r   r=   )rJ   r  r  r  r  r	  r   r   r   r  r  r   r   Zrad3Zr_colorZg_colorZb_colorr  Z	num_timesr  r   Zalpr   r]   r]   r^   r     s4    
0r   )rJ   vertices_listrM   c                 C   s   t |  | j}d}|tjkr4t| tdd} d}n |tjtjfvrTtd| dt| tj	}t
| }t||d |ddddd	f ttd k}|ddddd
f | d |ddddd
f |< t|tj}|rt|ddS |S )zAdd shadows to the image.

    Args:
        img (numpy.ndarray):
        vertices_list (list[numpy.ndarray]):

    Returns:
        numpy.ndarray:

    Reference:
        https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
    Fr   rN   Tr   z for RandomShadow augmentationrz   Nr   rP         ?r   )r   rO   rU   rQ   r,   r   rs   rZ   r{   r   r   ZfillPolyr   r   r=   )rJ   r  r   r   r   r   Zred_max_value_indr   r]   r]   r^   r   )  s"    

$4r   )rJ   gravelsrM   c                 C   s   t |  | j}d}|tjkr4t| tdd} d}n |tjtjfvrTtd| dt| tj	}|D ](}|\}}}}	}
|
|||	||df< qft|tj
}|rt|dd	}|S )
af  Add gravel to the image.

    From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library

    Args:
        img (numpy.ndarray): image to add gravel to
        gravels (list): list of gravel parameters. (float, float, float, float):
            (top-left x, top-left y, bottom-right x, bottom right y)

    Returns:
        numpy.ndarray:

    Fr   rN   Tr   z for AddGravel augmentationrP   rz   r   )r   rO   rU   rQ   r,   r   rs   rZ   r{   r   r   r=   )rJ   r  r   r   r   Zgravely1y2x1Zx2r   r   r]   r]   r^   r   T  s     
r   )rJ   rM   c                 C   s   t | j |  S r`   )r   rO   rJ   r]   r]   r^   r0   |  s    r0   )rJ   channels_shuffledrM   c                 C   s   | d|f S r   r]   )rJ   r  r]   r]   r^   r&     s    r&   )rJ   gammarM   c                 C   sB   | j tjkr6tddd| d }t| |tjS t| |S )Nr   g?p?rz   )rO   rU   r   r~   rZ   r   rY   power)rJ   r  tabler]   r]   r^   r-     s    r-   )re   gaussrM   c                 C   s   |  d} | | S )NrQ   )rY   )re   r  r]   r]   r^   r.     s    
r.   rP   F)rJ   r  betabeta_by_maxrM   c                 C   sX   | j }| d} |dkr | |9 } |dkrT|rBt| }| || 7 } n| |t|  7 } | S )NrQ   rP   r   )rO   rY   r   rU   rK   )rJ   r  r  r  rO   r   r]   r]   r^   $_brightness_contrast_adjust_non_uint  s    
r  c                 C   s   t d}t| }t d|d d}|dkr8||9 }|dkrh|rR||| 7 }n||| t |  7 }t |d||}t| |S )Nr   r   rP   rQ   )	rU   rO   r   r~   rY   rK   r   rZ   r   )rJ   r  r  r  rO   r   r   r]   r]   r^    _brightness_contrast_adjust_uint  s    
r  c                 C   s(   | j tjkrt| |||S t| |||S r`   )rO   rU   r   r  r  )rJ   r  r  r  r]   r]   r^   r%     s    r%   皙?r  )re   color_shift	intensityrandom_statekwargsrM   c                 K   s   | j tjkrd}t|t| s,d}t|td}tj| |tjd} t	| tj
}t|\}}	tj|	d | d |jdd |d	}
tjd
|d | |jdd |d	}|d }||7 }|d; }|d }||
d d|  7 }t	|tjd } | tjS )a  Apply poisson noise to image to simulate camera sensor noise.

    Args:
        image (numpy.ndarray): Input image, currently, only RGB, uint8 images are supported.
        color_shift (float):
        intensity (float): Multiplication factor for noise values. Values of ~0.5 are produce noticeable,
                   yet acceptable level of noise.
        random_state:
        **kwargs:

    Returns:
        numpy.ndarray: Noised image

    r   zImage must be RGBr  rN   rP   rz   NrE   )sizer  r   rI   r   .rP   r   )rO   rU   r   r   r   floatr4   rQ   rZ   r{   r   Z
meanStdDevr   ZpoissonrR   normalr   rY   )re   r  r  r  r   r   Zone_over_255Zhlsr   ZstddevZluminance_noiseZcolor_noiser   Z	luminancer]   r]   r^   r1     s&    &$r1   c                 C   s   t | t j}t |t jS r`   )rZ   r{   r   r   )rJ   grayr]   r]   r^   r>     s    r>   c                 C   s   t | t jS r`   )rZ   r{   r   r  r]   r]   r^   r?     s    r?   )rJ   r   down_interpolationup_interpolationrM   c           	      C   s   | j d d \}}|tjks&|tjko0| jtjk}|r>t| } tj| d |||d}tj|||f|d}|rtt	|ddtddS |S )NrE   )ZfxZfyinterpolation)r(  r   rP   r   rN   )
rR   rZ   ZINTER_NEARESTrO   rU   r   r=   resizer,   r   )	rJ   r   r&  r'  r   r   Z	need_castZ
downscaledZupscaledr]   r]   r^   r)     s    
r)   )rJ   r   rM   c                 C   s>   |d u r.| j tvr$td| j  dt| j  }| | tjS )NzUnsupported dtype z. Specify 'max_value' manually.)rO   r   RuntimeErrorrY   rU   rQ   )rJ   r   r]   r]   r^   r=     s
    

r=   )rJ   rO   r   rM   c                 C   s:   |d u r,|t vr$d| d}t|t | }| | |S )Nz(Can't infer the maximum value for dtype zS. You need to specify the maximum value manually by passing the max_value argument.)r   r*  rY   )rJ   rO   r   r   r]   r]   r^   r,   %  s    
r,   )	input_objparamsrM   c                 K   s   | S r`   r]   )r+  r,  r]   r]   r^   r5   1  s    r5   )re   tilesmappingrM   c                 C   s~   |j dks|du r|  S t| }t|D ]L\}}|| \}}}}	|| \}
}}}| |
|||f |||||	f< q,|S )a@  Swap tiles on the image according to the new format.

    Args:
        image: Input image.
        tiles: Array of tiles with each tile as [start_y, start_x, end_y, end_x].
        mapping: List of new tile indices.

    Returns:
        np.ndarray: Output image with tiles swapped according to the random shuffle.
    r   N)r!  r   rU   r   r   )re   r-  r.  Z	new_imager
  Z	new_indexstart_ystart_xend_yend_xZstart_y_origZstart_x_origZ
end_y_origZ
end_x_origr]   r]   r^   r<   5  s    
&r<   )rJ   
multiplierrM   c                 C   s   |  tj} t| |S r`   )rY   rU   rQ   r4   rJ   r3  r]   r]   r^   _multiply_uint8O  s    r5  c                 C   s  t | st|dkr`|d }tjddtjd}||9 }t|tjt| j }t	t
j|d}|| S | jd }tjddtjdg| }tj|dd}||9 }t|tjt| j }g }t|D ]>}t	t
j|d d |f d}||| d d d d |f  qtj|ddS )NrP   r   rx   rN   r   rj   rk   )r   rS   rU   r~   rQ   r   r   r   rO   r   rZ   r   rR   stackr   append)rJ   r3  r   funcr   Zimagesr   r]   r]   r^   _multiply_uint8_optimizedU  s"    
"r9  c                 C   s   | | S r`   r]   r4  r]   r]   r^   _multiply_non_uint8m  s    r:  c                 C   s8   | j tjkr.t|jdkr$t| |S t| |S t| |S )zArgs:

        img: Image.
        multiplier: Multiplier coefficient.

    Returns:
        Image multiplied by `multiplier` coefficient.

    rP   )rO   rU   r   rS   rR   r9  r5  r:  r4  r]   r]   r^   r4   r  s
    


r4   )r   rM   c                 C   sp   t j| dd}| sdS t j| dd}t |d ddg \}}t |d ddg \}}|||d |d fS )zCreate bounding box from binary mask (fast version)

    Args:
        mask (numpy.ndarray): binary mask.

    Returns:
        tuple: A bounding box tuple `(x_min, y_min, x_max, y_max)`.

    rP   rk   )rj   rj   rj   rj   r   rj   )rU   r   where)r   rowscolsy_miny_maxx_minx_maxr]   r]   r^   bbox_from_mask  s    
rB  )rJ   bboxrM   c                 C   s>   t j| jdd t jd}|\}}}}d|||||f< |S )zCreate binary mask from bounding box

    Args:
        img: input image
        bbox: A bounding box tuple `(x_min, y_min, x_max, y_max)`

    Returns:
        mask: binary mask

    NrE   rN   rP   )rU   r   rR   r   )rJ   rC  r   r@  r>  rA  r?  r]   r]   r^   mask_from_bbox  s    rD  皙?)rJ   r  rM   c                 C   s.  t | r| jtjkr d}t|| t }| d } | dd}|tj	|dd }tj
|dd}tj|\}}|d	d	d  }	|d	d	d   |d	d	|	f }t|}
td
}||d	d	  |d	d	df< t|
t| }tdD ] }|d|f  || d 7  < qt|dd}|tjS )a  Perform 'Fancy PCA' augmentation from:
    http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf

    Args:
        img: numpy array with (h, w, rgb) shape, as ints between 0-255
        alpha: how much to perturb/scale the eigen vecs and vals
                the paper used std=0.1

    Returns:
        numpy image-like array as uint8 range(0, 255)

    z(Image must be RGB image in uint8 format.rb   rj   rF   r   rk   F)ZrowvarN)rF   rP   .rz   r   )r   rO   rU   r   r   rY   r#  r   r   rK   ZcovZlinalgZeighZargsortsortZcolumn_stackr   rV   r   r   )rJ   r  r   Zorig_imgZimg_rsZimg_centeredZimg_covZeig_valsZeig_vecsZ	sort_permm1m2Zadd_vectr   r]   r]   r^   r+     s(    

r+   )rJ   factorrM   c                 C   s2   t dd| }t |ddt j}t| |S )Nr   rx   rz   )rU   r~   r   rY   r   rZ   r   rJ   rI  r   r]   r]   r^   $_adjust_brightness_torchvision_uint8  s    rK  c                 C   sL   |dkrt | S |dkr| S | jt jkr4t| |S t| | | jt| j S )Nr   rP   )rU   r   rO   r   rK  r   r   rJ   rI  r]   r]   r^   r!     s    

r!   )rJ   rI  rK   rM   c                 C   s:   t dd| }||d|   }t|| jd}t| |S )Nr   rx   rP   rz   )rU   r~   r   rO   rZ   r   )rJ   rI  rK   r   r]   r]   r^   "_adjust_contrast_torchvision_uint8  s    rM  c                 C   s   |dkr| S t | r|  nt| tj }|dkr`| jtjkrNt|d }tj	| || jdS | jtj
krxt| ||S t| tj| |d|   | jt| j S )NrP   r   r  rN   )r   rK   rZ   r{   r   rO   rU   rQ   r   r   r   rM  r   rY   r   )rJ   rI  rK   r]   r]   r^   r"     s    "r"   )rJ   rI  r  rM   c                 C   s|   |dkr| S t | r| S t| tj}t|tj}|dkr@|S tj| ||d| |d}| jtjkrh|S t	|| jt
| j S )NrP   r   )r  )r   rZ   r{   r   r   r   rO   rU   r   r   r   )rJ   rI  r  r%  resultr]   r]   r^   r$     s    r$   c                 C   s^   t | t j} tjddtjd}t|d|  dtj}t 	| d || d< t | t j
S )Nr   rx   rN   ry   r   )rZ   r{   r|   rU   r~   r   r   rY   r   r   r   rJ  r]   r]   r^   _adjust_hue_torchvision_uint82  s
    rO  c                 C   sf   t | r| S |dkr| S | jtjkr.t| |S t| tj} t| d |d  d| d< t| tj	S )Nr   r   rI   )
r   rO   rU   r   rO  rZ   r{   r|   r   r   rL  r]   r]   r^   r#   <  s    
r#   )re   
n_segmentsreplace_samplesmax_sizer(  rM   c                 C   s  t |s| S | j}|d urt| jd d }||kr|| }| jd d \}}	t|| t|	|  }
}ttj||
f|d}|| } tj	j
| |d| jtkrdnd d}d}t| j }t | } | jtkr| jg | jdR  } | jd }t|D ]}tjj|d | d|f d	}t|D ]l\}}||t|  r|j}| d|f }|jjd
v rttt |}tt|||}n|}||||k< qq|| jkrttj|d |d f|d}|| S | S )NrE   )Zdsizer(  r   rj   )rP  ZcompactnessZchannel_axisr   rP   .)Zintensity_image)r   ub)rU   r   rR   rr   r   r   rZ   r)  skimageZsegmentationZslicrn   TWOr   rO   r   r   r   ZmeasureZregionpropsr   rS   mean_intensitykindr   rq   )re   rP  rQ  rR  r(  Z
orig_shaper!  r   r   r   Z
new_heightZ	new_widthZ	resize_fnsegmentsZ	min_valuer   Znb_channelscZregionsZridxZregionrW  Z
image_sp_cr   r]   r]   r^   r;   K  sT    




r;   )img1r  img2r  rM   c                 C   s&   | | j| j}t| |||dS Nr   )r   rR   rY   rO   rZ   r   )r[  r  r\  r  r]   r]   r^   r      s    r    r   皙?r   )re   ksizesigmar  r   rM   c                 C   s   t tj||f|d}| j}|tjkr.t| } n |tjtjfvrNtd| d|| }| | }t	|d |k}	|	
d}	| ||  }
t|
dd}
||	}||
 d| |   }t||dS )	N)r_  ZsigmaXr   z for UnsharpMask augmentationrz   rQ   r   rP   rN   )r   rZ   ZGaussianBlurrO   rU   r   r=   rQ   rs   absrY   r   r,   )re   r_  r`  r  r   Zblur_fnr   r   Zresidualr   ZsharpZ	soft_maskr  r]   r]   r^   r@     s    	


r@   )re   	drop_mask
drop_valuerM   c                 C   s<   t |ttfr"|dkr"t| }nt| |}t||| S r]  )
isinstancer   r#  rU   r   r   r;  )re   rb  rc  Zdrop_valuesr]   r]   r^   pixel_dropout  s    re  )rJ   non_mudmudrainr   rM   c                 C   s   t |  t| j }| tjd|  } |dkrL|d u rBd}t|| |7 } nN|dkr|d u rhd}t||d u r|d}t|| | | } ntdt| | d S )	NrP   rh  zRain spatter requires rain maskrg  zMud spatter requires mud maskz!Mud spatter requires non_mud maskzUnsupported spatter mode: rz   )r   r   rO   rY   rU   rQ   rs   str)rJ   rf  rg  rh  r   Zcoefr   r]   r]   r^   spatter  s$    	

rj  )r   partsrM   c                    s,   t | |\ t fddt|D S )a  Generates an array of nearly equal integer intervals that sum up to `n`.

    This function divides the number `n` into `parts` nearly equal parts. It ensures that
    the sum of all parts equals `n`, and the difference between any two parts is at most one.
    This is useful for distributing a total amount into nearly equal discrete parts.

    Args:
        n (int): The total value to be split.
        parts (int): The number of parts to split into.

    Returns:
        np.ndarray: An array of integers where each integer represents the size of a part.

    Example:
        >>> almost_equal_intervals(20, 3)
        array([7, 7, 6])  # Splits 20 into three parts: 7, 7, and 6
        >>> almost_equal_intervals(16, 4)
        array([4, 4, 4, 4])  # Splits 16 into four equal parts
    c                    s    g | ]}|k r d  n qS rP   r]   r   Z	part_size	remainderr]   r^   r     r   z*almost_equal_intervals.<locals>.<listcomp>)divmodrU   rV   r   )r   rk  r]   rm  r^   almost_equal_intervals  s    rp  )r!  	divisionsr  rM   c                 C   s,   t | |}tj||d}tt|ddS )a  Generate shuffled splits for a given dimension size and number of divisions.

    Args:
        size (int): Total size of the dimension (height or width).
        divisions (int): Number of divisions (rows or columns).
        random_state (Optional[np.random.RandomState]): Seed for the random number generator for reproducibility.

    Returns:
        np.ndarray: Cumulative edges of the shuffled intervals.
    r  r   )rp  r   shufflerU   insertZcumsum)r!  rq  r  Z	intervalsr]   r]   r^   generate_shuffled_splits  s    
ru  )image_shapegridr  rM   c                    sT   |\}t | d |d | t | d |d | fddt|D }t|S )al  Splits an image shape into a uniform grid specified by the grid dimensions.

    Args:
        image_shape (Tuple[int, int]): The shape of the image as (height, width).
        grid (Tuple[int, int]): The grid size as (rows, columns).

    Returns:
        np.ndarray: An array containing the tiles' coordinates in the format (start_y, start_x, end_y, end_x).
    r   rP   c              	      s>   g | ]6}t D ](} | |  |d   |d   fqqS rl  )r   )r   r   jZheight_splitsZn_colsZwidth_splitsr]   r^   r   #  s   z&split_uniform_grid.<locals>.<listcomp>)ru  r   rU   rV   )rv  rw  r  Zn_rowsr-  r]   ry  r^   rA     s    rA   )r-  rM   c                 C   sD   t t}t| D ].\}\}}}}|| || f}|| | q|S )zBGroups tiles by their shape and stores the indices for each shape.)r   listr   r7  )r-  shape_groupsindexr/  r0  r1  r2  rR   r]   r]   r^   create_shape_groups,  s
    r}  )r{  r  rM   c                 C   s`   t dd |  D }dg| }|  D ]2}tj| |d}t||D ]\}}|||< qHq(|S )a  Shuffles indices within each group of similar shapes and creates a list where each
    index points to the index of the tile it should be mapped to.

    Args:
        shape_groups (Dict[Tuple[int, int], List[int]]): Groups of tile indices categorized by shape.
        random_state (Optional[np.random.RandomState]): Seed for the random number generator for reproducibility.

    Returns:
        List[int]: A list where each index is mapped to the new index of the tile after shuffling.
    c                 s   s   | ]}t |V  qd S r`   )rS   )r   indicesr]   r]   r^   	<genexpr>D  r   z4shuffle_tiles_within_shape_groups.<locals>.<genexpr>rj   rr  )r   valuesr   rs  r   zip)r{  r  Z	num_tilesr.  r~  Zshuffled_indicesoldnewr]   r]   r^   !shuffle_tiles_within_shape_groups5  s    
r  )rJ   primary_distortion_redsecondary_distortion_redprimary_distortion_bluesecondary_distortion_bluer(  rM   c                 C   s   t |  | jd d \}}tjdtjd}||d< ||d< |d |d< |d |d< tj||d	d	gtjd}	tj||d	d	gtjd}
t| d
 ||	|||}t| d ||
|||}t|| d |gS )NrE   rF   rN   )r   r   )rP   rP   r   )r   rE   )rP   rE   r   r   ).rE   r"  )r   rR   rU   ZeyerQ   rV   _distort_channelZdstack)rJ   r  r  r  r  r(  r   r   
camera_matZdistortion_coeffs_redZdistortion_coeffs_blueZred_distortedZblue_distortedr]   r]   r^   rB   Q  s4    	rB   )channelr  distortion_coeffsr   r   r(  rM   c                 C   s6   t j||d |||ft jd\}}t j| |||t jdS )N)ZcameraMatrixZ
distCoeffsRZnewCameraMatrixr!  Zm1type)r(  Z
borderMode)rZ   ZinitUndistortRectifyMapZCV_32FC1ZremapZBORDER_REPLICATE)r  r  r  r   r   r(  Zmap_xZmap_yr]   r]   r^   r  }  s    
r  c                 C   s   t j| |ddS NrP   )Z
iterations)rZ   rC   rJ   r   r]   r]   r^   rC     s    rC   c                 C   s   t j| |ddS r  )rZ   rD   r  r]   r]   r^   rD     s    rD   )rJ   r   	operationrM   c                 C   s6   |dkrt | |S |dkr$t| |S td| d S )NZdilationZerosionzUnsupported operation: )rD   rC   rs   )rJ   r   r  r]   r]   r^   
morphology  s
    

r  )rb   )r   )N)N)N)Nr   T)r   r   )rP   r   F)rP   r   F)rP   r   F)r  r  N)N)N)N)rE  )r   )r   r^  r   )N)N)N)~collectionsr   typingr   r   r   r   r   r   r	   warningsr
   rZ   numpyrU   rU  Ztyping_extensionsr   Zalbumentationsr   Z"albumentations.augmentations.utilsr   r   r   r   r   r   r   r   r   Zalbumentations.core.typesr   r   r   r   __all__rV  ZTHREEZNUM_RGB_CHANNELSro   rT   r   ZTHREE_SIXTYr   r_   ra   r#  r6   rt   r   r   r8   r   r:   r7   r   r   boolr   r   r*   r3   r   r   r   r9   r2   r'   r(   r/   r   r   r   r   r   r   r0   r&   r-   r.   r  r  r%   r1   r>   r?   Z
INTER_AREAZINTER_LINEARr)   r=   rO   r,   r5   r<   r5  r9  r:  r4   rB  rD  r+   rK  r!   rM  r"   r$   rO  r#   r;   r    r@   re  rj  rp  randomZRandomStateru  rA   r}  r  rB   r  rC   rD   ri  r  r]   r]   r]   r^   <module>   s&  $,/7"4    $
$-?(2> )&            /	 $"B
B    (! 
 


& 
-