如何高效将三维二进制Numpy数组转换为点云坐标数组
高效提取三维二进制数组中值为1的像素坐标
直接用Numpy的内置矢量化操作就能搞定,完全不需要三层循环,效率能提升几个数量级,具体有两种常用方法:
方法1:使用np.argwhere
np.argwhere会直接返回所有满足条件的元素的索引,返回结果就是你需要的P×3数组,每一行对应一个值为1的像素的(x, y, z)坐标(对应数组的三个轴顺序)。
示例代码:
import numpy as np # 假设你的三维数组名为arr,shape=(2000, 2000, 300) arr = np.random.randint(0, 2, size=(2000, 2000, 300), dtype=np.uint8) # 获取所有值为1的像素坐标 coords = np.argwhere(arr == 1) # coords就是维度为P×3的数组,P为值为1的像素总数
方法2:使用np.where + np.column_stack
np.where会分别返回每个轴上满足条件的索引数组,再用np.column_stack把三个轴的索引合并成P×3的坐标数组,结果和np.argwhere完全一致。
示例代码:
import numpy as np arr = np.random.randint(0, 2, size=(2000, 2000, 300), dtype=np.uint8) # 分别获取x、y、z轴上的索引 x_indices, y_indices, z_indices = np.where(arr == 1) # 合并成坐标数组 coords = np.column_stack((x_indices, y_indices, z_indices))
注意轴顺序
如果你的数组轴顺序和坐标定义不匹配(比如数组shape是(300, 2000, 2000),即z轴是第一个维度),只需要调整合并时的列顺序即可。比如要得到(x, y, z)的坐标:
# 假设arr.shape=(300, 2000, 2000),对应z, x, y轴 z_indices, x_indices, y_indices = np.where(arr == 1) coords = np.column_stack((x_indices, y_indices, z_indices))
这两种方法都是Numpy底层优化的矢量化操作,处理2000×2000×300的数组速度非常快,完全不需要手动写循环。
内容的提问来源于stack exchange,提问作者D. Brito
相关产品推荐
相关产品推荐

