![](/img/trans.png)
[英]Python Numpy. Delete an element (or elements) in a 2D array if said element is located between a pair of specified elements
[英]Python, Numpy. Find values in 2d array and replace neighbors with 1
我有一個 0 和 1 的 10x10 數組。
我想:
找到每個單元格的 position,其值為 1。
用1替換所有鄰居。鄰居=任何單元格到an=1距離(也是對角線)。 例子:
array([[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 1]])
output:
array([[1, 1, 1, 1, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
我正在嘗試查找索引,但它不起作用:
a=np.where(a==1)+1
從其他帖子中,我還嘗試使用此 function 獲取鄰居:
def n_closest(x,n,d=1):
return x[n[0]-d:n[0]+d+1,n[1]-d:n[1]+d+1]
但這不適用於邊緣
謝謝
如果您不介意使用scipy
,二維卷積將很快解決問題:
import numpy as np
from scipy import signal
# Input array
X = np.array([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 1]])
# We apply a 2D convolution with a 3x3 kernel and we check which value are bigger than 0.
R = (signal.convolve2d(X,np.ones((3,3)),mode='same')>0).astype(int)
# R = array([[1, 1, 1, 0, 0],
# [1, 1, 1, 1, 0],
# [1, 1, 1, 1, 0],
# [1, 1, 1, 1, 1],
# [1, 1, 1, 1, 1]])
# Finally we extract the index
x,y = np.where(R)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.