我有一个大小为1的矩阵变量,其中1表示单元格,例如:
Cells = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
]我需要找到一个参数大小的钻石形状的邻居。不是一个框作为答案给出的here或不是一个固定大小的1钻石,答案给定here。例如,N=2,我想知道下面的列,行:
Mask = [[0,0,1,0,0],
[0,1,1,1,0],
[1,1,0,1,1],
[0,1,1,1,0],
[0,0,1,0,0],
]函数应该接收被请求的列和行的x和y,(对于上面我将输入2,2)和N(输入2)菱形的大小。函数应该返回给定钻石大小的元组列表(x,y)。
我很难把形状定义为x,y和k的函数,在for循环中。我需要知道numpy (如果有任何帮助)和非numpy解决方案。
发布于 2020-11-13 15:01:53
对于迭代方法,您只需构造菱形:
def get_neighbors(center, n=1):
ret = []
for dx in range(-n, n + 1):
ydiff = n - abs(dx)
for dy in range(-ydiff, ydiff + 1):
ret.append((center[0] + dx, center[1] + dy))
return retget_neighbors((2, 2), 2)结果
[(0, 2), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (4, 2)]或者,对于递归方法:
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def add_tuples(a, b):
return tuple([x + y for (x, y) in zip(a, b)])
def get_neighbors(center, n=1, seen=set()):
seen.add(center)
if n <= 0:
return seen
for dir in dirs:
newpos = add_tuples(center, dir)
if newpos in seen:
continue
get_neighbors(newpos, n - 1, seen)
return seen发布于 2020-11-13 15:06:20
首先,我要取出一个“子矩阵”,它是可以包含结果单元格的最小方格。这是numpy应该能帮忙的部分。
然后定义一个函数,计算两个单元格(abs(x - x_p) + abs(y - y_p))之间的曼哈顿距离,并遍历子矩阵的单元格,并返回从原点起曼哈顿距离小于N的值。
发布于 2020-11-13 15:48:59
用rotation



import numpy as np
from scipy.ndimage import rotate, convolve
import matplotlib.pyplot as plt
def diamond_filter(radius):
s = radius * 2 + 1
x = np.ones((s, s), dtype=int)
x[radius, radius] = 0
return rotate(x, angle=45)
def make_diamonds(x, radius):
filter = diamond_filter(radius)
out = convolve(x, filter)
out[out > 1] = 1
out -= x
out[out < 0] = 0
return out
def plot(x):
plt.imshow(x)
plt.show()
plt.close()
def main():
cell = np.random.choice([0, 1], size=(200, 200), p=[0.95, 0.05])
plot(diamond_filter(2))
plot(cell)
result = make_diamonds(cell, 2)
plot(result)
if __name__ == '__main__':
main()https://stackoverflow.com/questions/64823023
复制相似问题