Sergey Vladimirovich
Sergey Vladimirovich

Reputation: 489

smooth the path of line with python

I have a set of points, all together they create a track, where the sequence is crucial. I can plot the track using lines, how could I smooth it after or while new points are fetching? Track might look like 1 pic:

Picture One Picture One

Picture Two Picture Two

Picture Three Picture Three

2 picture is what I want to have in the end. I tried to interpolate with scipy.interpolate but it didn't work, because it requires sorted sequence (I only achieved pic3 in the end)

Upvotes: 1

Views: 5404

Answers (2)

Isadora Rezende
Isadora Rezende

Reputation: 61

I was facing the same issue to smooth a path, the shapelysmooth package did the trick for me.

In my case, the best output was using Chaikins-Algorithm as I just wanted to remove some corners of the path.
In the issue case (keep the corners), the Catmull-Rom Spline might be a better option.

Upvotes: 0

AlecZ
AlecZ

Reputation: 590

It sounds like a different interpolation method or approach might get what you want. A cubic spline will get you straighter lines with curves at the vertices, as utilized from the scipy libary and this sample set of loop points:

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

arr = np.array([[0,0],[2,.5],[2.5, 1.25],[2.6,2.8],[1.3,1.1]])
x, y = zip(*arr)
#in this specific instance, append an endpoint to the starting point to create a closed shape
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]
#create spline function
f, u = interpolate.splprep([x, y], s=0, per=True)
#create interpolated lists of points
xint, yint = interpolate.splev(np.linspace(0, 1, 100), f)
plt.scatter(x, y)
plt.plot(xint, yint)
plt.show()

enter image description here

And original straight line would look like this:

enter image description here

Upvotes: 4

Related Questions