Last active
July 2, 2021 10:49
-
-
Save prerakmody/881e45e9ed7e2656ab72123f23f65c7f to your computer and use it in GitHub Desktop.
Volume Processing in TFlow 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This method uses the max pooling operation to get the boundary around a binary mask | |
Can be used in segmentation tasks where one wants to specific a loss for the boundary pixels/voxels | |
""" | |
import os | |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" | |
import nrrd | |
import numpy as np | |
import tensorflow as tf | |
import matplotlib.pyplot as plt | |
# Step 1 - Define params | |
filename = 'nrrd_HaN_MICCAI2015-test_offsite-0522c0555_resample_True_mask.nrrd' | |
idx = 40 | |
ksize = (6,6,3) | |
# Step 2 - Get boundary of mask | |
data, _ = nrrd.read(filename) # [H,W,D] | |
data[data > 0] = 1 | |
data = tf.constant(data, tf.float32) | |
data = tf.expand_dims(tf.expand_dims(data, axis=0), axis=-1) | |
data_dilated = tf.nn.max_pool3d(data, ksize=ksize, strides=1, padding='SAME') | |
data_eroded = -tf.nn.max_pool3d(-data, ksize=ksize, strides=1, padding='SAME') | |
data_boundary = data_dilated - data_eroded | |
f,axarr = plt.subplots(2,2, figsize=(10,10)) | |
axarr[0][0].imshow(data[0,:,:,idx,0], cmap='gray') | |
axarr[0][0].set_title('Original Map') | |
axarr[0][1].imshow(data_dilated[0,:,:,idx,0], alpha=0.5, cmap='gray') | |
axarr[0][1].set_title('Dilated ') | |
axarr[1][0].imshow(data_eroded[0,:,:,idx,0], alpha=0.5, cmap='gray') | |
axarr[1][0].set_title('Eroded ') | |
axarr[1][1].imshow(data_boundary[0,:,:,idx,0], alpha=0.5, cmap='gray') | |
axarr[1][1].set_title('Boundary') | |
plt.show() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: Chosing odd-numbered shape for kernels is important to achieve the desired dilation effect. | |
import numpy as np | |
import matplotlib.pyplot as plt | |
plt.imshow(np.random.random((100,100))); plt.show() | |
import tensorfow as tf | |
A = [[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 1, 0, 0], | |
[0, 0, 0, 1, 1, 1, 0], | |
[0, 0, 0, 0, 1, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0]] | |
A = np.expand_dims(np.expand_dims(A, axis=0),axis=-1) | |
A_ = tf.nn.dilation2d(A,filters=tf.zeros((3,3,1), dtype=tf.int32), strides=(1,1,1,1), padding='SAME', data_format='NHWC', dilations=(1,1,1,1)) | |
A[0,:,:,0] | |
A_[0,:,:,0] | |
A_ = tf.nn.max_pool2D(A, ksize=(3,3), strides=1, padding='SAME') | |
A[0,:,:,0] | |
A_[0,:,:,0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment