2015-06-07 62 views
2

我對圖像執行了均值偏移分割並獲得了標籤數組,其中每個點值對應於它所屬的分段。根據另一個數組中的信息對NumPy數組進行操作

labels = [[0,0,0,0,1], 
      [2,2,1,1,1], 
      [0,0,2,2,1]] 

另一方面,我有相應的grayScale圖像,並希望獨立執行每個區域的操作。

img = [[100,110,105,100,84], 
     [ 40, 42, 81, 78,83], 
     [105,103, 45, 52,88]] 

比方說,我想每個區域的灰階值的總和,如果是< 200,我想這些點設置爲0(在這種情況下,在區域2中的所有點),如何我會用numpy做那個嗎?我確定有比我已經開始的實現更好的方法,其中包括很多很多的循環和臨時變量...

回答

2

查找到numpy.bincount和numpy.where,應該讓你開始。例如:

import numpy as np 
labels = np.array([[0,0,0,0,1], 
        [2,2,1,1,1], 
        [0,0,2,2,1]]) 
img = np.array([[100,110,105,100,84], 
       [ 40, 42, 81, 78,83], 
       [105,103, 45, 52,88]]) 

# Sum the regions by label: 
sums = np.bincount(labels.ravel(), img.ravel()) 

# Create new image by applying threhold 
final = np.where(sums[labels] < 200, -1, img) 
print final 
# [[100 110 105 100 84] 
# [ -1 -1 81 78 83] 
# [105 103 -1 -1 88]] 
1

您正在尋找numpy函數where。這裏就是你得到是如何開始的:

import numpy as np 

labels = [[0,0,0,0,1], 
       [2,2,1,1,1], 
       [0,0,2,2,1]] 

img = [[100,110,105,100,84], 
      [ 40, 42, 81, 78,83], 
      [105,103, 45, 52,88]] 

# to sum pixels with a label 0: 
px_sum = np.sum(img[np.where(labels == 0)]) 
+0

哇,我愛numpy:D這正是我所期待的,謝謝! – xShirase

相關問題