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
@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
# 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 / 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 / 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 / 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], :]
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@maxrohleder
maxrohleder / basic-indexing.py
Last active July 23, 2021 06:58
smart indexing can save you a lot of looping
a = np.array([[0, 1, 2],
[3, 4, 5]])
b = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# subsetting of the array (start is included, end is excluded)
print(a[0:2, 0:2])
#> [[0 1]
#> [3 4]]
# striding / stepping "every second entry"
@maxrohleder
maxrohleder / simplify-loops.py
Created November 28, 2020 13:37
use array enumeration to simplify for loops
import numpy as np
img = np.arange(6).reshape(2, 3)
# looping over all elements like this ...
for x in range(img.shape[0]):
for y in range(img.shape[1]):
print(img[x, y])
# ... is easier and more readable with numpy
@maxrohleder
maxrohleder / advanced-indexing.py
Created November 28, 2020 14:38
advanced indexing lets you manipulate arrays elegantly
import numpy as np
# some sample data in shaped cubic (100, 100, 100)
img = np.random.sample((100, 100, 100))
# set all values between 0.5 and 0.6 to zero
img[(img < 0.6) & (img > 0.5)] = 0
# in a small sub cube (10, 10, 10)..
# .. get index arrays of all elements above 0.6