o
    MeA  ã                   @   sÖ   d 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	 ddl
mZ dadZdZd	Zd
ZdZdZdZdZedƒd#dd„ƒZejeded�e_ edƒd$dd„ƒZdd„ Zdd„ Z	d%dd„Zdd „ Zd!d"„ ZdS )&z@Utilities for ImageNet data preprocessing & prediction decoding.é    N)Úactivations)Úbackend)Ú
data_utils)Úkeras_exportzUhttps://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.jsonat  
  Preprocesses a tensor or Numpy array encoding a batch of images.

  Usage example with `applications.MobileNet`:

  ```python
  i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
  x = tf.cast(i, tf.float32)
  x = tf.keras.applications.mobilenet.preprocess_input(x)
  core = tf.keras.applications.MobileNet()
  x = core(x)
  model = tf.keras.Model(inputs=[i], outputs=[x])

  image = tf.image.decode_png(tf.io.read_file('file.png'))
  result = model(image)
  ```

  Args:
    x: A floating point `numpy.array` or a `tf.Tensor`, 3D or 4D with 3 color
      channels, with values in the range [0, 255].
      The preprocessed data are written over the input data
      if the data types are compatible. To avoid this
      behaviour, `numpy.copy(x)` can be used.
    data_format: Optional data format of the image tensor/array. Defaults to
      None, in which case the global setting
      `tf.keras.backend.image_data_format()` is used (unless you changed it,
      it defaults to "channels_last").{mode}

  Returns:
      Preprocessed `numpy.array` or a `tf.Tensor` with type `float32`.
      {ret}

  Raises:
      {error}
  aÐ  
    mode: One of "caffe", "tf" or "torch". Defaults to "caffe".
      - caffe: will convert the images from RGB to BGR,
          then will zero-center each color channel with
          respect to the ImageNet dataset,
          without scaling.
      - tf: will scale pixels between -1 and 1,
          sample-wise.
      - torch: will scale pixels between 0 and 1 and then
          will normalize each channel with respect to the
          ImageNet dataset.
  zE
    ValueError: In case of unknown `mode` or `data_format` argument.z;
    ValueError: In case of unknown `data_format` argument.zH
      The inputs pixel values are scaled between -1 and 1, sample-wise.z„
      The input pixels values are scaled between 0 and 1 and each channel is
      normalized with respect to the ImageNet dataset.z–
      The images are converted from RGB to BGR, then each color channel is
      zero-centered with respect to the ImageNet dataset, without scaling.z2keras.applications.imagenet_utils.preprocess_inputÚcaffec                 C   sf   |dvrt d|› �ƒ‚|du rt ¡ }n|dvrt d|› �ƒ‚t| tjƒr,t| ||d�S t| ||d�S )z@Preprocesses a tensor or Numpy array encoding a batch of images.>   Útorchr   ÚtfzDExpected mode to be one of `caffe`, `tf` or `torch`. Received: mode=N>   Zchannels_lastÚchannels_firstz]Expected data_format to be one of `channels_first` or `channels_last`. Received: data_format=)Údata_formatÚmode)Ú
ValueErrorr   Úimage_data_formatÚ
isinstanceÚnpZndarrayÚ_preprocess_numpy_inputÚ_preprocess_symbolic_input)Úxr
   r   © r   úQD:\Projects\ConvertPro\env\Lib\site-packages\keras/applications/imagenet_utils.pyÚpreprocess_inputg   s"   ÿÿ
ÿÿr   Ú )r   ÚretÚerrorz4keras.applications.imagenet_utils.decode_predictionsé   c                    sÖ   t | jƒdks| jd dkrtdt| jƒ ƒ‚tdu r=tjdtddd	�}t|ƒ�}t	 
|¡aW d  ƒ n1 s8w   Y  g }| D ]'‰ ˆ  ¡ | d… ddd
… }‡ fdd„|D ƒ}|jdd„ dd� | |¡ qA|S )aÂ  Decodes the prediction of an ImageNet model.

    Args:
      preds: Numpy array encoding a batch of predictions.
      top: Integer, how many top-guesses to return. Defaults to 5.

    Returns:
      A list of lists of top class prediction tuples
      `(class_name, class_description, score)`.
      One list of tuples per sample in batch input.

    Raises:
      ValueError: In case of invalid shape of the `pred` array
        (must be 2D).
    é   é   iè  zx`decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: Nzimagenet_class_index.jsonÚmodelsZ c2c37ea517e94d9795004a39431a14cb)Zcache_subdirZ	file_hashéÿÿÿÿc                    s&   g | ]}t tt|ƒ ƒˆ | f ‘qS r   )ÚtupleÚCLASS_INDEXÚstr)Ú.0Úi©Úpredr   r   Ú
<listcomp>«   s   & z&decode_predictions.<locals>.<listcomp>c                 S   s   | d S )Nr   r   )r   r   r   r   Ú<lambda>¬   s    z$decode_predictions.<locals>.<lambda>T)ÚkeyÚreverse)ÚlenÚshaper   r    r   r   Zget_fileÚCLASS_INDEX_PATHÚopenÚjsonÚloadZargsortÚsortÚappend)ÚpredsÚtopZfpathÚfÚresultsZtop_indicesÚresultr   r#   r   Údecode_predictions…   s.   ýÿü
ÿr6   c                 C   s.  t | jjtjƒs| jt ¡ dd�} |dkr| d } | d8 } | S |dkr0| d } g d¢}g d	¢}n/|d
krP| jdkrC| ddd…df } n| dd…ddd…df } n	| dddd…f } g d¢}d}|d
k�rT| jdkrÕ| ddd…dd…f  |d 8  < | ddd…dd…f  |d 8  < | ddd…dd…f  |d 8  < |durÓ| ddd…dd…f  |d   < | ddd…dd…f  |d   < | ddd…dd…f  |d   < | S | dd…ddd…dd…f  |d 8  < | dd…ddd…dd…f  |d 8  < | dd…ddd…dd…f  |d 8  < |du�rR| dd…ddd…dd…f  |d   < | dd…ddd…dd…f  |d   < | dd…ddd…dd…f  |d   < | S | d  |d 8  < | d  |d 8  < | d  |d 8  < |du�r•| d  |d   < | d  |d   < | d  |d   < | S )a•  Preprocesses a Numpy array encoding a batch of images.

    Args:
      x: Input array, 3D or 4D.
      data_format: Data format of the image array.
      mode: One of "caffe", "tf" or "torch".
        - caffe: will convert the images from RGB to BGR,
            then will zero-center each color channel with
            respect to the ImageNet dataset,
            without scaling.
        - tf: will scale pixels between -1 and 1,
            sample-wise.
        - torch: will scale pixels between 0 and 1 and then
            will normalize each channel with respect to the
            ImageNet dataset.

    Returns:
        Preprocessed Numpy array.
    F)Úcopyr   ç     à_@ç      ð?r   ç     ào@©g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?©gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?r	   é   Nr   .©gj¼t“üY@g`åÐ"Û1]@gìQ¸…ë^@r   r   r   ).r   ).r   ).r   )	Ú
issubclassÚdtypeÚtyper   ZfloatingZastyper   ZfloatxÚndim)r   r
   r   ÚmeanÚstdr   r   r   r   ±   sV   



""""""(ñ((
(((	ù
r   c                 C   s6  |dkr| d } | d8 } | S |dkr| d } g d¢}g d¢}n1|dkrAt  | ¡d	kr4| d
d
d…df } n| d
d
…d
d
d…df } n	| dd
d
d…f } g d¢}d
}t  t |¡ ¡}t  | ¡t  |¡krst j| t  |t  | ¡¡|d�} nt  | ||¡} |d
ur™t jt |¡t  | ¡d�}|dkr•t  |d¡}| | } | S )a�  Preprocesses a tensor encoding a batch of images.

    Args:
      x: Input tensor, 3D or 4D.
      data_format: Data format of the image tensor.
      mode: One of "caffe", "tf" or "torch".
        - caffe: will convert the images from RGB to BGR,
            then will zero-center each color channel with
            respect to the ImageNet dataset,
            without scaling.
        - tf: will scale pixels between -1 and 1,
            sample-wise.
        - torch: will scale pixels between 0 and 1 and then
            will normalize each channel with respect to the
            ImageNet dataset.

    Returns:
        Preprocessed tensor.
    r   r8   r9   r   r:   r;   r<   r	   r=   Nr   .r>   )r
   )r@   )r   r   r   )	r   rB   Zconstantr   Úarrayr@   Zbias_addÚcastZreshape)r   r
   r   rC   rD   Zmean_tensorZ
std_tensorr   r   r   r   ú   s:   
ýr   c                 C   sT  |dkrJ| rJt | ƒdkrJ|dkr-| d dvr%tjdt| d ƒ d dd	� | d ||f}n,| d
 dvrBtjdt| d
 ƒ d dd	� ||| d
 f}n|dkrTd||f}n||df}|dkrs|rs| durq| |krqtd|› d| › �ƒ‚|S | �r	|dkrÀ| dur¿t | ƒdkrˆtdƒ‚| d dkrš|dkrštd| › d�ƒ‚| d dur¦| d |k s²| d dur¿| d |k r¿td|› d|› d| › �ƒ‚nY| du�rt | ƒdkrÏtdƒ‚| d
 dkrá|dkrátd| › d�ƒ‚| d durí| d |k sû| d du�r| d |k �rtd|› d|› d| › �ƒ‚n|�r|} n
|dk�rd} nd} |�r(d| v �r(td| › �ƒ‚| S )a  Internal utility to compute/validate a model's input shape.

    Args:
      input_shape: Either None (will return the default network input shape),
        or a user-provided shape to be validated.
      default_size: Default input width/height for the model.
      min_size: Minimum input width/height accepted by the model.
      data_format: Image data format to use.
      require_flatten: Whether the model is expected to
        be linked to a classifier via a Flatten layer.
      weights: One of `None` (random initialization)
        or 'imagenet' (pre-training on ImageNet).
        If weights='imagenet' input channels must be equal to 3.

    Returns:
      An integer shape tuple (may include None entries).

    Raises:
      ValueError: In case of invalid argument values.
    Zimagenetr=   r	   r   >   r   r=   z]This model usually expects 1 or 3 input channels. However, it was passed an input_shape with z input channels.r   )Ú
stacklevelr   NzXWhen setting `include_top=True` and loading `imagenet` weights, `input_shape` should be z.  Received: input_shape=z0`input_shape` must be a tuple of three integers.z6The input must have 3 channels; Received `input_shape=ú`r   zInput size must be at least r   z; Received: input_shape=)r=   NN)NNr=   z[If `include_top` is True, you should specify a static `input_shape`. Received: input_shape=)r)   ÚwarningsÚwarnr    r   )Zinput_shapeZdefault_sizeZmin_sizer
   Zrequire_flattenÚweightsZdefault_shaper   r   r   Úobtain_input_shape6  s¾   
þýû
þýû
þýÿÿÿÿÿþÿ€
ÿÿÿÿÿþÿ€

þÿrL   c                 C   s¶   t  ¡ dkrdnd}t  | ¡||d … }t|tƒr||f}|d du r'd}nd|d d  d|d d  f}|d d |d d f}|d |d  |d f|d |d  |d ffS )zÊReturns a tuple for zero-padding for 2D convolution with downsampling.

    Args:
      inputs: Input tensor.
      kernel_size: An integer or tuple/list of 2 integers.

    Returns:
      A tuple.
    r	   r   r   r   N)r   r   )r   r   Z	int_shaper   Úint)ZinputsZkernel_sizeZimg_dimZ
input_sizeÚadjustZcorrectr   r   r   Úcorrect_pad¯  s   

 þrO   c                 C   s@   |du rdS t  | ¡} | t  d¡t  d¡hvrtd| › �ƒ‚dS )a@  validates that the classifer_activation is compatible with the weights.

    Args:
      classifier_activation: str or callable activation function
      weights: The pretrained weights to load.

    Raises:
      ValueError: if an activation other than `None` or `softmax` are used with
        pretrained weights.
    NZsoftmaxz³Only `None` and `softmax` activations are allowed for the `classifier_activation` argument when using pretrained weights, with `include_top=True`; Received: classifier_activation=)r   Úgetr   )Zclassifier_activationrK   r   r   r   Úvalidate_activationÈ  s   
þýÿürQ   )Nr   )r   )N)Ú__doc__r-   rI   Únumpyr   Zkerasr   r   Zkeras.utilsr   Z tensorflow.python.util.tf_exportr   r   r+   ZPREPROCESS_INPUT_DOCZPREPROCESS_INPUT_MODE_DOCZ"PREPROCESS_INPUT_DEFAULT_ERROR_DOCZPREPROCESS_INPUT_ERROR_DOCZPREPROCESS_INPUT_RET_DOC_TFZPREPROCESS_INPUT_RET_DOC_TORCHZPREPROCESS_INPUT_RET_DOC_CAFFEr   Úformatr6   r   r   rL   rO   rQ   r   r   r   r   Ú<module>   sB   ÿ$ý+IB
úy