![](/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.