代码之家  ›  专栏  ›  技术社区  ›  Vahni

where()返回不一致的维度

  •  0
  • Vahni  · 技术社区  · 6 年前

    我将一个数组大小(734814,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应具有满足条件的值的行索引和列索引。我在没有逻辑的情况下尝试过,只使用了一个条件,但问题仍然存在。

    1 回复  |  直到 6 年前
        1
  •  2
  •   user6655984    6 年前

    我遵守了你的守则 np.where 返回了预期结果:一个元组具有两个1D数组,其中包含满足条件的索引:

    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]都有其行索引,r1 1 将有其列索引。即,如果 r1 看起来像

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

    那我就知道了 h[0, 0] ,请 h[0, 1] ,请 h[0, 2] ,etc满足以下条件:行索引来自第一个数组,列索引来自第二个数组。这个结构可能不太可读,但它可以用于索引数组 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))