我发现了一个使用Numpy实现计算二维点凸包的好方法。我想将这个函数@njit化,以便在我的其他Numba jitted代码中使用它。但是,由于它使用递归和不支持的Numba功能,我无法修改它使其运行。有人能帮我重写一下吗?
import numpy as np
from numba import njit
def process(S, P, a, b):
signed_dist = np.cross(S[P] - S[a], S[b] - S[a])
K = [i for s, i in zip(signed_dist, P) if s > 0 and i != a and i != b]
if len(K) == 0:
return (a, b)
c = max(zip(signed_dist, P))[1]
return process(S, K, a, c)[:-1] + process(S, K, c, b)
def quickhull_2d(S: np.ndarray) -> np.ndarray:
a, b = np.argmin(S[:,0]), np.argmax(S[:,0])
max_index = np.argmax(S[:,0])
max_element = S[max_index]
return process(S, np.arange(S.shape[0]), a, max_index)[:-1] + process(S, np.arange(S.shape[0]), max_index, a)[:-1]
示例数据输入和输出
points = np.array([[0, 0], [1, 1], [0.5, 0.5], [0, 1], [1, 0]])
ch = quickhull_2d(points)
print(ch)
[0, 4, 1, 3]
print(points[ch])
[[0. 0.]
[1. 0.]
[1. 1.]
[0. 1.]]
np.full((3, 3), 2)
运行quickhull_2d
时,我在process
函数内部收到一个错误:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
。您确定提供的代码在其未修改的形式下是正确的吗?如果是,请提供一个示例输入数组。谢谢。 - Rafnus