Skip to content

Instantly share code, notes, and snippets.

View maxrohleder's full-sized avatar
🏠
Working from home

Maximilian Rohleder maxrohleder

🏠
Working from home
View GitHub Profile
import numpy as np
def get_camera_center(_P):
return -np.linalg.inv(_P[:3, :3]) @ _P[:3, 3]
def angle_between_plane_and_line(line_direction: np.ndarray, point1, point2, point3):
# Calculate the normal vector of the plane
normal_vector = np.cross(point2-point1, point3-point1)
normal_vector /= np.linalg.norm(normal_vector) # normalize normal vector
# set new weights from loaded tf values
with torch.no_grad():
for (name, param), (tf_name, tf_param) in zip(m.named_parameters(), tf_weights.items()):
# convert NHWC to NCHW format and copy to change memory layout
tf_param = np.transpose(tf_param, (3, 2, 0, 1)).copy() if len(tf_param.shape) == 4 else tf_param
assert tf_param.shape == param.detach().numpy().shape, name
# https://discuss.pytorch.org/t/how-to-assign-an-arbitrary-tensor-to-models-parameter/44082/3
param.copy_(torch.tensor(tf_param, requires_grad=True, dtype=param.dtype))
@maxrohleder
maxrohleder / translate_architecture.py
Last active January 11, 2023 13:06
Convert tf to pytorch model
# >>> tf1 implementation (without encapsulating class)
import tensorflow as tf
def upconvcat(self, x1, x2, n_filter, name):
x1 = tf.keras.layers.UpSampling2D((2, 2))(x1)
x1 = tf.layers.conv2d(x1, filters=n_filter, kernel_size=(3, 3), padding='same', name="upsample_{}".format(name))
return tf.concat([x1, x2], axis=-1, name="concat_{}".format(name)) # NHWC format
# >>> pytorch implementation
import torch
@maxrohleder
maxrohleder / extract_weights.py
Last active January 12, 2023 08:19
Tensorflow to Pytorch conversion
import tensorflow as tf # tensorflow 1.x
import pickle
'''
<base_folder>
├───checkpoint
├───<model_name>.meta
├───<model_name>.data-00000-of-00001
└───<model_name>.index
'''
@maxrohleder
maxrohleder / to_stl.py
Created August 2, 2022 08:34
snippet to convert a binary volume to an stl surface mesh
from skimage import measure
from stl import mesh
def to_stl(fname, vol):
assert np.alltrue(np.isin(vol, [1, 0])), "volume must be binary"
verts, faces, _, _ = measure.marching_cubes_lewiner(vol)
m = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
for j in range(3):
m.vectors[i][j] = verts[f[j], :]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@maxrohleder
maxrohleder / DiceBCELoss.py
Last active June 14, 2023 13:54
losses for biomedical image segmentation
import tensorflow as tf
class DiceBCELoss(tf.keras.losses.Loss):
def __init__(self, roi, smooth=1e-6, eps=1e-8, name='DiceBCE'):
""" A more stable surrogate for the dice metric
Sources:
[1] https://github.com/Project-MONAI/MONAI/issues/807
[2] https://www.kaggle.com/bigironsphere/loss-function-library-keras-pytorch
Args:
roi: bool mask same size as y_pred and y_true
@maxrohleder
maxrohleder / tf_slicing.py
Created June 21, 2021 09:43
tensorflow slice assignment
# we have 1 batch of a stack of size 2 of images shape (3, 4)
test = tf.constant(np.arange(24).reshape(1, 2, 3, 4), dtype=tf.int64)
# <tf.Tensor: shape=(1, 2, 3, 4), dtype=int64, numpy=
# array([[[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]]])>
# Adapted from https://www.tensorflow.org/overview
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# 1. Define a model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
@maxrohleder
maxrohleder / keras-functional.py
Created February 7, 2021 18:18
this toy-resnet demonstrates the functional api of keras.
# taken from https://www.tensorflow.org/guide/keras/functional#a_toy_resnet_model
inputs = keras.Input(shape=(32, 32, 3), name="img")
x = layers.Conv2D(32, 3, activation="relu")(inputs)
x = layers.Conv2D(64, 3, activation="relu")(x)
block_1_output = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(block_1_output)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(x)
block_2_output = layers.add([x, block_1_output])