簡體   English   中英

對列表中包含的每個元組進行索引的最 Pythonic 方法

[英]Most pythonic way to index each tuple contained within a list

有點像 Python 初學者,對不起,如果這是一個基本問題。

我有一個包含在可變長度列表中的 (i, j) 形式的元組。 該列表由一個函數輸出,該函數選擇圖像內的像素簇並平均它們的 RGB 值,因此元組是索引。 該函數是遞歸的,這里是返回語句:

return ((red,blue,green), tuple_list, sum_n)
# [0] (r,g,b) values [1] list of indices as tuples [2] number of pixels gathered

我從這個函數中獲取輸出並將新的 RGB 值寫入我的圖像矩陣,它是一個 numpy 數組,就像這樣使用 for 循環:

cluster = rgb_avg_cluster(depth = 0, row = i, column = j, image = newimg)
    # cluster[1] is the list of tuple indices
    for x in cluster[1]: 
          newimg[x[0],x[1],0] = int(cluster[0][0])
          newimg[x[0],x[1],1] = int(cluster[0][1])
          newimg[x[0],x[1],2] = int(cluster[0][2])

我的 numpy 數組是 [width, height, rgb],所以對於 1200x600 的圖像,它將是 (1200,600,3)。 有沒有更快的方法來索引每個元組索引處的 rgb 值並將它們更改為新值?

例如,如果我的輸出是((150,40,40), [(35,35), (95,42)], 2)是否有更好/更快的方法來更改像素(35,35)(95,42)在我的 numpy 數組中轉換為rgb = (150,40,40) 像這樣:

input: 
        ((150,40,40), [(35,35), (95,42)], 2)

result: 
        newimg[35,35,0] = 150
        newimg[35,35,1] = 40
        newimg[35,35,2] = 40
        newimg[95,42,0] = 150
        newimg[95,42,1] = 40
        newimg[95,42,2] = 40

我知道矢量化操作是使用 numpy 的方法,但我不知道在這種情況下如何實現它。 此函數需要一段時間才能按原樣執行。

謝謝!

避免 RGB 維度上的迭代很容易。 我們仍然需要迭代像素索引元組:

In [10]: atup = ((150,40,40), [(35,35), (95,42)], 2)
In [11]: newimg = np.zeros((1200,600,3),int)
In [12]: vals = atup[0]
In [13]: idx = atup[1]
In [14]: for x in idx:
    ...:     newimg[x[0],x[1],:] = vals
    ...: 

測試幾個值:

In [15]: newimg[35,35,1]
Out[15]: 40
In [16]: newimg[95,42,2]
Out[16]: 40

第一個改進是,當您調用rgb_avg_cluster 時,將其分解為 3 個組件的結果保存:

rgb, ind, sum_n = rgb_avg_cluster(...)

這樣您就可以避免對復合返回值的索引訪問(到目前為止cluster )。

然后您可以將rgb保存到相應的像素中,例如在以下循環中:

for r, c in ind:
    newimg[r, c, :] = rgb

為了測試上面的代碼,我創建了一個大小為2 行x 4 列x 3 種顏色的零填充數組:

newimg = np.zeros((2, 4, 3), dtype='int')

並將“代理” rgb_avg_cluster結果設置為:

rgb, ind, sum_n = ((150,40,40), [(1,1), (0,0)], 2)

運行上述循環后,結果是:

array([[[150,  40,  40],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [150,  40,  40],
        [  0,   0,   0],
        [  0,   0,   0]]])

編輯

即使沒有任何顯式循環,也可以保存您的結果。

要在同一個數組上執行測試,請運行:

newimg = np.zeros((2, 4, 3), dtype='int')
rgb, ind, sum_n = ((150,40,40), [(1,1), (0,0)], 2)
ind2 = np.array(ind).T
newimg[ind2[0], ind2[1], :] = rgb

細節:

  1. ind2包含一個有 2 行的數組:

     array([[1, 0], [1, 0]])

    第一行包含要保存的像素的x坐標,第二行 - y坐標,

  2. newimg[ind2[0], ind2[1]] - 提供對指定像素的訪問。 ind2[0]指定x坐標, ind2[1] - y坐標。 第三個索引實際上是不需要的。 您可以訪問此維度中的所有元素,就像您編寫的“ , : ”(作為第三個索引)一樣。

  3. newimg[...] = rgb -在給定的指標保存RGB,一氣呵成

暫無
暫無

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

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