【问题标题】:replace row of 3D array if all values below test - one numpy line using indexing如果所有值都低于测试,则替换 3D 数组的行 - 使用索引的一个 numpy 行
【发布时间】:2017-02-10 12:42:52
【问题描述】:

有没有一种 numpythonic 方法可以做到这一点?原始数组的维度为N x M x 3,我想制作一个N x M 掩码,如图所示。我认为有一种简单的方法可以用 Numpy 编写此代码,但我的大脑冻结了。

虽然可能有其他方法可以实现这一点,但我正在尝试以这种方式来保持我使用 Numpy 索引的技能。

这失败了,因为img2[test] 失去了原来的形状。我是否必须以某种方式.reshape(),还是有更简单的方法不需要明确重申轴的尺寸?

import numpy as np
import matplotlib.pyplot as plt

img  = np.random.random(100*100*3).reshape(100, 100, -1)
img2 = img.copy()

target = np.array([0.5, 0.3, 0.7])

test = np.abs(img - target) < 0.5

img2[test] = np.zeros(3)  # probem, img2[test] looses its shape

plt.figure()
plt.imshow(np.hstack((img, img2)))
plt.show()

File "/Users/yournamehere/Documents/fishing/Eu;er diagram/stackexchange question v00.py", line 12, in <module>
    img2[test] = target
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 11918 output values where the mask is true

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    这是一个展示非常有用的keepdims kwarg

    np.where(np.logical_and.reduce(test, axis=-1, keepdims=True), [0, 0, 0], img)
    

    【讨论】:

    • 感谢您的迷你 numpyphany!并不是每天都能从一条线上的答案中学到几件新东西。
    • @uhoh 谢谢!很高兴你喜欢它。
    【解决方案2】:

    大脑未冻结。忘记使用 .all() 将测试折叠为每个 N x M 位置的单个布尔值。一旦改正,Numpy 就会做得非常好。

    import numpy as np
    import matplotlib.pyplot as plt
    
    img  = np.random.random(100*100*3).reshape(100, 100, -1)
    img2 = img.copy()
    
    target = np.array([0.5, 0.3, 0.7])
    
    test = (np.abs(img - target) < 0.5).all(axis=-1)
    
    img2[test] = np.zeros(3)  # probem, img2[test] looses its shape
    
    plt.figure()
    plt.imshow(np.hstack((img, img2)))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2019-09-26
      • 2021-01-22
      相关资源
      最近更新 更多