Skip to content

Instantly share code, notes, and snippets.

@nanaHa1003
Last active March 27, 2020 08:10
Show Gist options
  • Save nanaHa1003/4356eeeae84cbb844858b19b835de855 to your computer and use it in GitHub Desktop.
Save nanaHa1003/4356eeeae84cbb844858b19b835de855 to your computer and use it in GitHub Desktop.
[Calculate volume diameter]
import numpy as np
from scipy.ndimage import morphology
def calc_diameter(labels, target):
# Find slice with maximum area
i = np.argmax(np.where(labels == target, 1, 0).sum(axis=(0, 1)))
s = np.where(labels[:, :, i] == target, 1, 0)
# Extract contour points of target area
c = s - morphology.binary_erosion(s)
p = np.argwhere(c == 1)
# Calculate pairwise distance of points on the contour
n = p.shape[0]
# Use (x - y)^2 = x^2 + y^2 - 2xy
d = np.broadcast_to(np.sum(np.square(p), axis=1), (n, n))
d = d + d.T - 2 * np.matmul(p, p.T)
d = np.sqrt(np.max(d))
return d
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment