B-spline or basis spline is a curve approximation method based on given coefficients. B-spline requires the parameters such as knots, spline coefficients, and degree of a spline. The SciPy API provides BSpline class to implement the B-spline fitting for a given dataset.

In this tutorial, you'll learn how to implement B-spline interpolation by using a BSpline class in Python. The tutorial covers:

- B-spline interpolation
- Source code listing

We'll start by loading the required libraries.

` `

```
from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
```

` `

**B-spline interpolation**

```
y = [0,1,3,4,3,5,7,5,2,3,4,8,9,8,7]
n = len(y)
x = range(0, n)
```

` `

` `

```
plt.plot(x, y, 'ro', label="original")
plt.plot(x, y, 'b', label="linear interpolation")
plt.title("Target data")
plt.legend(loc='best', fancybox=True, shadow=True)
plt.grid()
plt.show()
```

To represent B-spline interpolation, we need to provide required coefficients. We can take them by using the '**splrep**' function. The '**splrep**' function returns t, c, k tuple containing the vector of knots, the B-spline
coefficients, and the degree of the spline.

` `

`tck = interpolate.splrep(x, y, s=0, k=3) `

` `

` `

```
x_new = np.linspace(min(x), max(x), 100)
y_fit = interpolate.BSpline(*tck)(x_new)
```

` `

` `

```
plt.title("BSpline curve fitting")
plt.plot(x, y, 'ro', label="original")
plt.plot(x_new, y_fit, '-c', label="B-spline")
plt.legend(loc='best', fancybox=True, shadow=True)
plt.grid()
plt.show()
```

` `

**Source code listing**

` `

```
from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
y = [0,1,3,4,3,5,7,5,2,3,4,8,9,8,7]
n = len(y)
x = range(0, n)
plt.plot(x, y, 'ro', label="original")
plt.plot(x, y, 'b', label="linear interpolation")
plt.title("Target data")
plt.legend(loc='best', fancybox=True, shadow=True)
plt.grid()
plt.show()
tck = interpolate.splrep(x, y, s=0, k=3)
x_new = np.linspace(min(x), max(x), 100)
y_fit = interpolate.BSpline(*tck)(x_new)
plt.title("BSpline curve fitting")
plt.plot(x, y, 'ro', label="original")
plt.plot(x_new, y_fit, '-c', label="B-spline")
plt.legend(loc='best', fancybox=True, shadow=True)
plt.grid()
plt.show()
```

` `

**References:**

## No comments:

## Post a Comment