
    2VhM@                         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
 d dlmZ  ed       G d	 d
e             Zy)    )backend)keras_export)BaseImagePreprocessingLayer)clip_to_image_size)convert_format)SeedGenerator)backend_utilszkeras.layers.RandomZoomc                        e 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dZddZd Zd Zd Z fdZ xZS )
RandomZooma  A preprocessing layer which randomly zooms images during training.

    This layer will randomly zoom in or out on each axis of an image
    independently, filling empty space according to `fill_mode`.

    Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
    of integer or floating point dtype.
    By default, the layer will output floats.

    Input shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., height, width, channels)`, in `"channels_last"` format,
        or `(..., channels, height, width)`, in `"channels_first"` format.

    Output shape:
        3D (unbatched) or 4D (batched) tensor with shape:
        `(..., target_height, target_width, channels)`,
        or `(..., channels, target_height, target_width)`,
        in `"channels_first"` format.

    **Note:** This layer is safe to use inside a `tf.data` pipeline
    (independently of which backend you're using).

    Args:
        height_factor: a float represented as fraction of value, or a tuple of
            size 2 representing lower and upper bound for zooming vertically.
            When represented as a single float, this value is used for both the
            upper and lower bound. A positive value means zooming out, while a
            negative value means zooming in. For instance,
            `height_factor=(0.2, 0.3)` result in an output zoomed out by a
            random amount in the range `[+20%, +30%]`.
            `height_factor=(-0.3, -0.2)` result in an output zoomed in by a
            random amount in the range `[+20%, +30%]`.
        width_factor: a float represented as fraction of value, or a tuple of
            size 2 representing lower and upper bound for zooming horizontally.
            When represented as a single float, this value is used for both the
            upper and lower bound. For instance, `width_factor=(0.2, 0.3)`
            result in an output zooming out between 20% to 30%.
            `width_factor=(-0.3, -0.2)` result in an output zooming in between
            20% to 30%. `None` means i.e., zooming vertical and horizontal
            directions by preserving the aspect ratio. Defaults to `None`.
        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 `"reflect"`.
            - `"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"`.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        seed: Integer. Used to create a random seed.
        fill_value: a float that represents the value to be filled outside
            the boundaries when `fill_mode="constant"`.
        data_format: string, either `"channels_last"` or `"channels_first"`.
            The ordering of the dimensions in the inputs. `"channels_last"`
            corresponds to inputs with shape `(batch, height, width, channels)`
            while `"channels_first"` corresponds to inputs with shape
            `(batch, channels, height, width)`. It defaults to the
            `image_data_format` value found in your Keras config file at
            `~/.keras/keras.json`. If you never set it, then it will be
            `"channels_last"`.
        **kwargs: Base layer keyword arguments, such as `name` and `dtype`.

    Example:

    >>> input_img = np.random.random((32, 224, 224, 3))
    >>> layer = keras.layers.RandomZoom(.5, .2)
    >>> out_img = layer(input_img)
    FzyThe `height_factor` and `width_factor` arguments should be a number (or a list of two numbers) in the range [-1.0, 1.0]. )reflectwrapconstantnearest)r   bilinearc                    t        	|   di | || _        | j                  |d      \  | _        | _        || _        || j                  |d      \  | _        | _        || j                  vrt        d| d| j                   d      || j                  vrt        d| d| j                   d      || _        || _        || _        || _        t!        |      | _        t%        j&                  |      | _        d| _        y )	Nheight_factorwidth_factorzUnknown `fill_mode` z. Expected of one .zUnknown `interpolation` F )super__init__r   _set_factorheight_lowerheight_upperr   width_lowerwidth_upper_SUPPORTED_FILL_MODENotImplementedError_SUPPORTED_INTERPOLATION	fill_mode
fill_valueinterpolationseedr   	generatorr   standardize_data_formatdata_formatsupports_jit)
selfr   r   r    r"   r#   r!   r&   kwargs	__class__s
            n/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/preprocessing/image_preprocessing/random_zoom.pyr   zRandomZoom.__init__l   s'    	"6"*/3/?/??0
,4, )#151A1An2.Dd. D555%&yk1C,,-Q0   = ==%*=/9K0014 
 #$*	&t,"::;G!    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      )
isinstancetuplelistlen
ValueError_FACTOR_VALIDATION_ERROR_check_factor_rangesortedintfloatabs)r(   factorfactor_nameloweruppers        r+   r   zRandomZoom._set_factor   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 )N      ?g      zReceived: input_number=)r5   r6   )r(   input_numbers     r+   r7   zRandomZoom._check_factor_range   s;    #!4--+L>:;  "5r,   c                 z    | j                   j                  || j                        }|r| j                  ||      S |S N)r   castcompute_dtype_zoom_inputs)r(   imagestransformationtrainings       r+   transform_imageszRandomZoom.transform_images   s9    ""64+=+=>$$V^<<r,   c                     |S rD   r   )r(   labelsrI   rJ   s       r+   transform_labelszRandomZoom.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   axisr0   )r   numpysplit)r(   xy	transforma0a1a2b0b1b2c0c1kx_transformedy_transformeds                  r+   get_transformed_x_yzRandomZoom.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                 v   |d   }| j                   j                  j                  |dd      \  }}}	}
t        |j                        dk(  r| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  |d      }| j                   j                  j                  |||      |z
  }| j                   j                  j                  |||      |z
  }| j                   j                  j                  |	||      |z
  }	| j                   j                  j                  |
||      |z
  }
| j                   j                  j                  |||	|
gd      |d<   |S )Nboxes   rQ   rR      )r   rT   rU   r4   shapeexpand_dimsclipconcatenate)r(   bounding_boxesh_endh_startw_endw_startbboxesx1y1x2y2s              r+   get_clipped_bboxzRandomZoom.get_clipped_bbox   s}   (++11&!"1EBBv||!LL&&225"=Ell((44WbAGLL&&225"=Ell((44WbAG\\$$R%87B\\$$R%87B\\$$R%87B\\$$R%87B"&,,"4"4"@"@R2 #A #
w r,   c                    |rt        j                         r| j                  j                  d       |d   }|d   }|d   }| j                  dk(  r|d   }|d   }n
|d   }|d   }t        || j                  d	||
      }| j                  j                  | j                  j                  j                  ||gd      d      }	| j                  |	||      }
| j                  dd|
      \  }}| j                  |||
      \  }}| j                  |||||      }||z
  }||z
  }| j                  j                  j                  |d      }| j                  j                  j                  |d      }t        |d	d||
      }t        |||d      }t        |d| j                  ||
      }| j                  j                          |S )N
tensorflow
width_zoomheight_zoominput_shapechannels_firstrQ   xyxy)sourcetargetheightwidthr0   rR   float32dtyper   rel_xyxy)rm   r   r   bounding_box_format)r	   in_tf_graphr   set_backendr&   r   r   rE   rT   rl   _get_zoom_matrixrd   rw   rj   r   reset)r(   rm   rI   rJ   rz   r{   inputs_shaper   r   zoomsrX   rq   ro   rp   rn   height_transformedwidth_transformeds                    r+   transform_bounding_boxesz#RandomZoom.transform_bounding_boxes   s    ((*((6'5J(7K)-8L#33%b)$R(%b)$R(+//N LL%%""..-A /   	 & E --eVUCI#77 GW  33LE5 "22wwN "' %!%!3!3!?!?"B" !% 2 2 > >!2! ,!)'N 0-)'$.	N ,!//N LL r,   c                 *    | j                  |||      S )N)rJ   )rK   )r(   segmentation_masksrI   rJ   s       r+   transform_segmentation_masksz'RandomZoom.transform_segmentation_masks0  s#     $$ % 
 	
r,   c                    |sy t        |t              r|d   }n|}| j                  j                  |      }t	        |      dk(  r|d   df}nd}|sK| j                  j
                  j                  |      | j                  j
                  j                  |      dS |%| j                  | j                  j                        }| j                  j                  j                  d| j                  z   d| j                  z   ||      }| j                  D| j                  j                  j                  d| j                  z   d| j                  z   ||      }n|}|||d	S )
NrH   rg   r   r0   )r0   r0   )r{   rz   rA   )minvalmaxvalri   r#   )r{   rz   r|   )r1   dictr   ri   r4   rT   zeros_get_seed_generator_backendrandomuniformr   r   r   r   r   )	r(   datarJ   r#   rH   images_shapezoom_factor_shaper{   rz   s	            r+   get_random_transformationz$RandomZoom.get_random_transformation7  s`   dD!(^FF||))&1|!!-a! 4 &#||11778IJ"ll00667HI  <++DLL,A,ABDll))11******#	 2 
 (,,44T---T---'	 5 J %J&$'
 	
r,   c                    ||S |d   }|d   }| j                   j                  | j                   j                  j                  ||gd      d      }| j                   j	                  |      }t        |      dk(  }|rB| j                   j                  j                  |d      }| j                   j	                  |      }| j                  d	k(  r|d
   }|d   }	n
|d   }|d
   }	| j                   j                  j                  || j                  |||	      | j                  | j                  | j                  | j                        }
|r'| j                   j                  j                  |
d      }
|
S )Nrz   r{   r0   rR   r   r   rh   r   r}   r~   rQ   r   )rX   r"   r    r!   r&   )r   rE   rT   rl   ri   r4   rj   r&   imageaffine_transformr   r"   r    r!   squeeze)r(   inputsrI   rz   r{   r   r   	unbatchedr   r   outputss              r+   rG   zRandomZoom._zoom_inputsa  sn   !M#L1
$]3!!LL**J+D1*M " 

 ||))&1%*	\\''33F3CF<<--f5L//!"%F $E!"%F $E,,$$55++E65A,,nn(( 6 
 ll((00q0AGr,   c                 `   | j                   j                  |      d   }| j                   j                  |d      dz
  dz  d|d d ddf   z
  z  }| j                   j                  |d      dz
  dz  d|d d dd f   z
  z  }| j                   j                  j	                  |d d ddf   | j                   j                  j                  |df      || j                   j                  j                  |df      |d d dd f   || j                   j                  j                  |df      gd      S )Nr   r   rA   g       @r0   r.   rR   )r   ri   rE   rT   rl   r   )r(   r   image_heightimage_width	num_zoomsx_offsety_offsets          r+   r   zRandomZoom._get_zoom_matrix  s3   LL&&u-a0	 \\&&{I>DK%1Q3-
 \\|Y7#=D5AB<! ||!!--a1f""(()Q8""(()Q8ae""(()Q8  . 
 	
r,   c                     |S rD   r   )r(   r|   s     r+   compute_output_shapezRandomZoom.compute_output_shape  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RandomZoom.get_config  sb    g(*!// --!//II//++
 )+(((r,   )Nr   r   Ng        N)T)TN)__name__
__module____qualname____doc___USE_BASE_FACTORr6   r   r   r   r   r7   rK   rN   rd   rw   r   r   r   rG   r   r   r   __classcell__)r*   s   @r+   r   r      s    Ob 	% 
 F6
  &"P*,. 	Xv <@
(
T"H
6) )r,   r   N)	keras.srcr   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      sG     - : ) '(]), ]) )])r,   