【问题标题】:Isolate greatest/smallest labeled patches from numpy array从 numpy 数组中分离出最大/最小的标记补丁
【发布时间】:2017-07-18 18:33:38
【问题描述】:

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

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

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    这里是完整的代码:

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

    结果:

    【讨论】:

    • 太好了,非常感谢!这很好用。我之前尝试过对其进行索引,但之前我没有得到将标签 1 的大小加 1 的技巧。
    【解决方案2】:

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

    labeled_mask, cc_num = ndimage.label(mask)
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2018-12-28
      • 2015-10-10
      • 2018-10-22
      相关资源
      最近更新 更多