簡體   English   中英

在一維numpy數組中查找相鄰元素

[英]Finding adjacent elements in 1D numpy array

我有一個表示NxN矩陣的一維numpy布爾數組(例如,一個10x10矩陣的值是0到9,然后是10到19,依此類推。)我的目標是找出相鄰的“ true”元素的數量-上,下,左,右或對角線。

我解決這個問題的計划是遍歷數組(對於my_array中的x),當遇到'true'元素時,為周圍的元素輸入搜索模式。 如果周圍元素之一也為真,那么它將搜索其周圍元素。 但是,我不確定這是否是優化的搜索,並且以遞歸方式實現它非常困難。

關於在1D numpy數組中搜索相鄰元素的算法或方法有何建議?

編輯:

因為我看到的深度優先搜索使用字典來設置元素之間的路徑,所以我嘗試創建一個函數來定義此內容(如下)。

我將其簡化為僅考慮左,右,上方和下方(尚無對角線),但是邊緣情況不起作用。

有了這個,我希望使用深度優先搜索功能,在找到“ true”元素時遞歸調用自身。

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

您描述的問題在圖像處理中被稱為“連接組件標記”-您只有一維數組而不是矩陣(順便說一句,這在過去的圖像處理中很常見)。

如果轉換為2D數組,則可以應用scipy.ndimage.measurements.label( docs )(例如,如本答案中所述

如果您仍然想自己實現它,則將2-pass算法稱為標准解決方案。 在這個其他答案中還有很多其他見解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM