2013-03-07 81 views
2

我有一個大的numpy數組,並用scipy中的連接組件標記進行標記。現在我想創建這個數組的子集,其中只剩下最大或最小的標籤。 這兩個極值當然可以發生多次。從numpy數組中分離最大/最小的標籤補丁

import numpy 
from scipy import ndimage 
.... 
# Loaded in my image file here. To big to paste 
.... 
s = ndimage.generate_binary_structure(2,2) # iterate structure 
labeled_array, numpatches = ndimage.label(array,s) # labeling 
# get the area (nr. of pixels) of each labeled patch 
sizes = ndimage.sum(array,labeled_array,range(1,numpatches+1)) 

# To get the indices of all the min/max patches. Is this the correct label id? 
map = numpy.where(sizes==sizes.max()) 
mip = numpy.where(sizes==sizes.min()) 

# This here doesn't work! Now i want to create a copy of the array and fill only those cells 
# inside the largest, respecitively the smallest labeled patches with values 
feature = numpy.zeros_like(array, dtype=int) 
feature[labeled_array == map] = 1 

有人可以給我提示如何繼續前進?

回答

4

下面是完整的代碼:

import numpy 
from scipy import ndimage 

array = numpy.zeros((100, 100), dtype=np.uint8) 
x = np.random.randint(0, 100, 2000) 
y = np.random.randint(0, 100, 2000) 
array[x, y] = 1 

pl.imshow(array, cmap="gray", interpolation="nearest") 

s = ndimage.generate_binary_structure(2,2) # iterate structure 
labeled_array, numpatches = ndimage.label(array,s) # labeling 

sizes = ndimage.sum(array,labeled_array,range(1,numpatches+1)) 
# To get the indices of all the min/max patches. Is this the correct label id? 
map = numpy.where(sizes==sizes.max())[0] + 1 
mip = numpy.where(sizes==sizes.min())[0] + 1 

# inside the largest, respecitively the smallest labeled patches with values 
max_index = np.zeros(numpatches + 1, np.uint8) 
max_index[map] = 1 
max_feature = max_index[labeled_array] 

min_index = np.zeros(numpatches + 1, np.uint8) 
min_index[mip] = 1 
min_feature = min_index[labeled_array] 

注:

  • numpy.where返回一個元組
  • 標籤1的大小尺寸[0],所以你需要加1 numpy.where
  • 要獲得具有多個標籤的遮罩陣列,可以使用labeled_array作爲標籤遮罩陣列的索引。

結果:

enter image description here

enter image description here

enter image description here

+0

太好了,謝謝你非常喜歡!這工作得很好。我嘗試過索引它,但我沒有得到將1添加到標籤1的大小之前的技巧。 – Curlew 2013-03-08 16:42:06

1

首先需要標記的掩模,給出的掩模僅具有0(背景)和1(前景):

labeled_mask, cc_num = ndimage.label(mask) 

然後找到最大的連接組件:

largest_cc_mask = (labeled_mask == (np.bincount(labeled_mask.flat)[1:].argmax() + 1)) 

您可以通過使用argmin推斷最小的對象發現()..