[英]Neighbors in a 2D array python
我有一個 2D numpy 數組,如下所示:
start = np.array([
[1,1,0,1],
[1,0,0,1],
[0,1,0,0]
])
我需要得到相同的矩陣,但是用我可以通過向任何方向移動一步但只沿着1
走得到的鄰居數替換每個值
結果,我應該得到以下信息:
finish = np.array([
[4,4,0,2],
[4,0,0,2],
[0,4,0,0]
])
在我看來,這是一個眾所周知的問題,但我什至沒有想出如何在搜索中表述它,因為我正在尋找的一切都有點不同。 最好的方法是什么?
您可以使用帶有自定義結構數組s
的scipy.ndimage
標簽function :
import numpy as np
from scipy.ndimage import label
start = np.asarray([ [1,1,0,1],
[1,0,0,1],
[0,1,0,0] ])
#structure array what to consider as "neighbors"
s = [[1,1,1],
[1,1,1],
[1,1,1]]
#label blobs in array
labeledarr,_ = label(start, structure=s)
#retrieve blobs and the number of elements within each blobs
blobnr, blobval = np.unique(labeledarr.ravel(), return_counts=True)
#substitute blob label with the number of elements
finish = np.zeros_like(labeledarr)
for k, v in zip(blobnr[1:], blobval[1:]):
finish[labeledarr==k] = v
print(finish)
Output:
[[4 4 0 2]
[4 0 0 2]
[0 4 0 0]]
我確信用它出現的值替換 label 數字的最后一步可以在速度方面進行優化。
@mad-physicist 正確地提到最初使用的labeledarr.flat
應該替換為labeledarr.ravel()
。 此處解釋了其原因。
我有一個二維 numpy 數組,如下所示:
start = np.array([
[1,1,0,1],
[1,0,0,1],
[0,1,0,0]
])
我需要得到相同的矩陣,但將每個值替換為我可以通過向任何方向移動一步而得到的鄰居數,但只能沿着1
行走
結果,我應該得到以下信息:
finish = np.array([
[4,4,0,2],
[4,0,0,2],
[0,4,0,0]
])
在我看來,這是一個眾所周知的問題,但我什至沒有弄清楚如何在搜索中制定它,因為我正在尋找的一切都有點不同。 最好的方法是什么?
您可以使用scipy.ndimage.label到 label 連接區域並返回區域數,如@Mr.T 指出的那樣。 這可以用於創建用於索引和計數的 boolean 掩碼。
感謝@Mr.T go,因為他首先提出了類似的解決方案。 由於第二部分不同,這個答案仍然發布,我發現它更具可讀性並且在我的機器上快 40%。
import numpy as np
from scipy.ndimage import label
a = [[1,1,0,1],
[1,0,0,1],
[0,1,0,0]])
# Label connected regions, the second arg defines the connection structure
labeled, n_labels = label(a, np.ones((3,3)))
# Replace label value with the size of the connected region
b = np.zeros_like(labeled)
for i in range(1, n_labels+1):
target = (labeled==i)
b[target] = np.count_nonzero(target)
print(b)
output:
[[4 4 0 2]
[4 0 0 2]
[0 4 0 0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.