Skip to content

Instantly share code, notes, and snippets.

@alisterburt
Created October 7, 2022 12:07
Show Gist options
  • Select an option

  • Save alisterburt/6f19f8db22b6860952b3ac468e861166 to your computer and use it in GitHub Desktop.

Select an option

Save alisterburt/6f19f8db22b6860952b3ac468e861166 to your computer and use it in GitHub Desktop.
equidistant sampling on a spline
import numpy as np
import napari
from scipy.interpolate import splprep, splev
n = 10
w = np.linspace(0, 8*np.pi, num=n)
x = [0, 1, 1, 1,]
y = [0, 0, 10, 10]
z = [0, 0, 0, 100]
xyz = np.stack((x, y, z), axis=-1)
# calculate spline representation of curve
tck, _ = splprep([*xyz.T], s=0, k=3)
# sample points on spline
n_points_spline = 100
u = np.linspace(0, 1, n_points_spline)
sampled_points = splev(u, tck)
sampled_points = np.stack(sampled_points, axis=-1)
inter_point_differences = np.diff(sampled_points, axis=0)
inter_point_distances = np.linalg.norm(inter_point_differences, axis=-1)
cumulative_distance = np.cumsum(inter_point_distances)
cumulative_distance /= cumulative_distance[-1]
# compute spline coefficients for normalised cumulative distance
tck_prime, _ = splprep([np.linspace(0, 1, num=len(cumulative_distance))], u=cumulative_distance, s=0, k=3)
equidistant_u = splev(u, tck_prime)
equidistant_point_samples = splev(equidistant_u, tck)
equidistant_point_samples = np.stack(equidistant_point_samples, axis=-1).squeeze(axis=0)
viewer = napari.Viewer(ndisplay=3)
viewer.add_points(xyz)
viewer.add_points(sampled_points)
viewer.add_points(equidistant_point_samples)
napari.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment