3

我有一个大的 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

有人可以给我提示如何继续前进吗?

4

2 回答 2

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的大小是sizes[0],所以需要在结果中加1numpy.where
  • 要获取具有多个标签的掩码数组,可以将labeled_array其用作标签掩码数组的索引。

结果:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

于 2013-03-08T12:37:04.497 回答
3

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

labeled_mask, cc_num = ndimage.label(mask)

然后找到最大的连通分量:

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

您可以使用 argmin() 推断最小的对象查找。

于 2017-07-18T10:33:38.237 回答