【问题标题】:Finding adjacent elements in 1D numpy array在 1D numpy 数组中查找相邻元素
【发布时间】:2016-03-08 05:02:36
【问题描述】:

我有一个代表 NxN 矩阵的一维 numpy 布尔数组(例如,一个 10x10 矩阵的值是 0 到 9,然后是 10 到 19,等等) 我的目标是找到相邻的“真实”元素的数量——上、下、左、右或对角线。

我解决这个问题的计划是遍历数组(对于 my_array 中的 x),当遇到“真”元素时,输入周围元素的搜索模式。如果周围元素之一也为真,则搜索其周围元素。但是,我不确定这是否是优化的搜索,并且递归地实现它被证明是困难的。

关于在 1D numpy 数组中搜索相邻元素的算法或方法有什么建议吗?

编辑:

因为我见过的深度优先搜索使用字典来设置元素之间的路径,所以我尝试创建一个函数来定义它(如下)。

我将其简化为只考虑左、右、上和下(还没有对角线),但边缘情况不起作用。

有了这个,我希望使用深度优先搜索功能,当找到“真实”元素时递归调用自身。

def getgraph(lst):
    #print('here2')
    for x in lst:
        if x is 0:
            graph[x] = set([x+1, x+n])
            x = x+1
        while (x > 0) and (x < (n-1)): #first row, excluding edges
            graph[x] = set([(x-1),(x+1),(x+n)])
            x= x+1

        while x >= (n-1) and x < ((n-1)*n): #second to second last row, with edge cases
            v = x%n
            width = n-1
            print('XN: %f' %v)
            if (x % n) == 0:
                graph[x] = set([x+1, x+n])
                x = x+1
            if (v) is width:
                graph[x] = set([(x-1),(x+n)])
                x = x+1
            else:
                graph[x] = set([(x-1), (x+1), (x+n), (x-n)])
                x= x+1

        while x >= (n-1)*n and x <= ((n*n)-1):
            value = ((n*n)-1)
            if x is value: # works with manually inputting last element number
                graph[x] = set([(x-1),(x-n)])
                x = x+1
            else:
                graph[x] = set([(x-1),(x+1),(x-n)])
                x= x+1

    print(graph)
    return graph

【问题讨论】:

标签: python arrays algorithm numpy


【解决方案1】:

您描述的问题在图像处理中称为“连接组件标记”-您只有一个一维数组而不是矩阵(顺便说一句,这是过去图像处理的常见情况)。

如果您转换为二维数组,您可以应用 scipy.ndimage.measurements.label (docs)(例如,如answer 中所述)

如果您仍想自己实现,a 2-pass algorithm 被称为标准解决方案。许多额外的见解in this other answer

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2015-12-26
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多