【问题标题】:Why does 2D assignment not work as expected in Numpy?为什么 2D 分配在 Numpy 中不能按预期工作?
【发布时间】:2020-10-22 23:21:42
【问题描述】:

我有以下代码:

    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 的风格?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

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

    这达到了我想要的效果,虽然不是很漂亮:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-04
      • 2021-05-30
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多