向np数组添加行号和列号

时间:2018-02-20 05:46:10

标签: python arrays numpy

我有一个形状为(1024, 1024, 3)的numpy数组。它是RGB转换为numpy数组的图像。我想将像素的行号和列号添加到numpy数组中。

给定一个形状为(1024, 1024, 3)的numpy数组。如何将其转换为(1024, 1024, 5)的numpy数组,其他列是特定像素的行号和列号?

如果其中一个单元格值为[125, 125, 125]且它是第5行和第3列,我想将其转换为[5, 3, 125, 125, 125]

1 个答案:

答案 0 :(得分:1)

以下是使用np.indicesnp.r_的方法:

# small test case
>>> a = np.arange(108).reshape(6, 6, 3)
# create indices
>>> i, j = np.indices(a.shape[:2])
# stack them
>>> result = np.r_["2,3,0", i, j, a]
# admire
>>> result
array([[[  0,   0,   0,   1,   2],
        [  0,   1,   3,   4,   5],
        [  0,   2,   6,   7,   8],
        [  0,   3,   9,  10,  11],
        [  0,   4,  12,  13,  14],
        [  0,   5,  15,  16,  17]],

       [[  1,   0,  18,  19,  20],
        [  1,   1,  21,  22,  23],
        [  1,   2,  24,  25,  26],
        [  1,   3,  27,  28,  29],
        [  1,   4,  30,  31,  32],
        [  1,   5,  33,  34,  35]],

       [[  2,   0,  36,  37,  38],
        [  2,   1,  39,  40,  41],
        [  2,   2,  42,  43,  44],
        [  2,   3,  45,  46,  47],
        [  2,   4,  48,  49,  50],
        [  2,   5,  51,  52,  53]],

       [[  3,   0,  54,  55,  56],
        [  3,   1,  57,  58,  59],
        [  3,   2,  60,  61,  62],
        [  3,   3,  63,  64,  65],
        [  3,   4,  66,  67,  68],
        [  3,   5,  69,  70,  71]],

       [[  4,   0,  72,  73,  74],
        [  4,   1,  75,  76,  77],
        [  4,   2,  78,  79,  80],
        [  4,   3,  81,  82,  83],
        [  4,   4,  84,  85,  86],
        [  4,   5,  87,  88,  89]],

       [[  5,   0,  90,  91,  92],
        [  5,   1,  93,  94,  95],
        [  5,   2,  96,  97,  98],
        [  5,   3,  99, 100, 101],
        [  5,   4, 102, 103, 104],
        [  5,   5, 105, 106, 107]]])