Convert an image to 2D array in python

前端 未结 3 833
独厮守ぢ
独厮守ぢ 2021-02-07 16:24

I want to convert an image to 2D array with 5 columns where each row is of the form [r, g, b, x, y]. x, y is the position of the pixel and r,g,b are the pixel value

3条回答
  •  情书的邮戳
    2021-02-07 16:57

    I am not sure if this is the very efficient. But here you go, say arr = np.array(im); then you can do something like this.

    >>> arr = np.arange(150).reshape(5, 10, 3)
    >>> x, y, z = arr.shape
    >>> indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
    #or indices = np.hstack((np.repeat(np.arange(y), x)[:,np.newaxis], np.tile(np.arange(x), y)[:,np.newaxis]))
    >>> np.hstack((arr.reshape(x*y, z), indices))
    array([[  0,   1,   2,   0,   0],
           [  3,   4,   5,   0,   1],
           [  6,   7,   8,   0,   2],
           [  9,  10,  11,   0,   3],
           [ 12,  13,  14,   0,   4],
           [ 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,   2,   0],
           [ 33,  34,  35,   2,   1],
           [ 36,  37,  38,   2,   2],
           ...
           [129, 130, 131,   8,   3],
           [132, 133, 134,   8,   4],
           [135, 136, 137,   9,   0],
           [138, 139, 140,   9,   1],
           [141, 142, 143,   9,   2],
           [144, 145, 146,   9,   3],
           [147, 148, 149,   9,   4]])
    

提交回复
热议问题