File size: 9,043 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#  /*---------------------------------------------------------------------------------------------
#  * 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 os
import tensorflow as tf
from omegaconf import DictConfig
from tensorflow.keras import layers



def change_yolo_model_number_of_classes(model,num_classes,num_anchors):

    output_shape = (5 + num_classes)*num_anchors

    # If the model already has the correct number of classes -> dont do anything
    for outp in model.outputs:
        if outp.shape[0] == output_shape:
            return model

    l = -1
    l_list = []

    while True:

        layer_type = type(model.layers[l])
        layer_config = model.layers[l].get_config()

        if layer_type in [layers.Conv2D,
                          layers.Conv2DTranspose,
                          layers.Conv1D,
                          layers.Conv1DTranspose,
                          layers.Dense]:
            if layer_type in [layers.Conv2D,layers.Conv2DTranspose,layers.Conv1D,layers.Conv1DTranspose]:
                layer_config['filters'] = output_shape
                new_layer = layer_type(**layer_config)
                outputs = new_layer(model.layers[l-1].output)
            else:
                layer_config['units'] = output_shape
                new_layer = layer_type(**layer_config)
                outputs = new_layer(model.layers[l-1].output)

            for i,new_l in enumerate(l_list[::-1]):
                outputs = new_l(outputs)

            return tf.keras.Model(inputs=model.input, outputs=outputs, name=model.name)

        else:
            l_list.append(layer_type(**layer_config))
            l-=1

    return None


def search_layer(tensor,model,with_his="output"):
    for i,l in enumerate(model.layers): # search which layer has this tensor as output
        if not type(l)==layers.InputLayer:
            if with_his=="output":
                for lo in (l.output if type(l.output)==list else [l.output]):
                    if tensor is lo:
                        return i
            if with_his=="input":
                if tensor in (l.input if type(l.input)==list else [l.input]):
                    return i
    return None

def change_yolo_x_model_number_of_classes(model,num_classes,num_anchors):

    model_outputs = model.outputs

    concatenate_layers_indexes = []
    for o in model_outputs:
        concatenate_layers_indexes.append(search_layer(o,model,'output'))

    output_tensors_list = [] # list of output tensors of the new model

    for c in concatenate_layers_indexes: # for all Yolo_X heads

        # concatenate layer infos
        concatenate_layer_inputs = model.layers[c].input
        concatenate_layer_type   = type(model.layers[c])
        concatenate_layer_config = model.layers[c].get_config()

        new_concatenate_layer_inputs = []

        list_of_shapes = [4*num_anchors,1*num_anchors,num_classes*num_anchors]

        for i,t in enumerate(concatenate_layer_inputs):
            if t.shape[-1] != list_of_shapes[i]:

                conv_layer_index = search_layer(t,model,"output")

                conv_layer_input  = model.layers[conv_layer_index].input
                conv_layer_type   = type(model.layers[conv_layer_index])
                conv_layer_config = model.layers[conv_layer_index].get_config()

                # change the number of filters of the Conv2d layer
                conv_layer_config['filters'] = list_of_shapes[i]

                new_conv_layer = conv_layer_type(**conv_layer_config)
                new_concatenate_layer_inputs.append(new_conv_layer(conv_layer_input))
            else:
                new_concatenate_layer_inputs.append(concatenate_layer_inputs[i])

        new_concatenate_layer = concatenate_layer_type(**concatenate_layer_config)
        output_tensors_list.append(new_concatenate_layer(new_concatenate_layer_inputs))

    return tf.keras.Model(inputs=model.input, outputs=output_tensors_list, name=model.name)

def change_model_input_shape(model,new_inp_shape):
    
    conf = model.get_config()
    conf['layers'][0]['config']['batch_shape'] = new_inp_shape
    new_model = model.__class__.from_config(conf, custom_objects={})

    # iterate over all the layers that we want to get weights from
    weights = [layer.get_weights() for layer in model.layers[1:]]
    for layer, weight in zip(new_model.layers[1:], weights):
        layer.set_weights(weight)

    old_inp_shape = model.get_config()['layers'][0]['config']['batch_shape']

    return new_model, old_inp_shape

def change_yolo_model_number_of_classes(model,num_classes,num_anchors):

    output_shape = (5 + num_classes)*num_anchors

    # If the model already has the correct number of classes -> dont do anything
    for outp in model.outputs:
        if outp.shape[0] == output_shape:
            return model

    l = -1
    l_list = []

    while True:

        layer_type = type(model.layers[l])
        layer_config = model.layers[l].get_config()

        if layer_type in [layers.Conv2D,
                          layers.Conv2DTranspose,
                          layers.Conv1D,
                          layers.Conv1DTranspose,
                          layers.Dense]:
            if layer_type in [layers.Conv2D,layers.Conv2DTranspose,layers.Conv1D,layers.Conv1DTranspose]:
                layer_config['filters'] = output_shape
                new_layer = layer_type(**layer_config)
                outputs = new_layer(model.layers[l-1].output)
            else:
                layer_config['units'] = output_shape
                new_layer = layer_type(**layer_config)
                outputs = new_layer(model.layers[l-1].output)

            for i,new_l in enumerate(l_list[::-1]):
                outputs = new_l(outputs)

            return tf.keras.Model(inputs=model.input, outputs=outputs, name=model.name)

        else:
            l_list.append(layer_type(**layer_config))
            l-=1

    return None


def search_layer(tensor,model,with_his="output"):
    for i,l in enumerate(model.layers): # search which layer has this tensor as output
        if with_his=="output":
            if tensor in (l.output if type(l.output)==list else [l.output]):
                return i
        if with_his=="input":
            if tensor in (l.input if type(l.input)==list else [l.input]):
                return i
    return None

def change_yolo_x_model_number_of_classes(model,num_classes,num_anchors):

    model_outputs = model.outputs

    concatenate_layers_indexes = []
    for o in model_outputs:
        concatenate_layers_indexes.append(search_layer(o,model,'output'))

    output_tensors_list = [] # list of output tensors of the new model

    for c in concatenate_layers_indexes: # for all Yolo_X heads

        # concatenate layer infos
        concatenate_layer_inputs = model.layers[c].input
        concatenate_layer_type   = type(model.layers[c])
        concatenate_layer_config = model.layers[c].get_config()

        new_concatenate_layer_inputs = []

        list_of_shapes = [4*num_anchors,1*num_anchors,num_classes*num_anchors]

        for i,t in enumerate(concatenate_layer_inputs):
            if t.shape[-1] != list_of_shapes[i]:

                conv_layer_index = search_layer(t,model,"output")

                conv_layer_input  = model.layers[conv_layer_index].input
                conv_layer_type   = type(model.layers[conv_layer_index])
                conv_layer_config = model.layers[conv_layer_index].get_config()

                # change the number of filters of the Conv2d layer
                conv_layer_config['filters'] = list_of_shapes[i]

                new_conv_layer = conv_layer_type(**conv_layer_config)
                new_concatenate_layer_inputs.append(new_conv_layer(conv_layer_input))
            else:
                new_concatenate_layer_inputs.append(concatenate_layer_inputs[i])

        new_concatenate_layer = concatenate_layer_type(**concatenate_layer_config)
        output_tensors_list.append(new_concatenate_layer(new_concatenate_layer_inputs))

    return tf.keras.Model(inputs=model.input, outputs=output_tensors_list, name=model.name)


def ai_runner_invoke(image_processed,ai_runner_interpreter):
    def reduce_shape(x):  # reduce shape (request by legacy API)
        old_shape = x.shape
        n_shape = [old_shape[0]]
        for v in x.shape[1:len(x.shape) - 1]:
            if v != 1:
                n_shape.append(v)
        n_shape.append(old_shape[-1])
        return x.reshape(n_shape)

    preds, _ = ai_runner_interpreter.invoke(image_processed)
    predictions = []
    for x in preds:
        x = reduce_shape(x)
        predictions.append(x.copy())
    return predictions