首页 > 解决方案 > 为什么 2D 分配在 Numpy 中不能按预期工作?

问题描述

我有以下代码:

    for (old_point, new_point) in zip(masked_indices, masked_new_indices):
        row, col = old_point
        new_row, new_col = new_point
        
        new_img[row, col] = img[new_row, new_col]

其中new_imgimg都是 1024x1024x3 ndarray,并且masked_indicesmasked_new_indices都是 80000x2 ndarray。

为什么这个语句没有相同的行为?

    new_img[masked_indices] = img[masked_new_indices]

有没有办法把这个for循环优化成更 NumPy 风格的?

标签: pythonnumpy

解决方案


我想到了。由于new_img是三维的,我必须指定两个索引。尝试在单个索引中使用 2D 值是导致意外行为的原因。

这产生了我想要的效果,虽然它不是很漂亮:

new_img[masked_indices[:, 0], masked_indices[:, 1], :] = img[masked_new_indices[:, 0], masked_new_indices[:, 1], :]

推荐阅读