Python - 通过已识别的组件功能

时间:2012-09-24 00:38:19

标签: python image-processing numpy scipy

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

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

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

2 个答案:

答案 0 :(得分: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()

这是脚本生成的图像:

enter image description here

答案 1 :(得分:1)

快速说明解决上述问题的另一种方法。也可以使用ndimage“find_objects”函数代替使用NumPy“fanzy indexing”。 例如:

# 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()非常容易)以及特征附近的非标记单元的数量(ergo计算特征周围的零数)。