簡體   English   中英

獲取圖像中每個像素的坐標

[英]get coordinate of each pixel in an image

我有一個圖像讀取為 numpy 數組 A 形狀(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

但是迭代需要很長時間,您有更好的方法嗎? 此致

我要做的是創建坐標 arrays 並連接:

# 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)

Output:

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

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

       [[203, 133,  79,   2,   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]]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM