3D Spline fitting

This post is dedicated to interpolating spline from 3d point cloud data. In computer graphics, a spline is a smooth curve passing through two or more specific points. If points are in two dimension then we use regression techniques to interpolate the curve. But if data is having dimensions more than 2, fitting spline through the data is becomes more difficult. In this post we are dealing with noisy 3d data. 

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from mpl_toolkits.mplot3d import Axes3D


# 3D example
total_rad = 10
z_factor = 3
noise = 0.1

num_true_pts = 200
s_true = np.linspace(0, total_rad, num_true_pts)
x_true = np.cos(s_true)
y_true = np.sin(s_true)
z_true = s_true/z_factor

num_sample_pts = 80
s_sample = np.linspace(0, total_rad, num_sample_pts)
x_sample = np.cos(s_sample) + noise * np.random.randn(num_sample_pts)
y_sample = np.sin(s_sample) + noise * np.random.randn(num_sample_pts)
z_sample = s_sample/z_factor + noise * np.random.randn(num_sample_pts)

tck, u = interpolate.splprep([x_sample,y_sample,z_sample], s=2)
x_knots, y_knots, z_knots = interpolate.splev(tck[0], tck)
u_fine = np.linspace(0,1,num_true_pts)
x_fine, y_fine, z_fine = interpolate.splev(u_fine, tck)
%matplotlib inline
fig2 = plt.figure(2)
ax3d = fig2.add_subplot(111, projection='3d')
ax3d.plot(x_true, y_true, z_true, 'b')
ax3d.plot(x_sample, y_sample, z_sample, 'r*')
ax3d.plot(x_knots, y_knots, z_knots, 'go')
ax3d.plot(x_fine, y_fine, z_fine, 'g')
fig2.show()
plt.show()

In the above image Blue line indicates original spline. The red star data is noisy data derived from spline represented by blue colour. Green coloured points are interpolated points from noisy red coloured data. Finally green colour line connecting all the green points is our final interpolated spline.

No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...