我想知道是否有人可以帮助我解决我在这段代码中做错的事情?
我对编码非常陌生,因此使用相同逻辑编码的简单解决方案将不胜感激。
第一张图是我需要做什么的描述。
这是我的代码:
def smooth_polygon(self, alpha):
n = len(self.x)
self.x[0] = (1-alpha)*self.x[0]+alpha*1/2*(self.x[-1] + self.x[1])
self.y[0] = (1-alpha)*self.y[0]+alpha*1/2*(self.y[-1] + self.y[1])
self.x[-1] = (1-alpha)*self.x[-1]+alpha*1/2*(self.x[-2] + self.x[0])
self.y[-1] = (1-alpha) * self.y[-1] + alpha * 1/2 * (self.y[-2] + self.y[0])
for i in range(1, n-1):
self.x[i] = (1-alpha)*self.x[i]+1/2*alpha*(self.x[i-1] + self.x[i+1])
self.y[i] = (1-alpha)*self.y[i]+1/2*alpha*(self.y[i-1] + self.y[i+1])
plt.plot(self.x,self.y, 'k.-')
plt.show()
return self.x,self.y
第三张图是红色多边形的绘图,这是正确的平滑多边形:
最后是我的图:
我做错了什么?
如评论中所述,逐个元素修改数组是问题的根源。您可以创建一个新的临时数组,然后移动到位。此外,我喜欢的一种模式是“不可变对象”模式。总而言之,这就是这种方法:
class Polygon:
def __init__(self, x, y):
self.x = [e for e in x]
self.y = [e for e in y]
assert len(self.x) == len(self.y), "x and y must have same length"
@staticmethod
def smooth_filter(a, alpha):
roll_neg = a[-1:] + a[:-1]
roll_pos = a[1:] + a[:1]
return [(1 - alpha) * u + alpha/2 * (v + w) for u, v, w in zip(a, roll_neg, roll_pos)]
def smoothed(self, alpha=0.1):
'''returns a new, smoothed Polygon'''
return Polygon(
Polygon.smooth_filter(self.x, alpha),
Polygon.smooth_filter(self.y, alpha),
)
def plot(self, ax=None, **kwargs):
ax = plt.gca() if ax is None else ax
ax.plot(self.x + self.x[:1], self.y + self.y[:1], **kwargs)
return ax
现在举个例子:
# rough approximation of the points in the OP's image
p = Polygon(
[0, 11, 18, 28, 46, 36, 39, 23, 5, 8],
[4, 0, 4, 0, 4, 8, 16, 12, 16, 12],
)
fig, ax = plt.subplots(figsize=(5, 4))
p.plot(c='k', ax=ax)
p.smoothed(.5).plot(c='r', ax=ax)