获取图像中每个像素的坐标

问题描述 投票:1回答:1

我有一个图像读取为一个numpy数组A shape(n,m,3)

A = 
array([[[ 21,  38,  32],
        [ 29,  46,  38],
        [ 35,  52,  42],
        ...,

我想转换它,以便在一个新的轴上得到每个元素的索引坐标。

B = 
array([[[ 21,  38,  32,   0,  0],
        [ 29,  46,  38,   0,  1],
        [ 35,  52,  42,   0,  2],
        ...,
# in the form
B = 
array([[[ R,  G,  B,   px,  py],

where 
px= row index of the pixel
py= column index of the pixel

我编了这个

B=np.zeros((n,m,5))
for x in range(n):
    for y in range(m):
        row=list(A[x,y,:])+[x,y]
        B[x,y]=row

但这是花了太多的时间来迭代有你更好的方法吗?最好的问候。

python image numpy
1个回答
0
投票

如果你想要一个没有导入的答案。

array = np.array(img)
print(array.shape)
# (1080, 1920, 3)
zeros = np.zeros(array.shape[:2])
x_and_y = (np.dstack([(zeros.T + np.arange(0, array.shape[0])).T,
                      zeros + np.arange(0, array.shape[1])])
           .astype('uint32'))
print(np.dstack([array, x_and_y]))

输出。

    [[[39   86  101    0    0]
      [39   86  101    0    1]
      [39   86  101    0    2]
      ...
      [11  114  123    0 1917]
      [13  121  128    0 1918]
      [13  121  128    0 1919]]

     [[39   86  101    1    0]
      [39   86  101    1    1]
      [39   86  101    1    2]
      ...
      [7  110  119    1 1917]
      [19  127  134    1 1918]
      [17  125  132    1 1919]]

     ...

     [[46  136  154 1078    0]
      [49  139  157 1078    1]
      [46  143  159 1078    2]
      ...
      [30  105  119 1078 1917]
      [30  105  119 1078 1918]
      [30  105  119 1078 1919]]

     [[46  136  154 1079    0]
      [49  139  157 1079    1]
      [46  143  159 1079    2]
      ...
      [30  105  119 1079 1917]
      [30  105  119 1079 1918]
      [30  105  119 1079 1919]]]

0
投票

我会做的是创建坐标数组并连接。

# random A
np.random.seed(1)
A = np.random.randint(0,256, (3,2,3))

from itertools import product
coords = np.array(list(product(np.arange(A.shape[0]),
                      np.arange(A.shape[1])))
        ).reshape(A.shape[:2]+(-1,))

B = np.concatenate((A,coords), axis=-1)

输出:

array([[[ 37, 235, 140,   0,   0]],

       [[ 72, 255, 137,   1,   0]],

       [[203, 133,  79,   2,   0]]])
© www.soinside.com 2019 - 2024. All rights reserved.