You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用三维索引数组批量为Numpy数组指定位置赋值?

解决方案:批量设置Numpy数组指定三维坐标的值

要实现将image中indices指定的所有三维坐标位置设为255,核心是正确使用Numpy的高级索引方式,具体步骤如下:

正确代码实现

import numpy as np

# 假设indices已定义,形状为(1031532, 3)
image = np.zeros((indices[:,0].max()+1, indices[:,1].max()+1, indices[:,2].max()+1), dtype='uint8')
# 关键:将indices转置后转为tuple,作为索引
image[tuple(indices.T)] = 255

错误原因解释

你之前尝试image[tuple(indices)]=255报错,是因为tuple(indices)会把indices的每一行转换为一个元组,最终得到1031532个长度为3的元组。用这个结构去索引3维数组时,Numpy会认为你要使用1031532个维度进行索引,这显然超出了数组的3维限制,因此抛出IndexError: too many indices for array。

而indices.T会将原数组转置为(3, 1031532)的形状,此时转为tuple后,得到的是3个一维数组,分别对应image的三个维度的索引集合,完全符合Numpy高级索引的要求,能精准定位到所有目标坐标。

验证示例

比如你的前4个索引:

indices_sample = np.array([[588, 153, 24],
                          [588, 154, 340],
                          [588, 156, 214],
                          [588, 157, 277]], dtype=np.int32)

使用tuple(indices_sample.T)得到的是:

(array([588, 588, 588, 588]), array([153, 154, 156, 157]), array([24, 340, 214, 277]))

这正好对应image中四个目标位置的三维索引,赋值后就能得到你期望的image[588,153,24]=255等结果。


内容的提问来源于stack exchange,提问作者testman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:57:39