gpt4 book ai didi

python - 如何拟合闭合轮廓?

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:24 40 4
gpt4 key购买 nike

我有一个代表闭合轮廓(带有噪声)的数据:

contour = [(x1, y1), (x2, y2), ...]

有什么简单的方法可以贴合轮廓吗?有 numpy.polyfit功能。但如果重复 x 值,它就会失败,并且需要一些努力来确定多项式的适当次数。

最佳答案

从一个点到您要拟合的轮廓的距离是极坐标中以该点为中心的角度的周期函数。该函数可以表示为正弦(或余弦)函数的组合,可以通过傅里叶变换精确计算。实际上,根据 Parseval's theorem,通过截断为前 N 个函数的傅里叶变换计算出的线性组合最适合这 N 个函数的组合。 .

要在实践中使用它,请选择一个中心点(可能是轮廓的重心),将轮廓转换为极坐标,然后计算距中心点距离的傅里叶变换。拟合轮廓由前几个傅立叶系数给出。

剩下的一个问题是转换为极坐标的轮廓在均匀间隔的角度上没有距离值。这是 Irregular Sampling问题。由于您可能拥有相当高的样本密度,因此您可以通过在距离均匀间隔角度最近的 2 个点之间使用线性插值,或者(取决于您的数据)使用小窗口进行平均来非常简单地解决这个问题。大多数其他不规则抽样的解决方案在这里要复杂得多,也没有必要。

编辑:示例代码,有效:

import numpy, scipy, scipy.ndimage, scipy.interpolate, numpy.fft, math

# create simple square
img = numpy.zeros( (10, 10) )
img[1:9, 1:9] = 1
img[2:8, 2:8] = 0

# find contour
x, y = numpy.nonzero(img)

# find center point and conver to polar coords
x0, y0 = numpy.mean(x), numpy.mean(y)
C = (x - x0) + 1j * (y - y0)
angles = numpy.angle(C)
distances = numpy.absolute(C)
sortidx = numpy.argsort( angles )
angles = angles[ sortidx ]
distances = distances[ sortidx ]

# copy first and last elements with angles wrapped around
# this is needed so can interpolate over full range -pi to pi
angles = numpy.hstack(([ angles[-1] - 2*math.pi ], angles, [ angles[0] + 2*math.pi ]))
distances = numpy.hstack(([distances[-1]], distances, [distances[0]]))

# interpolate to evenly spaced angles
f = scipy.interpolate.interp1d(angles, distances)
angles_uniform = scipy.linspace(-math.pi, math.pi, num=100, endpoint=False)
distances_uniform = f(angles_uniform)

# fft and inverse fft
fft_coeffs = numpy.fft.rfft(distances_uniform)
# zero out all but lowest 10 coefficients
fft_coeffs[11:] = 0
distances_fit = numpy.fft.irfft(fft_coeffs)

# plot results
import matplotlib.pyplot as plt
plt.polar(angles, distances)
plt.polar(angles_uniform, distances_uniform)
plt.polar(angles_uniform, distances_fit)
plt.show()

附言有一种特殊情况可能需要注意,当轮廓非凸(重入)到一定程度时,一些光线沿某个角度通过所选中心点与它相交两次。在这种情况下,选择不同的中心点可能会有所帮助。在极端情况下,可能没有不具有此属性的中心点(如果您的轮廓看起来是 like this )。在那种情况下,您仍然可以使用上面的方法来内接或外接您拥有的形状,但这本身并不是适合它的合适方法。此方法旨在适合像土 bean 一样的“ block 状”椭圆形,而不是像椒盐卷饼这样的“扭曲”椭圆形:)

关于python - 如何拟合闭合轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13604611/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com