【问题标题】:Efficient bit-testing conditional iteration over distinct array-elements对不同数组元素进行有效的位测试条件迭代
【发布时间】:2014-10-31 11:24:54
【问题描述】:

我有两个相同形状的 2D-numpy 数组,一个包含数据,一个 'ubyte' 类型存储每个像素的位标志。我想访问数据数组中在 bitflags-array 中具有特定标志的每个像素。

我可以遍历任一数组中的每个像素并使用多索引来获取位标志和像素值,例如

it = np.nditer(array, flags=['multi_index'])
while not it.finished:
    if bitflags[it.multi_index] & FLAG:
        do_something(array[it.multi_index])
    it.iternext()

由于大多数像素没有设置相应的位标志,我宁愿找到具有给定位标志的所有像素(例如使用 numpy.where(bitflags & FLAG) 并仅遍历这些像素 - 类似于

pixels = np.where(bitflags & FLAG)
for pixel in array[pixels]:
    do_something()

有没有办法我仍然可以获取原始数组的索引以在do_something() 中使用它们?

【问题讨论】:

    标签: python numpy iteration


    【解决方案1】:

    不完全确定我是否正确理解了您的问题,但您是否正在寻找这个:

    pixels, = np.where(bitflags & FLAG)
    for i, pixel in zip(pixels, array[pixels]):
        do_something(i, pixel)
    

    【讨论】:

    • 如此简单的解决方案!谢谢!由于我的数组是二维的,len(pixels) 是 2,所以你的代码不能直接工作,但我可以使用 p,y,x in zip(array[pixels], *pixels) 获取实际索引我完全错过了这一点,因为我很少需要 zip
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2022-09-22
    • 2017-06-06
    • 2013-05-08
    • 1970-01-01
    • 2015-02-03
    • 2021-01-19
    相关资源
    最近更新 更多