【问题标题】:getting indices when comparing multidimensional arrays比较多维数组时获取索引
【发布时间】:2014-09-26 05:51:39
【问题描述】:

我有两个 numpy 数组,一个是 RGB 图像,一个是像素值查找表,例如:

img = np.random.randint(0, 9 , (3, 3, 3))
lut = np.random.randint(0, 9, (1,3,3))

我想知道lut 中像素的x,y 坐标,这些像素的值与imglut 相同,所以我尝试了:

for x in xrange(img.shape[0]):
    for y in xrange(img.shape[1]):
            print np.transpose(np.concatenate(np.where(lut == img[x,y])))

此时,问题在于img[x,y] 的形式为[int_r, int_g, int_b] 不会被评估为单个元素,因此在img 中分别寻找这三个组件...

我希望输出类似于:

(x_coord, y_coord)

但我只得到以下形式的输出:

[0 0 0]
[0 2 1]
[0 0 2]
[0 0 0]
[0 0 0]
[0 0 2]
[0 0 1]
[0 2 2]
[0 1 2]

有人可以帮忙吗?谢谢!

【问题讨论】:

    标签: python arrays numpy multidimensional-array indexing


    【解决方案1】:
    img = np.random.randint(0, 9 , (3, 3, 3))
    lut2 = img[1,2,:] # so that we know exactly the answer
    
    # compare two matrices
    img == lut2
    
    array([[[False, False, False],
            [False, False, False],
            [False,  True, False]],
    
           [[False, False, False],
            [False, False, False],
            [ True,  True,  True]],
    
           [[ True, False, False],
            [ True, False, False],
            [False, False, False]]], dtype=bool)
    
    # rows with all true are the matching ones
    np.where( (img == lut2).sum(axis=2) == 3 )
    
    (array([1]), array([2]))
    

    我真的不知道为什么 lut 充满了随机数。但是,我假设您要查找具有完全相同颜色的像素。如果是这样,这似乎有效。这是你需要做的吗?

    【讨论】:

    • 是的,这正是我想要的。非常感谢!
    • 它帮助了毕业。使用 Numpy,尽量避免循环。享受 numpy!
    【解决方案2】:

    @otterb 的答案在 lut 被定义为单个 [r,g,b] 像素切片时有效,但如果您想将此过程推广到多像素 @987654323,则需要稍作调整@:

    img = np.random.randint(0, 9 , (3, 3, 3))
    lut2 = img[0:1,0:2,:]
    
    for x in xrange(lut2.shape[0]):
        for y in xrange(lut2.shape[1]):
            print lut2[x,y]
            print np.concatenate(np.where( (img == lut2[x,y]).sum(axis=2) == 3 ))
    

    产量:

    [1 1 7]
    [0 0]
    [8 7 4]
    [0 1]
    

    其中三元组是像素值,二元组是它们在lut 中的坐标。

    干杯,感谢@otterb!

    PS:对 numpy 数组的迭代很糟糕。以上不是生产代码。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多