从numpy数组中隔离最大/最小标记的补丁

时间:2013-03-07 23:23:49

标签: python numpy scipy

我有一个大的numpy数组,并用scipy中标记的连接组件标记它。现在我想创建这个数组的子集,其中只剩下最大或最小的标签。 两种极值当然都可以发生几次。

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

有人可以告诉我如何继续前进吗?

2 个答案:

答案 0 :(得分:6)

以下是完整代码:

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],因此您需要在numpy.where
  • 的结果中加1
  • 要获取具有多个标签的掩码数组,可以使用labeled_array作为标签掩码数组的索引。

结果:

enter image description here

enter image description here

enter image description here

答案 1 :(得分:1)

首先你需要一个带标签的面具,给定一个只有0(背景)和1(前景)的面具:

labeled_mask, cc_num = ndimage.label(mask)

然后找到最大的连通组件:

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

您可以使用argmin()..

推断出最小的物体发现