首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确定巨蟒中细胞的邻域为菱形

确定巨蟒中细胞的邻域为菱形
EN

Stack Overflow用户
提问于 2020-11-13 14:50:58
回答 3查看 151关注 0票数 0

我有一个大小为1的矩阵变量,其中1表示单元格,例如:

代码语言:javascript
复制
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,我想知道下面的列,行:

代码语言:javascript
复制
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解决方案。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-11-13 15:01:53

对于迭代方法,您只需构造菱形:

代码语言:javascript
复制
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 ret

get_neighbors((2, 2), 2)结果

代码语言:javascript
复制
[(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)]

或者,对于递归方法:

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2020-11-13 15:06:20

首先,我要取出一个“子矩阵”,它是可以包含结果单元格的最小方格。这是numpy应该能帮忙的部分。

然后定义一个函数,计算两个单元格(abs(x - x_p) + abs(y - y_p))之间的曼哈顿距离,并遍历子矩阵的单元格,并返回从原点起曼哈顿距离小于N的值。

票数 0
EN

Stack Overflow用户

发布于 2020-11-13 15:48:59

用rotation

  • Convolute细胞制作
  • 掩码和掩码
  • 修正结果

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64823023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档