
    2Vh):                     x    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	m
Z
  ed       G d d	e             Zy
)    )keras_export)BaseImagePreprocessingLayer)clip_to_image_size)convert_format)SeedGenerator)backend_utilszkeras.layers.RandomShearc                        e Zd ZdZdZdZdZdZdZ	 	 	 	 	 	 	 d fd	Z	d Z
d	 Zdd
ZddZd Zd ZddZd Zd Z	 ddZd Z	 ddZ fdZd Z xZS )RandomShearaH
  A preprocessing layer that randomly applies shear transformations to
    images.

    This layer shears the input images along the x-axis and/or y-axis by a
    randomly selected factor within the specified range. The shear
    transformation is applied to each image independently in a batch. Empty
    regions created during the transformation are filled according to the
    `fill_mode` and `fill_value` parameters.

    Args:
        x_factor: A tuple of two floats. For each augmented image, a value
            is sampled from the provided range. If a float is passed, the
            range is interpreted as `(0, x_factor)`. Values represent a
            percentage of the image to shear over. For example, 0.3 shears
            pixels up to 30% of the way across the image. All provided values
            should be positive.
        y_factor: A tuple of two floats. For each augmented image, a value
            is sampled from the provided range. If a float is passed, the
            range is interpreted as `(0, y_factor)`. Values represent a
            percentage of the image to shear over. For example, 0.3 shears
            pixels up to 30% of the way across the image. All provided values
            should be positive.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        fill_mode: Points outside the boundaries of the input are filled
            according to the given mode. Available methods are `"constant"`,
            `"nearest"`, `"wrap"` and `"reflect"`. Defaults to `"constant"`.
            - `"reflect"`: `(d c b a | a b c d | d c b a)`
                The input is extended by reflecting about the edge of the
                last pixel.
            - `"constant"`: `(k k k k | a b c d | k k k k)`
                The input is extended by filling all values beyond the edge
                with the same constant value `k` specified by `fill_value`.
            - `"wrap"`: `(a b c d | a b c d | a b c d)`
                The input is extended by wrapping around to the opposite edge.
            - `"nearest"`: `(a a a a | a b c d | d d d d)`
                The input is extended by the nearest pixel.
            Note that when using torch backend, `"reflect"` is redirected to
            `"mirror"` `(c d c b | a b c d | c b a b)` because torch does
            not support `"reflect"`.
            Note that torch backend does not support `"wrap"`.
        fill_value: A float representing the value to be filled outside the
            boundaries when `fill_mode="constant"`.
        seed: Integer. Used to create a random seed.
    F)r      z[The `factor` argument should be a number (or a list of two numbers) in the range [0, 1.0]. )reflectwrapconstantnearest)r   bilinearc                    t        	|   d	d|i| | j                  |d      | _        | j                  |d      | _        || j
                  vrt        d| d| j
                   d      || j                  vrt        d| d| j                   d      || _        || _	        || _
        || _        t        |      | _        d| _        y )
Ndata_formatx_factory_factorzUnknown `fill_mode` z. Expected of one .zUnknown `interpolation` F )super__init___set_factor_with_namer   r   _SUPPORTED_FILL_MODENotImplementedError_SUPPORTED_INTERPOLATION	fill_mode
fill_valueinterpolationseedr   	generatorsupports_jit)
selfr   r   r   r   r   r   r    kwargs	__class__s
            o/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/preprocessing/image_preprocessing/random_shear.pyr   zRandomShear.__init__H   s     	;[;F;228ZH228ZHD555%&yk1C,,-Q0   = ==%*=/9K0014 
 #$*	&t,!    c                    t        |t        t        f      rft        |      dk7  rt	        | j
                  d| d| z         | j                  |d          | j                  |d          t        |      \  }}||fS t        |t        t        f      r(| j                  |       t        |      }| |g\  }}||fS t	        | j
                  d| d| z         )N   z
Received: =r   r   )
isinstancetuplelistlen
ValueError_FACTOR_VALIDATION_ERROR_check_factor_rangesortedintfloatabs)r#   factorfactor_nameloweruppers        r&   r   z!RandomShear._set_factor_with_namei   s    fudm,6{a 11";-q9:  $$VAY/$$VAY/!&>LE5 e| e-$$V,[F#GV,LE5 e|	 --{m1VH56 r'   c                 N    |dkD  s|dk  rt        | j                  d| z         y )Ng      ?        zReceived: input_number=)r/   r0   )r#   input_numbers     r&   r1   zRandomShear._check_factor_range~   s;    #!3--+L>:;  "4r'   c                 "   |sy t        |t              r|d   }n|}| j                  j                  |      }t	        |      dk(  rd}n|d   }|%| j                  | j                  j                        }| j                  j                  j                  dd|dg|| j                        }| j                  j                  j                  |dkD  | j                  j                  j                  |       | j                  j                  j                  |            }| j                  j                  j                  | j                  d   | j                  d   |dg|| j                        }| j                  j                  j                  | j                  d   | j                  d   |dg|| j                        }	| j                  j                  | j                  j                  j!                  |	|gd      | j                        |z  }
|
|d	S )
Nimages   r   r   )minvalmaxvalshaper    dtypeg      ?axisrC   )shear_factorinput_shape)r+   dictbackendrB   r.   _get_seed_generator_backendrandomuniformcompute_dtypenumpywhere	ones_liker   r   castconcatenate)r#   datatrainingr    r>   images_shape
batch_sizeinvertshear_yshear_xrG   s              r&   get_random_transformationz%RandomShear.get_random_transformation   s   dD!(^FF||))&1|!J%aJ<++DLL,A,ABD$$,,q/$$ - 
 ##))SL\\))&11LL((0
 ,,%%--==#==#q/$$ . 
 ,,%%--==#==#q/$$ . 
 LL""../A.J((   	 	 !-\JJr'   c                 z    | j                   j                  || j                        }|r| j                  ||      S |S N)rJ   rS   rO   _shear_inputs)r#   r>   transformationrV   s       r&   transform_imageszRandomShear.transform_images   s9    ""64+=+=>%%fn==r'   c                    ||S | j                   j                  |      }t        |      dk(  }|r'| j                   j                  j	                  |d      }|d   }| j                   j
                  j                  || j                  |      | j                  | j                  | j                  | j                        }|r'| j                   j                  j                  |d      }|S )Nr?   r   rD   rG   )	transformr   r   r   r   )rJ   rB   r.   rP   expand_dimsimageaffine_transform_get_shear_matrixr   r   r   r   squeeze)r#   inputsr`   inputs_shape	unbatchedrG   outputss          r&   r_   zRandomShear._shear_inputs   s    !M||))&1%*	\\''33F3CF%n5,,$$55,,\:,,nn(( 6 
 ll((00q0AGr'   c                 h   | j                   j                  |      d   }| j                   j                  j                  | j                   j                  j	                  |f      |d d df   | j                   j                  j                  |f      |d d df   | j                   j                  j	                  |f      | j                   j                  j                  |f      | j                   j                  j                  |f      | j                   j                  j                  |f      gd      S )Nr   r   rD   )rJ   rB   rP   stackoneszeros)r#   shear_factorsnum_shear_factorss      r&   rg   zRandomShear._get_shear_matrix   s
    LL..}=a@ ||!!''""''):(<=ad#""((*;)=>ad#""''):(<=""((*;)=>""((*;)=>""((*;)=>	  ( 
 	
r'   c                     |S r^   r   )r#   labelsr`   rV   s       r&   transform_labelszRandomShear.transform_labels   s    r'   c                     | j                   j                  j                  |dd      \  }}}}}}	}
}|
|z  ||z  z   dz   }||z  ||z  z   |z   |z  }||z  ||z  z   |	z   |z  }||fS )N   rD   r   )rJ   rP   split)r#   xyrc   a0a1a2b0b1b2c0c1kx_transformedy_transformeds                  r&   get_transformed_x_yzRandomShear.get_transformed_x_y   s    )-););)A)Aqr *B *
&BBBB FR!VOaa"q&2-2a"q&2-2m++r'   c                 B   |d   }| j                   j                  j                  |dd      \  }}}}| j                   j                  ||j                        }| j                   j                  ||j                        }t        |j                        dk(  rL| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  ||z
  ||z
  ||z
  ||z
  gd      |d<   |S )Nboxes   rx   rD   rF   r?   )	rJ   rP   ry   convert_to_tensorrC   r.   rB   rd   rT   )	r#   bounding_boxesw_shift_factorh_shift_factorbboxesx1x2x3x4s	            r&   get_shifted_bboxzRandomShear.get_shifted_bbox   s   (++11&!"1EBB77"(( 8 
 77"(( 8 
 v||!!\\//;;NBON!\\//;;NBON"&,,"4"4"@"@^#^#^#^#	  #A #
w r'   c                      fd}|rt        j                         r j                  j                  d        ||      \  }}t	        | j
                  d|| j                        } j                  ||      }t        |||d      }t	        |d j
                  || j                        } j                  j                          |S )Nc                 \    j                   dk(  rd}d}nd}d}| d   |   | d   |   }}||fS )Nchannels_firstrx   rH   )r   )r`   height_axis
width_axisinput_heightinput_widthr#   s        r&   _get_height_widthz?RandomShear.transform_bounding_boxes.<locals>._get_height_width  sT    #33 
 
}-k:}-j9 &L  ,,r'   
tensorflowrel_xyxy)sourcetargetheightwidthrC   )r   r   r   bounding_box_format)
r   in_tf_graphrJ   set_backendr   r   rO   _shear_bboxesr   reset)r#   r   r`   rV   r   r   r   s   `      r&   transform_bounding_boxesz$RandomShear.transform_bounding_boxes  s    	- ((*((6(9.(I%L++//!#!((N "//ON/-#!$.	N ,!//#!((N LL r'   c           	         | j                   j                  |d   | j                        }| j                   j                  j	                  |dd      \  }}| j                   j                  j	                  |d   dd      \  }}}}	| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  |	d      }	|t|||z  z
  }
|||	z  z
  }| j                   j                  j                  |dk  |
|      }|||z  z
  }|||	z  z
  }| j                   j                  j                  |dk  ||      }|t|||z  z
  }|||z  z
  }| j                   j                  j                  |dkD  ||      }|	||z  z
  }|	||z  z
  }| j                   j                  j                  |dkD  ||      }	| j                   j                  j                  | j                   j                  j                  |d      | j                   j                  j                  |d      | j                   j                  j                  |d      | j                   j                  j                  |	d      gd      }||d<   |S )	NrG   rF   r)   rx   rD   r   r   r   )	rJ   rS   rO   rP   ry   rh   rQ   rT   rd   )r#   r   r`   rG   shear_x_amountshear_y_amountr   y1r   y2x1_top	x1_bottomx2_top	x2_bottomy1_lefty1_righty2_lefty2_rightr   s                      r&   r   zRandomShear._shear_bboxesM  s   ||((>*$2D2D ) 
 *.););)A)A!" *B *
& ++117#QR 2 
BB \\'''4\\'''4\\'''4\\'''4%>B./Fnr12I##)).1*<fiPB>B./Fnr12I##)).1*<iPB%NR/0G^b01H##)).1*<hPBNR/0G^b01H##)).1*<gxPB""..""..r.;""..r.;""..r.;""..r.;	  / 
 #(wr'   c                 *    | j                  |||      S )N)rV   )ra   )r#   segmentation_masksr`   rV   s       r&   transform_segmentation_masksz(RandomShear.transform_segmentation_masks|  s#     $$ % 
 	
r'   c                     t         |          }| j                  | j                  | j                  | j
                  | j                  | j                  | j                  d}i ||S )N)r   r   r   r   r    r   r   )	r   
get_configr   r   r   r   r    r   r   )r#   base_configconfigr%   s      r&   r   zRandomShear.get_config  s^    g(*!//II//++
 )+(((r'   c                     |S r^   r   )r#   rH   s     r&   compute_output_shapez RandomShear.compute_output_shape  s    r'   )r;   r;   r   r   r;   NN)TN)T)__name__
__module____qualname____doc___USE_BASE_FACTOR_FACTOR_BOUNDSr0   r   r   r   r   r1   r\   ra   r_   rg   ru   r   r   r   r   r   r   r   __classcell__)r%   s   @r&   r
   r
      s    ,\ N	"  F6  "B*4Kl.
,,< 	6p-` <@
)r'   r
   N)keras.src.api_exportr   Qkeras.src.layers.preprocessing.image_preprocessing.base_image_preprocessing_layerr   Lkeras.src.layers.preprocessing.image_preprocessing.bounding_boxes.convertersr   r   keras.src.random.seed_generatorr   keras.src.utilsr   r
   r   r'   r&   <module>r      sD    - : ) ()A- A *Ar'   