gpt4 book ai didi

python - 在不丢失顺序的情况下消除冗余的 2D 点

转载 作者:行者123 更新时间:2023-12-01 06:22:43 24 4
gpt4 key购买 nike

我有以下几点:

import numpy as np
points = np.array([[49.8, 66.35],
[49.79, 66.35],
[49.79, 66.35],
[44.65, 67.25],
[44.65, 67.25],
[44.65, 67.25],
[44.48, 67.24],
[44.63, 67.21],
[44.68, 67.2],
[49.69, 66.21],
[49.85, 66.17],
[50.51, 66.04],
[49.8, 66.35]])

当我绘制它们时,我得到这个形状:

import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

enter image description here

正如您从点列表中看到的,其中一些是多余的(即查看点 1 和 2(从 0 开始))。

为了只保留非冗余点,我恢复了这个问题的答案: Removing duplicate columns and rows from a NumPy 2D array

def unique_2D(a):
order = np.lexsort(a.T)
a = a[order]
diff = np.diff(a, axis=0)
ui = np.ones(len(a), 'bool')
ui[1:] = (diff != 0).any(axis=1)
return a[ui]

我将此函数应用于我的点,我得到:

non_redundant_points = unique_2D(points)

这是保留点的打印列表:

[[ 50.51  66.04]
[ 49.85 66.17]
[ 49.69 66.21]
[ 49.79 66.35]
[ 49.8 66.35]
[ 44.68 67.2 ]
[ 44.63 67.21]
[ 44.48 67.24]
[ 44.65 67.25]]

但是,现在我面临以下问题:当我绘制它们时,顺序不知何故没有保留......

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

enter image description here

你知道我该如何解决这个问题吗?

为了更轻松地复制和粘贴,以下是完整代码:

import numpy as np    
import matplotlib.pyplot as plt

points = np.array([[49.8, 66.35],
[49.79, 66.35],
[49.79, 66.35],
[44.65, 67.25],
[44.65, 67.25],
[44.65, 67.25],
[44.48, 67.24],
[44.63, 67.21],
[44.68, 67.2],
[49.69, 66.21],
[49.85, 66.17],
[50.51, 66.04],
[49.8, 66.35]])

x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

def unique_2D(a):
order = np.lexsort(a.T)
a = a[order]
diff = np.diff(a, axis=0)
ui = np.ones(len(a), 'bool')
ui[1:] = (diff != 0).any(axis=1)
return a[ui]

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

最佳答案

您可以使用np.unique来获取唯一元素,并使用return_index=True来获取原始数组的索引。然后您可以使用它们对返回的唯一数组进行排序以获得原始索引顺序

points = np.array([[49.8, 66.35],
[49.79, 66.35],
[49.79, 66.35], ... ] # Your original input array

points, idx = np.unique(points, axis=0, return_index=True)
print (idx)
# [ 6 7 3 8 9 1 0 10 11]


arr = points[np.argsort(idx), :]

print (arr)

# [[49.8 66.35]
# [49.79 66.35]
# [44.65 67.25]
# [44.48 67.24]
# [44.63 67.21]
# [44.68 67.2 ]
# [49.69 66.21]
# [49.85 66.17]
# [50.51 66.04]]

绘制它们

plt.plot(arr[:, 0], arr[:, 1])

enter image description here

关于python - 在不丢失顺序的情况下消除冗余的 2D 点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60289064/

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