
    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.RandomPerspectivec                        e Zd ZdZdZdZdZ	 	 	 	 	 	 d fd	ZddZddZ	d Z
	 dd	Zd
 ZddZ	 ddZd Z fdZ xZS )RandomPerspectiveab  A preprocessing layer that applies random perspective transformations.

    This layer distorts the perspective of input images by shifting their
    corner points, simulating a 3D-like transformation. The amount of distortion
    is controlled by the `factor` and `scale` parameters.

    Args:
        factor: A float or a tuple of two floats.
            Represents the probability of applying the perspective
            transformation to each image in the batch.
            - `factor=0.0` ensures no transformation is applied.
            - `factor=1.0` means the transformation is always applied.
            - If a tuple `(min, max)` is provided, a probability is randomly
              sampled between `min` and `max` for each image.
            - If a single float is given, the probability is sampled between
              `0.0` and the provided float.
            Default is 1.0.
        scale: A float defining the relative amount of perspective shift.
            Determines how much the image corners are displaced, affecting
            the intensity of the perspective effect.
        interpolation: Interpolation mode. Supported values: `"nearest"`,
            `"bilinear"`.
        fill_value: a float represents the value to be filled outside the
            boundaries when `fill_mode="constant"`.
        seed: Integer. Used to create a random seed.

    F)r      )nearestbilinearc                    t        |   dd|i| | j                  |       || _        || _        || _        || _        t        |      | _        d| _	        |dk  s|dkD  rt        d|       || j                  vrt        d| d| j                   d      | j                  d	k(  rd
| _        d| _        d| _        y d| _        d
| _        d| _        y )Ndata_formatF              ?zLThe `scale` argument should be a number in the range [0,1]. Received: scale=zUnknown `interpolation` z. Expected of one .channels_first )super__init___set_factorscale
fill_valueinterpolationseedr   	generatorsupports_jit
ValueError_SUPPORTED_INTERPOLATIONNotImplementedErrorr   height_axis
width_axischannel_axis)	selffactorr   r   r   r   r   kwargs	__class__s	           u/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/preprocessing/image_preprocessing/random_perspective.pyr   zRandomPerspective.__init__1   s     	;[;F; 
$*	&t,!3;%#+# $)'+   = ==%*=/9K0014 
 //!D DO "D!D DO "D    c                    |sy t        |t              r|d   }n|}| j                  j                  |      }t	        |      dk(  }|rd}n|d   }|j                  | j
                     |j                  | j                     }	}|xs% | j                  | j                  j                        }| j                  j                  j                  |f| j                  d   | j                  d   |      }
| j                  j                  j                  |fdd|      }||
k  }| j                  j                  j                  |dd	fd
| j                  z  d| j                  z  || j                        }| j                  j                  ddg|	dz
  dgd|dz
  g|	dz
  |dz
  ggg| j                        }| j                  j                  j!                  ||d      }|||z  z   }||||dS )Nimages   r   r   )shapeminvalmaxvalr   r   r         g      g      ?)r0   r1   r2   r   dtyper5   axis)apply_perspectivestart_points
end_pointsinput_shape)
isinstancedictbackendr0   lenr$   r%   _get_seed_generator_backendrandomuniformr(   r   compute_dtypeconvert_to_tensornumpyrepeat)r'   datatrainingr   r.   images_shape	unbatched
batch_sizeheightwidthtransformation_probabilityrandom_thresholdr9   perspective_factorr:   r;   s                   r+   get_random_transformationz+RandomPerspective.get_random_transformation[   s   dD!(^FF||))&1%*	J%aJLL))*LL) 
 Ft//0E0EF%)\\%8%8%@%@-;;q>;;q>	 &A &
"  <<..66-	 7 
 -/II!\\0088q!$$**$#$$ 9 
 ||55 #JQY$&1*%QY
+	 $$ 6 

 ||))00*1 1 
 "L3E$EE
 "3($'	
 	
r,   c                     | j                   j                  || j                        }|r:|8| j                  ||      }| j                   j                  || j                        }|S N)r?   castrE   _perspective_inputs)r'   r.   transformationrJ   s       r+   transform_imagesz"RandomPerspective.transform_images   sY    ""64+=+=>2--fnEF\\&&vt/A/ABFr,   c                    ||S | j                   j                  |      }t        |      dk(  }|r'| j                   j                  j	                  |d      }|d   }|d   }| j                   j
                  j                  |||| j                  | j                  | j                        }|d   }| j                   j                  j                  |d d d d d f   ||      }|r'| j                   j                  j                  |d      }|S )Nr/   r   r7   r:   r;   )r   r   r   r9   )r?   r0   r@   rG   expand_dimsimageperspective_transformr   r   r   wheresqueeze)	r'   inputsrX   inputs_shaperL   r:   r;   outputsr9   s	            r+   rW   z%RandomPerspective._perspective_inputs   s   !M||))&1%*	\\''33F3CF%n5#L1
,,$$::,,(( ; 
 ++>?,,$$**atT12
 ll((00q0AGr,   c           	      V   |r|t        j                         r| j                  j                  d       |d   | j                     |d   | j
                     }}t        || j                  d||      }|d   }| j                  j                  j                  |dd      \  }}}	}
|d	   }|d
   }| j                  j                  j                  ||      }| j                  j                  j                  |d      }| j                  j                  || j                        }||f|	|
f||
f|	|ffD cg c]  \  }}| j                  |||       }}}t!        | \  }}| j                  j                  j#                  |d      }| j                  j                  j#                  |d      }| j                  j                  j%                  |d      | j                  j                  j'                  |d      }}| j                  j                  j%                  |d      | j                  j                  j'                  |d      }}| j                  j                  j                  |d      }| j                  j                  j                  |d      }| j                  j                  j                  |d      }| j                  j                  j                  |d      }| j                  j                  j)                  ||||gd      }| j                  j*                  j-                  |d   |j.                        }| j                  j                  j1                  |d d d d f   ||d         |d<   t3        |||d      }| j                  j5                          |S c c}}w )N
tensorflowr<   xyxy)sourcetargetrN   rO   boxesr3   r   r7   r:   r;   r   r6   r9   )bounding_boxesrN   rO   bounding_box_format)r   in_tf_graphr?   set_backendr$   r%   r   rj   rG   splitr\   compute_homography_matrixr[   rV   rE   _get_transformed_coordinateszipstackminmaxconcatenatecorerF   r5   r^   r   reset)r'   ri   rX   rJ   input_heightinput_widthrh   x0y0x1y1r:   r;   	transformxycorners	x_corners	y_cornersxsysmin_xmax_xmin_ymax_yr9   s                             r+   transform_bounding_boxesz*RandomPerspective.transform_bounding_boxes   s    2((*((6 }-d.>.>?}-doo> &L
 ,//#!N #7+E!\\//55eQR5HNBB).9L'5J**DDjI **66yq6II)))4;M;M)NI !"XBx"bB8DAq 11!Q	BG  $'= Iy##)))")=B##)))")=B ""&&r&3""&&r&3 E
 ""&&r&3""&&r&3 E
 LL&&225r2BELL&&225r2BELL&&225r2BELL&&225r2BELL&&22ue,2 3 E !% 1 1 C C235;; !D ! '+ll&8&8&>&>!!T4-0w''N7# 0-#!$*	N LL ]s   5N%c                    | j                   }|j                  |      d   }|j                  j                  ||j                  j	                  |ddf      gd      }|j                  j                  ||ddf      }|j                  j                  |      }|j                  j                  |      }|j                  j                  |||gd      }	|j                  j                  |	dd      }	|j                  j                  ||	      }
|j                  j                  |
dd      }
|
d   |
d   z  }|
d	   |
d   z  }||fS )
Nr   r   r   r7   r/   r   ).r   ).r4   ).r   )r?   r0   rG   rt   onesreshapelinalginv	ones_likemoveaxismatmul)r'   x_coordsy_coordstransformation_matrixr?   rM   homogeneous_transforminverse_transformones_columnhomogeneous_coordstransformed_coordsx_transformedy_transformeds                r+   ro   z.RandomPerspective._get_transformed_coordinates  sY    ,,]]#89!<
 ' 9 9"GMM$6$6
Aq7I$JK !: !
 !( 5 5!J1#5!
 $NN../DEmm--h7$]]66x-B 7 
 %]]334FBO$]]111
 %]]334FBO*625G5OO*625G5OOm++r,   c                     |S rU   r   )r'   labelsrX   rJ   s       r+   transform_labelsz"RandomPerspective.transform_labels:  s    r,   c                 *    | j                  |||      S )N)rJ   )rY   )r'   segmentation_masksrX   rJ   s       r+   transform_segmentation_masksz.RandomPerspective.transform_segmentation_masks=  s#     $$ % 
 	
r,   c                     |S rU   r   )r'   r<   s     r+   compute_output_shapez&RandomPerspective.compute_output_shapeD  s    r,   c                     t         |          }| j                  | j                  | j                  | j
                  | j                  d}i ||S )N)r(   r   r   r   r   )r   
get_configr(   r   r   r   r   )r'   base_configconfigr*   s      r+   r   zRandomPerspective.get_configG  sN    g(*kkZZ!////II
 )+(((r,   )r   r   r   r   NN)TN)T)__name__
__module____qualname____doc___USE_BASE_FACTOR_FACTOR_BOUNDSr"   r   rS   rY   rW   r   ro   r   r   r   r   __classcell__)r*   s   @r+   r
   r
      sx    8 N6  (#TC
JH 	Pd,B <@
	) 	)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    - : ) ./@)3 @) 0@)r,   