【问题标题】:Returning specific numpy label indices for an image返回图像的特定 numpy 标签索引
【发布时间】:2014-02-05 18:28:12
【问题描述】:

我想使用 numpy 的标签分割我的图像,然后根据在每个标签中找到的索引数量删除满足我标准的那些。例如,如果像这样创建带有我分割区域的图像并使用 scipy 的label 进行分割:

from numpy import ones, zeros
from numpy.random import random_integers
from scipy.ndimage import label

image = zeros((512, 512), dtype='int')
regionator = ones((11, 11), dtype='int')
xs = random_integers(5, 506, size=500)
ys = random_integers(5, 506, size=500)

for x, y in zip(xs, ys):
    image[x-5:x+6, y-5:y+6] = regionator

labels, n_labels = label(image)

现在我想检索大小大于 121 像素(或一个区域器大小)的每个区域的索引。然后我想取这些索引并将它们设置为零,这样它们就不再是标记图像的一部分。完成这项任务最有效的方法是什么?

基本上类似于 MATLAB 的 regionprops 或利用 IDL 的 reverse_indices 从其直方图函数输出。

【问题讨论】:

    标签: numpy label idl indices


    【解决方案1】:

    我会使用 bincount 和阈值来制作查找表:

    import numpy as np
    
    threshold = 121
    
    size = np.bincount(labels.ravel())
    keep_labels = size <= threshold
    # Make sure the background is left as 0/False
    keep_labels[0] = 0
    filtered_labels = keep_labels[labels]
    

    在上面的最后,我用数组labels 索引数组keep_labels。这在 numpy 中称为advanced indexing,它要求labels 是一个整数数组。 Numpy 然后使用labels 的元素作为keep_labels 的索引,并生成一个与labels 形状相同的数组。

    【讨论】:

    • 因此,要获得最终答案,您必须执行过滤标签 =(1 - 过滤标签)*标签之类的操作
    • 在您使用输入数组索引索引的情况下,这个魔法是如何工作的?
    • 对不起,我误解了你的问题,我以为你想保留大区域。我看到你想保留小的。您可以将 &gt; 替换为 &lt;= (请注意 0 标签,因为那是背景)。我已经改变了答案。我还添加了关于使用数组索引数组的注释。
    【解决方案2】:

    这是迄今为止我发现的对我有用的方法,即使对于大型数据集也具有良好的性能。

    使用来自here 的获取索引过程,我得出了这个结论:

    from numpy import argsort, histogram, reshape, where
    import bisect
    
    h = histogram(labels, bins=n_labels)
    h_inds = where(h[0] > 121)[0]
    
    labels_f = labels.flatten()
    sortedind = argsort(labels_f)
    sorted_labels_f = labels_f[sortedind]
    inds = []
    for i in range(1, len(h_inds)):
        i1 = bisect.bisect_left(sorted_labels_f, h[1][h_inds[i]])
        i2 = bisect.bisect_right(sorted_labels_f, h[1][h_inds[i]])
        inds.extend(sortedind[i1:i2])
    
    # Now get rid of all of those indices that were part of a label
    # larger than 121 pixels
    labels_f[inds] = 0
    filtered_labels = reshape(labels_f, (512, 512))
    

    【讨论】:

    • np.searchsorted 可能会比使用 bisect 更快
    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 2012-08-29
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2018-10-12
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多