如何在 Swift 中使用 PythonKit 将布尔掩码数组与 NumPy 一起使用

How to use boolean mask arrays with NumPy using PythonKit in Swift

我有以下 Python 代码:

print("Cluster connected triangles")

with o3d.utility.VerbosityContextManager(
        o3d.utility.VerbosityLevel.Debug) as cm:
    triangle_clusters, cluster_n_triangles, cluster_area = (
        mesh.cluster_connected_triangles())
triangle_clusters = np.asarray(triangle_clusters)
cluster_n_triangles = np.asarray(cluster_n_triangles)
cluster_area = np.asarray(cluster_area)

print("Get mesh with small clusters removed")

mesh_1 = copy.deepcopy(mesh)
largest_cluster_idx = cluster_n_triangles.argmax()
triangles_to_remove = triangle_clusters != largest_cluster_idx
mesh_1.remove_triangles_by_mask(triangles_to_remove)

我正尝试在 Swift(Python套件)

中进行改编
let np = Python.import("numpy")

let clusters = mesh.cluster_connected_triangles()
let triangle_clusters = np.asarray(clusters[0])
let cluster_n_triangles = np.asarray(clusters[1])
let cluster_area = np.asarray(clusters[2])
let largest_cluster_idx = cluster_n_triangles.argmax()
let triangles_to_remove = (triangle_clusters != largest_cluster_idx).  // ERROR: Ambiguous use of operator '!='
let largestCluster = mesh.remove_triangles_by_mask(triangles_to_remove)

谁能帮我转换这个 Python 行: triangles_to_remove = triangle_clusters != largest_cluster_idx 在 Swift/PythonKit

换句话说: 用于创建布尔掩码数组的 PythonKit/Swift 语法是什么?

答案是将代码包装在PythonObject中:

print("Clustering...")

let clusters = mesh.cluster_connected_triangles()
let triangle_clusters = np.asarray(clusters[0])
let cluster_n_triangles = np.asarray(clusters[1])
let cluster_area = np.asarray(clusters[2])
let largest_cluster_idx = cluster_n_triangles.argmax()

print("\(mesh) : with \(cluster_n_triangles.count) clusters.")
print("Largest cluster : \(cluster_n_triangles[largest_cluster_idx]) triangles.")

//THIS!
let triangles_to_remove = PythonObject(triangle_clusters != largest_cluster_idx)

mesh.remove_triangles_by_mask(triangles_to_remove)
mesh.remove_unreferenced_vertices()

print("Cluster Result: \(mesh)")