File size: 5,848 Bytes
747451d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# /*---------------------------------------------------------------------------------------------
#  * Copyright (c) 2022-2023 STMicroelectronics.
#  * All rights reserved.
#  *
#  * This software is licensed under terms that can be found in the LICENSE file in
#  * the root directory of this software component.
#  * If no LICENSE file comes with this software, it is provided AS-IS.
#  *--------------------------------------------------------------------------------------------*/
import numpy as np
import tensorflow as tf


def _apply_rescaling(dataset: tf.data.Dataset = None, 
                      scale: float = None, 
                      offset: float = None) -> tf.data.Dataset:
    """
    Applies rescaling to a dataset using a tf.keras.Sequential model.

    Args:
        dataset (tf.data.Dataset): The dataset to be rescaled.
        scale (float): The scaling factor.
        offset (float): The offset factor.

    Returns:
        The rescaled dataset.
    """
    # Define the rescaling model
    rescaling = tf.keras.Sequential([
        tf.keras.layers.Rescaling(scale, offset)
    ])

    # Apply the rescaling to the dataset
    rescaled_dataset = dataset.map(lambda x, y: (rescaling(x), y))

    return rescaled_dataset


def _apply_normalization(dataset: tf.data.Dataset = None, 
                          mean: tuple[float] = None, 
                          std: tuple[float] = None) -> tf.data.Dataset:
    """
    Applies normalization to a dataset using a tf.keras.Sequential model.

    Args:
        dataset (tf.data.Dataset): The dataset to be rescaled.
        mean (float): The mean of the three channels.
        std (float): The variance of the three channels.

    Returns:
        The rescaled dataset.
    """
    # Define the rescaling model
    if isinstance(std, float):
        variance = pow(std, 2)
    elif isinstance(std, list):
        variance = [x ** 2 for x in std]
    else:
        variance = [x ** 2 for x in std]
    normalization = tf.keras.Sequential([
        tf.keras.layers.Normalization(mean=mean, variance=variance)
    ])

    # Apply the rescaling to the dataset
    normalized_dataset = dataset.map(lambda x, y: (normalization(x), y))

    return normalized_dataset


def apply_rescaling_on_image(image: tf.Tensor = None, 
                             scale: float = None, 
                             offset: float = None) -> tf.Tensor:
    """
    Applies rescaling to an image using a tf.keras.Sequential model.

    Args:
        image (tf.Tensor): The image to be rescaled.
        scale (float): The scaling factor.
        offset (float): The offset factor.

    Returns:
        The rescaled image.
    """
    # Define the rescaling model
    rescaling = tf.keras.Sequential([
        tf.keras.layers.Rescaling(scale, offset)
    ])

    # Apply the rescaling to the image
    rescaled_image = rescaling(image)

    return rescaled_image


def preprocessing(dataset: tf.data.Dataset = None, 
                  scale: float = None, 
                  offset: float = None,
                  mean: tuple[float] = None, 
                  std: tuple[float] = None) -> tf.data.Dataset:
    """
    Applies a full preprocessing to an image using a tf.keras.Sequential model.

    Args:
        image (tf.Tensor): The image to be rescaled.
        scale (float): The scaling factor.
        offset (float): The offset factor.
        mean (float): The mean of the three channels.
        variance (float): The variance of the three channels.

    Returns:
        The rescaled and normalized image.
    """

    if dataset != None:
        dataset = _apply_rescaling(dataset=dataset, 
                                    scale=scale,
                                    offset=offset)
    
        dataset = _apply_normalization(dataset=dataset, 
                                        mean=mean,
                                        std=std)
   
    return dataset
   
   
def preprocess_input(image: np.ndarray, input_details: dict) -> tf.Tensor:
    """
    Preprocesses an input image according to input details.

    Args:
        image: Input image as a NumPy array.
        input_details: Dictionary containing input details, including quantization and dtype.

    Returns:
        Preprocessed image as a TensorFlow tensor.

    """

    image = tf.image.resize(image, (input_details['shape'][1], input_details['shape'][2]))
    # Get the dimensions
    if input_details['dtype'] in [np.uint8, np.int8]:
        image_processed = (image / input_details['quantization'][0]) + input_details['quantization'][1]
        image_processed = np.clip(np.round(image_processed), np.iinfo(input_details['dtype']).min,
                                  np.iinfo(input_details['dtype']).max)
    else:
        image_processed = image
    image_processed = tf.cast(image_processed, dtype=input_details['dtype'])
    image_processed = tf.expand_dims(image_processed, 0)
    return image_processed


def postprocess_output(output: np.ndarray, output_details: dict) -> np.ndarray:
    """
    Postprocesses the model output to obtain the predicted label.

    Args:
        output (np.ndarray): The output tensor from the model.
        output_details: Dictionary containing output details, including quantization and dtype.

    Returns:
        np.ndarray: The predicted label.
    """
    if output_details['dtype'] in [np.uint8, np.int8]:
        # Convert the output data to float32 data type and perform the inverse quantization operation
        output_flp = (np.float32(output) - output_details['quantization'][1]) * output_details['quantization'][0]
    else:
        output_flp = output

    if output.shape[1] > 1:
        predicted_label = np.argmax(output_flp, axis=1)
    else:
        predicted_label = np.where(output_flp < 0.5, 0, 1)

    return predicted_label