Keras
File size: 5,933 Bytes
883fed0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import traceback
import os

try:
    import numpy as np
except:
    traceback.print_exc(file=open("errlog.txt","a"))

try:
    import tensorflow as tf
except:
    traceback.print_exc(file=open("errlog.txt","a"))

print(tf.keras.__version__)
devices = tf.config.list_physical_devices()
print("\nDevices: ", devices)

gpus = tf.config.list_physical_devices('GPU')
if gpus:
  details = tf.config.experimental.get_device_details(gpus[0])
  print("GPU details: ", details)     

classes = [
    ["airplane", 0.0],
    ["background", 0.0],
    ["building", 128.5],
    ["bush", 0.0],
    ["cable", 0.0],
    ["earth", 255.0],
    ["field", 255.0],
    ["garden", 128.5],
    ["grass", 255.0],
    ["person", 0.0],
    ["sand", 128.5],
    ["ship", 0.0],
    ["stony", 128.5],
    ["street", 255.0],
    ["tracks", 0.0],
    ["train", 0.0],
    ["tree", 0.0],
    ["vehicle", 0.0],
    ["water", 0.0]
]

class ConvBlock(tf.keras.layers.Layer):
    def __init__(self, kernels, kernel_size=(3, 3), strides=(1, 1), padding='same', is_bn=True, is_relu=True, n=1, ps=1, **kwargs):
      super(ConvBlock, self).__init__()
      self.kernels = kernels
      self.kernel_size = kernel_size
      self.strides = strides
      self.padding = padding
      self.is_bn = is_bn
      self.is_relu = is_relu
      self.n = n
      self.conv_layers = []
      if ps > 1:
          self.conv_layers.append(tf.keras.layers.MaxPool2D(pool_size=(ps, ps)))
      for i in range(1, n + 1):
        self.conv_layers.append(tf.keras.layers.Conv2D(filters=kernels, kernel_size=kernel_size,
                                                       padding=padding, strides=strides))
        if is_bn:
          self.conv_layers.append(tf.keras.layers.BatchNormalization())
        if is_relu:
          self.conv_layers.append(tf.keras.layers.ReLU())

    def call(self, inputs):
      x = inputs
      for layer in self.conv_layers:
        x = layer(x)
      return x
      
    def get_config(self):
      config = super().get_config()
      config.update(
            {
                "kernels": self.kernels,
                "kernel_size": self.kernel_size,
                "strides": self.strides,
                "padding": self.padding,
                "is_bn": self.is_bn,
                "is_relu": self.is_relu,
                "n": self.n,
                "conv_layers": self.conv_layers
            }
        )
      return config
    
    def build(self, input_shape):
      self.conv_layers[0].build(input_shape)
      for i in range(1, len(self.conv_layers)):
        self.conv_layers[i].build(self.conv_layers[i - 1].compute_output_shape(input_shape))

    @classmethod
    def from_config(cls, config):
        config["conv_layers"] = []
        kernels = config["kernels"]
        if "ps" not in config:
          config["ps"] = 1
        ps = config["ps"]
        if "kernel_size" not in config:
          config["kernel_size"] = (3, 3)
        kernel_size = config["kernel_size"]
        if "strides" not in config:
          config["strides"] = (1, 1)
        strides = config["strides"]
        if "padding" not in config:
          config["padding"] = "same"
        padding = config["padding"]
        if "is_bn" not in config:
          config["is_bn"] = True
        is_bn = config["is_bn"]
        if "is_relu" not in config:
          config["is_relu"] = True
        is_relu = config["is_relu"]
        if "n" not in config:
          config["n"] = 1
        n = config["n"]
        if ps > 1:
          config["conv_layers"].append(tf.keras.layers.MaxPool2D(pool_size=(ps, ps)))
        for i in range(1, n + 1):
          config["conv_layers"].append(tf.keras.layers.Conv2D(filters=kernels, kernel_size=kernel_size,
																												padding=padding, strides=strides))
          if is_bn:
            config["conv_layers"].append(tf.keras.layers.BatchNormalization())
          if is_relu:
            config["conv_layers"].append(tf.keras.layers.ReLU())
        return cls(**config)

_model = None

def create_scores(pred_mask, imageSize):
    global classes
    pred_mask = tf.math.argmax(pred_mask, axis=-1)
    pred_mask = pred_mask[..., tf.newaxis]
    pred_mask_numpy = pred_mask.numpy()
    mask = pred_mask_numpy[0].reshape(imageSize, imageSize)
    scores = np.ones(mask.shape, dtype=np.float32)
    for i in range(len(classes)):
        scores[mask == i] = float(classes[i][1])
    return scores

# --------------------- C++ interface ---------------------------------------------------------------
def load_model():
    try:
        print("Loading Terrain CNN model...")
        model_path = "/home/andreas/Dokumente/Uni/masterarbeit/landing_spot_finder/pre_labeled_4/py_terrain_VGG16_Unet.keras"
        global _model
        _model = tf.keras.models.load_model(model_path)
        # Unet3+ model
        # _model = tf.keras.models.load_model(model_path, custom_objects={"ConvBlock": ConvBlock})
        print("Finished loading Terrain CNN model")
        print("Scores: ", classes)
        return None
    except KeyboardInterrupt:
        print("Interrupted by user.")
        return None
    except Exception as e:
        print("Error: ", e)
        return None

def predict(data, imageSize):
    try:
        data = np.frombuffer(data, dtype=np.uint8)
        _imageSize = int(imageSize)
        data = data.reshape(1, _imageSize, _imageSize, 3)
        global _model
        prediction = _model.predict(data)
        scores = create_scores(prediction, _imageSize).tolist()
        min_score = np.min(scores)
        max_score = np.max(scores)
        mean_score = np.mean(scores)
        print("Terrain: ", imageSize)
        print("Min: ", min_score)
        print("Max: ", max_score)
        print("Mean: ", mean_score)
        return scores
    except KeyboardInterrupt:
        print("Interrupted by user.")
        return None
    except Exception as e:
        print("Error: ", e)
        return None