
    hB                       S r SSKJr  SSKJr  SSKJr  SSKrSSKr	SSK
JrJr  SSKJr  SSKJr  SS	KJrJr  / S
Qr          SS jr S         SS jjr\" S5            SS j5       rSS jrSS jr\                  SS j5       r            SS jr\" S5           S             S S jj5       r            S!S jr            S"S jr S#                   S$S jjr g)%a  Functional implementations of image cropping operations.

This module provides utility functions for performing various cropping operations on images,
bounding boxes, and keypoints. It includes functions to calculate crop coordinates, crop images,
and handle the corresponding transformations for bounding boxes and keypoints to maintain
consistency between different data types during cropping operations.
    )annotations)Sequence)AnyN)maybe_process_in_chunkspreserve_channel_dim)
functional)handle_empty_array)denormalize_bboxesnormalize_bboxes)cropcrop_and_padcrop_and_pad_bboxescrop_and_pad_keypointscrop_bboxes_by_coordscrop_keypoints_by_coordsget_center_crop_coordsget_crop_coordspad_along_axesvolume_crop_yxvolumes_crop_yxc                    U SS u  pE[        US   U5      n[        US   U5      n[        XF-
  S-   U-  5      nX-   n	[        XW-
  S-   U-  5      n
X-   nXX4$ )a/  Get crop coordinates.

This function gets the crop coordinates.

Args:
    image_shape (tuple[int, int]): Original image shape.
    crop_shape (tuple[int, int]): Crop shape.
    h_start (float): Start height.
    w_start (float): Start width.

Returns:
    tuple[int, int, int, int]: Crop coordinates.

N   r      )minint)image_shape
crop_shapeh_startw_startheightwidthcrop_height
crop_widthy_miny_maxx_minx_maxs               g/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/crops/functional.pyr   r   %   s|    2  OMF jmV,KZ]E*J%)W45EE#a'723EE%%    c                   U R                   (       d  U $ U(       a8  [        U R                  5       R                  [        R
                  5      U5      nO-U R                  5       R                  [        R
                  5      nUSS u  pVUSS2SS/4==   U-  ss'   USS2SS/4==   U-  ss'   US   US   -
  nUS   US   -
  nXx4n	U(       a  [        XI5      $ U$ )a  Crop bounding boxes based on given crop coordinates.

This function adjusts bounding boxes to fit within a cropped image.

Args:
    bboxes (np.ndarray): Array of bounding boxes with shape (N, 4+) where each row is
                         [x_min, y_min, x_max, y_max, ...]. The bounding box coordinates
                         can be either normalized (in [0, 1]) if normalized_input=True or
                         absolute pixel values if normalized_input=False.
    crop_coords (tuple[int, int, int, int]): Crop coordinates (x_min, y_min, x_max, y_max)
                                             in absolute pixel values.
    image_shape (tuple[int, int]): Original image shape (height, width).
    normalized_input (bool): Whether input boxes are in normalized coordinates.
                           If True, assumes input is normalized [0,1] and returns normalized coordinates.
                           If False, assumes input is in absolute pixels and returns absolute coordinates.
                           Default: True for backward compatibility.

Returns:
    np.ndarray: Array of cropped bounding boxes. Coordinates will be in the same format as input
               (normalized if normalized_input=True, absolute pixels if normalized_input=False).

Note:
    Bounding boxes that fall completely outside the crop area will be removed.
    Bounding boxes that partially overlap with the crop area will be adjusted to fit within it.

Nr   r   r      )sizer
   copyastypenpfloat32r   )
bboxescrop_coordsr   normalized_inputcropped_bboxesr&   r$   r"   r#   r   s
             r(   r   r   K   s    @ ;; +FKKM,@,@,LkZ--bjj9r?LE 1q!f9&1q!f9& a.;q>1KQ+a.0J*J <LN7_Q__r)   	keypointsc                x    USS u  p#U R                  5       nUSS2S4==   U-  ss'   USS2S4==   U-  ss'   U$ )am  Crop keypoints using the provided coordinates of bottom-left and top-right corners in pixels.

Args:
    keypoints (np.ndarray): An array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
    crop_coords (tuple): Crop box coords (x1, y1, x2, y2).

Returns:
    np.ndarray: An array of cropped keypoints with the same shape as the input.

Nr   r   r   )r-   )r5   r2   x1y1cropped_keypointss        r(   r   r      sL     !_FB!(adr!adr!r)   c                R    U SS u  p#USS u  pEX$-
  S-  nXd-   nX5-
  S-  nX-   n	XX4$ )zGet center crop coordinates.

This function gets the center crop coordinates.

Args:
    image_shape (tuple[int, int]): Original image shape.
    crop_shape (tuple[int, int]): Crop shape.

Returns:
    tuple[int, int, int, int]: Center crop coordinates.

Nr    )
r   r   r    r!   r"   r#   r$   r%   r&   r'   s
             r(   r   r      sT      OMF(!nK!a'EEA%EE%%r)   c                    U R                   SS u  pVX1::  d  XB::  a  [        SU SU SU SU S3	5      eUS:  d  X6:  d  US:  d  XE:  a  [        S	U SU SU SU S
U SU S35      eXU2X24   $ )a  Crop an image.

This function crops an image.

Args:
    img (np.ndarray): Input image.
    x_min (int): Minimum x coordinate.
    y_min (int): Minimum y coordinate.
    x_max (int): Maximum x coordinate.
    y_max (int): Maximum y coordinate.

Returns:
    np.ndarray: Cropped image.

Nr   zDWe should have x_min < x_max and y_min < y_max. But we got (x_min = z
, y_min = z
, x_max = z
, y_max = )r   zUValues for crop should be non negative and equal or smaller than image sizes(x_min = z, height = z
, width = shape
ValueError)imgr&   r$   r'   r%   r    r!   s          r(   r   r      s      IIbqMMF~z%
5'E7RSU
 	

 qyEMUQY%.wjz%
5' Rxz%3
 	
 U{EK'((r)   c           
     2   Ub#  [        S U 5       5      (       a  [        U /UQ76 n Ub=  [        S U 5       5      (       a&  [        R                  " U US   US   US   US   UUS9n U(       a)  USS u  p[	        [
        R                  X4US	9n
U
" U 5      $ U $ )
a"  Crop and pad an image.

This function crops and pads an image.

Args:
    img (np.ndarray): Input image.
    crop_params (tuple[int, int, int, int] | None): Crop parameters.
    pad_params (tuple[int, int, int, int] | None): Pad parameters.
    pad_value (tuple[float, ...] | float | None): Pad value.
    image_shape (tuple[int, int]): Original image shape.
    interpolation (int): Interpolation method.
    pad_mode (int): Pad mode.
    keep_size (bool): Whether to keep the original size.

Returns:
    np.ndarray: Cropped and padded image.

Nc              3  *   #    U  H	  oS :g  v   M     g7fr   Nr;   .0is     r(   	<genexpr>crop_and_pad.<locals>.<genexpr>   s     &C{!Av{   c              3  *   #    U  H	  oS :g  v   M     g7frD   r;   rE   s     r(   rH   rI      s     %Aj1fjrJ   r   r   r   r+   )border_modevalue)dsizeinterpolation)anyr   
fgeometricpad_with_paramsr   cv2resize)rA   crop_params
pad_params	pad_valuer   rO   pad_mode	keep_sizerowscols	resize_fns              r(   r   r      s    : 3&C{&C#C#C3%%#%Aj%A"A"A((qMqMqMqM 
  !_
+CJJtlZgh	~Jr)   c                   [        U 5      S:X  a  U $ [        X5      nUb-  USS u  pgUSS2SS/4==   U-  ss'   USS2SS/4==   U-  ss'   Ub+  Uu  ppUSS2SS/4==   U
-  ss'   USS2SS/4==   U-  ss'   [        XT5      $ )a  Crop and pad bounding boxes.

This function crops and pads bounding boxes.

Args:
    bboxes (np.ndarray): Array of bounding boxes.
    crop_params (tuple[int, int, int, int] | None): Crop parameters.
    pad_params (tuple[int, int, int, int] | None): Pad parameters.
    image_shape (tuple[int, int]): Original image shape.
    result_shape (tuple[int, int]): Result image shape.

Returns:
    np.ndarray: Array of cropped and padded bounding boxes.

r   Nr   r   r+   )lenr
   r   )r1   rU   rV   r   result_shapedenormalized_bboxescrop_xcrop_ytop_lefts              r(   r   r     s    , 6{a -VA$RaA1vI&&0&A1vI&&0&$A1vI&$.&A1vI&#-& />>r)   c                P   U R                  5       nUb)  USS u  pxUSS2S4==   U-  ss'   USS2S4==   U-  ss'   Ub'  Uu  ppUSS2S4==   U-  ss'   USS2S4==   U	-  ss'   USS u  pUSS u  pU(       a*  X:w  d  X:w  a   X-  nX-  n[        R                  " UUU5      $ U$ )ak  Crop and pad multiple keypoints simultaneously.

Args:
    keypoints (np.ndarray): Array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
    crop_params (Sequence[int], optional): Crop parameters [crop_x1, crop_y1, ...].
    pad_params (Sequence[int], optional): Pad parameters [top, bottom, left, right].
    image_shape (Tuple[int, int]): Original image shape (rows, cols).
    result_shape (Tuple[int, int]): Result image shape (rows, cols).
    keep_size (bool): Whether to keep the original size.

Returns:
    np.ndarray: Array of transformed keypoints with the same shape as input.

Nr   r   r   )r-   rQ   keypoints_scale)r5   rU   rV   r   r_   rY   transformed_keypointscrop_x1crop_y1rc   rd   re   rZ   r[   result_rowsresult_colsscale_xscale_ys                     r(   r   r   1  s    . &NN,&r?ad#w.#ad#w.#$ad#t+#ad#s*#RaJD+BQ/Kk)[-@$$))*?'RR  r)   c                    U R                   SS u  pVnX1::  d  XB::  a  [        SU SU SU SU S3	5      eUS:  d  US:  d
  X7:  d  XF:  a'  [        S	U SU SU SU S
U R                   SS  3
5      eU SS2X$2X24   $ )a  Crop a single volume along Y (height) and X (width) axes only.

Args:
    volume (np.ndarray): Input volume with shape (D, H, W) or (D, H, W, C).
    x_min (int): Minimum width coordinate.
    y_min (int): Minimum height coordinate.
    x_max (int): Maximum width coordinate.
    y_max (int): Maximum height coordinate.

Returns:
    np.ndarray: Cropped volume (D, H_new, W_new, [C]).

Raises:
    ValueError: If crop coordinates are invalid.

Nr+   5Crop coordinates must satisfy min < max. Got: (x_min=, y_min=, x_max=, y_max=r=   r   ECrop coordinates must be within image dimensions (H, W). Got: (x_min=) for volume shape r>   )volumer&   r$   r'   r%   rd   r    r!   s           r(   r   r   _  s    . ||BQ'Au~WHUG8E7(5'L
 	

 qyEAI%.WHUG8E7(5' J  &Ra 013
 	
 !U[%+-..r)   c                N   SU R                   s=::  a  S::  d  O  [        SU R                    35      eU R                  SS u  pVnX1::  d  XB::  a  [        SU SU SU SU S	3	5      eUS
:  d  US
:  d
  X7:  d  XF:  a  [        SU SU SU SU SXVU4 3
5      eU SS2SS2X$2X24   $ )a  Crop a batch of volumes along Y (height) and X (width) axes only.

Args:
    volumes (np.ndarray): Input batch of volumes with shape (B, D, H, W) or (B, D, H, W, C).
    x_min (int): Minimum width coordinate.
    y_min (int): Minimum height coordinate.
    x_max (int): Maximum width coordinate.
    y_max (int): Maximum height coordinate.

Returns:
    np.ndarray: Cropped batch of volumes (B, D, H_new, W_new, [C]).

Raises:
    ValueError: If crop coordinates are invalid or volumes shape is incorrect.

      z1Input volumes should have 4 or 5 dimensions, got r   rp   rq   rr   rs   r=   r   rt   ru   N)ndimr@   r?   )volumesr&   r$   r'   r%   depthr    r!   s           r(   r   r     s    . !!LW\\N[\\"==1-E5~WHUG8E7(5'L
 	

 qyEAI%.WHUG8E7(5' J !& 679
 	
 1aek122r)   c	           
        U R                   n	SUs=::  a  U	:  a  O  OSUs=::  a  U	:  d  O  [        SU SU SU	 S35      eXV:X  a  [        SU SU S35      e[        R                  S	[        R                  S
[        R
                  S[        R                  S[        R                  S0n
Xz;  a  [        SU 35      eX   nS/U	-  nX4X'   X44X'   SU0nUS	:X  a  XS'   [        R                  " X40 UD6$ )a  Pad an array along specified height (H) and width (W) axes using np.pad.

Args:
    arr (np.ndarray): Input array.
    pad_top (int): Padding added to the top (start of H axis).
    pad_bottom (int): Padding added to the bottom (end of H axis).
    pad_left (int): Padding added to the left (start of W axis).
    pad_right (int): Padding added to the right (end of W axis).
    h_axis (int): Index of the height axis (Y).
    w_axis (int): Index of the width axis (X).
    border_mode (int): OpenCV border mode.
    pad_value (float | Sequence[float]): Value for constant padding.

Returns:
    np.ndarray: Padded array.

Raises:
    ValueError: If border_mode is unsupported or axis indices are out of bounds.

r   zAxis indices z, z" are out of bounds for array with z dimensions.zHeight axis z and width axis z cannot be the same.constantedgereflect	symmetricwrapzUnsupported border_mode: r   r   modeconstant_values)
rz   r@   rS   BORDER_CONSTANTBORDER_REPLICATEBORDER_REFLECTBORDER_REFLECT_101BORDER_WRAPr/   pad)arrpad_top
pad_bottompad_left	pad_righth_axisw_axisrL   rW   rz   mode_mapnp_mode	pad_widthkwargss                 r(   r   r     s   > 88D$1#5#5=6(:\]a\bbnopp<x/?xG[\]] 	ZfIH "4[MBCC#G4I -I!-I %g.F*$- !66#+F++r)   )
r   tuple[int, int]r   r   r   floatr   r   returntuple[int, int, int, int])T)
r1   
np.ndarrayr2   r   r   r   r3   boolr   r   )r5   r   r2   r   r   r   )r   r   r   r   r   r   )rA   r   r&   r   r$   r   r'   r   r%   r   r   r   )rA   r   rU    tuple[int, int, int, int] | NonerV   r   rW   z tuple[float, ...] | float | Noner   r   rO   r   rX   r   rY   r   r   r   )r1   r   rU   r   rV   r   r   r   r_   r   r   r   )NNr   r   F)r5   r   rU   r   rV   r   r   r   r_   r   rY   r   r   r   )rv   r   r&   r   r$   r   r'   r   r%   r   r   r   )r{   r   r&   r   r$   r   r'   r   r%   r   r   r   )r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   rL   r   rW   zfloat | Sequence[float]r   r   )!__doc__
__future__r   collections.abcr   typingr   rS   numpyr/   albucorer   r   &albumentations.augmentations.geometricr   rQ   "albumentations.augmentations.utilsr	   albumentations.core.bbox_utilsr
   r   __all__r   r   r   r   r   r   r   r   r   r   r   r;   r)   r(   <module>r      s   # $  
  B K A O#& #&#& #& 	#&
 #&T "	5`5`*5` !5` 	5`
 5`p K *  !.&.)B .	.1. 1. 0	.
 !. . . . . .b)?)?1)? 1)? !	)?
 ")? )?X K  5937#)$**!*!1*! 1*! !	*!
 "*! *! *! !*!Z&/&/&/ &/ 	&/
 &/ &/R)3)3)3 )3 	)3
 )3 )3j *+:,	:,:, :, 	:,
 :, :, :, :, ':, :,r)   