numpy.where() returns 尺寸不一致

numpy.where() returns inconsisten dimensions

我将一个大小为 (734,814,3) 的数组传递给一个函数,但是 numpy.where() 给出的是一维结果而不是二维结果,二维数组应该是这样

def hsi2rgb(img):
    img_rgb = np.empty_like(img)
    h = img[:,:,0] #(734,814)
    s = img[:,:,1] #(734,814)
    i = img[:,:,2] #(734,814)
    l1 = 0.00
    l2 = 2*3.14/3
    l3 = 4*3.14/3
    l4 = 3.14
    r1 = np.where(np.logical_and(h>=l1, h<l2)) #(99048,)
    r2 = np.where(np.logical_and(h>=l2, h<l3))
    r3 = np.where(np.logical_and(h>=l3, h<l4))
    hs = h[r1]
    return img_rgb

r1 显示为一个元组,r1[0]、r1[1] 的大小为 99048,这不应该是这种情况。 r1 应具有满足条件的那些值的行索引和列索引。我在没有逻辑和的情况下尝试了它,只使用一个条件,但问题仍然存在。

我遵循了你的代码,np.where 返回了预期的结果:一个包含两个一维数组的元组,其中包含满足条件的索引:

import numpy as np
h = np.random.uniform(size=(734, 814))
r1 = np.where(np.logical_and(h >= 0.1, h < 0.9))
print(r1[0].shape, r1[1].shape)    # (478129,) (478129,)

这意味着有478129个元素满足条件。对于它们中的每一个,r1[0] 将具有其行索引,而 r11 将具有其列索引。也就是说,如果 r1 看起来像

(array([  0,   0,   0, ..., 733, 733, 733]), array([  0,   1,   2, ..., 808, 809, 811]))

然后我知道h[0, 0]h[0, 1]h[0, 2]等满足条件:行索引来自第一个数组,列索引来自第二个数组。此结构的可读性可能较差,但可用于索引数组 h

输出的转置形式更具可读性,是具有行列索引对的二维数组:

array([[  0,   0],
       [  0,   1],
       [  0,   2],
       ...,
       [733, 808],
       [733, 809],
       [733, 811]])

可以通过r1转置得到(如果你也需要原来的r1),或者直接用np.argwhere:

r1 = np.argwhere(np.logical_and(h >= 0.1, h < 0.9))