Instructions to use Agzu/terrain_cnn with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Agzu/terrain_cnn with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Agzu/terrain_cnn") - Notebooks
- Google Colab
- Kaggle
Download terrainClassifier.py from Agzu/terrain_cnn: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/Agzu/terrain_cnn/resolve/main/terrainClassifier.py
- Command line
-
hf download hf://Agzu/terrain_cnn/terrainClassifier.py
-
curl -L -o terrainClassifier.py https://huggingface.co/Agzu/terrain_cnn/resolve/main/terrainClassifier.py
5.93 kB
| 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)) | |
| 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 |