1

我站在一个巨大的问题面前。使用 Python 库 NumPy 和 SciPy,我确定了大型数组中的几个特征。为此,我创建了一个 3x3 邻居结构并将其用于连通分量分析 --> 请参阅docs

struct = scipy.ndimage.generate_binary_structure(2,2)
labeled_array, num_features = ndimage.label(array,struct)

我现在的问题是我想循环遍历所有已识别的功能。有人知道如何处理生成的 NumPy 数组中的各个特征?

4

2 回答 2

3

这是处理由 ndimage.label 标识的特征的示例。这是否对您有帮助取决于您要对这些功能做什么。

import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt


# Make a small array for the demonstration.
# The ndimage.label() function treats 0 as the "background".
a = np.zeros((16, 16), dtype=int)
a[:6, :8] = 1
a[9:, :5] = 1
a[8:, 13:] = 2
a[5:13, 6:12] = 3

struct = ndi.generate_binary_structure(2, 2)
lbl, n = ndi.label(a, struct)

# Plot the original array.
plt.figure(figsize=(11, 4))
plt.subplot(1, n + 1, 1)
plt.imshow(a, interpolation='nearest')
plt.title("Original")
plt.axis('off')

# Plot the isolated features found by label().
for i in range(1, n + 1):
    # Make an array of zeros the same shape as `a`.
    feature = np.zeros_like(a, dtype=int)

    # Set the elements that are part of feature i to 1.
    # Feature i consists of elements in `lbl` where the value is i.
    # This statement uses numpy's "fancy indexing" to set the corresponding
    # elements of `feature` to 1.
    feature[lbl == i] = 1

    # Make an image plot of the feature.
    plt.subplot(1, n + 1, i + 1)
    plt.imshow(feature, interpolation='nearest', cmap=plt.cm.copper)
    plt.title("Feature {:d}".format(i))
    plt.axis('off')

plt.show()

这是脚本生成的图像:

在此处输入图像描述

于 2012-09-24T02:54:44.183 回答
1

简要说明解决上述问题的另一种方法。除了使用 NumPy “fanzy indexing”,还可以使用 ndimage “find_objects” 函数。例子:

# Returns a list of slices for the labeled array. The slices represent the position of features in the labeled area 
s = ndi.find_objects(lbl, max_label=0)
# Then you can simply output the patches  
for i in n:
    print a[s[i]]

我会留下这个问题,因为我无法解决另一个出现的问题。我想获得特征的大小(已经解决,通过 ndi.sum() 很容易)以及特征附近的未标记单元格的数量(因此计算特征周围的零的数量)。

于 2012-09-24T11:37:49.540 回答