python邻域数组(moore索引)

2024-04-28 14:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

主要问题是当我print cells[i-1][j]for i = 2j = 1时,它应该返回1,但是它说有0。我想计算每个单元的邻域数,但这不能正常工作,但应该这样做。在

我有一个3x3矩阵,添加额外的零边以避免数组外,然后在我的原始区域上有2个for循环,用值来计算邻域。但是这个计数被打破了。在

import numpy as np
def get_generation(cells, generations):
cells=np.array(cells)
for k in range(generations):

    cells=np.c_[np.zeros(cells.shape[0]), cells,np.zeros(cells.shape[0])]
    cells=np.r_[[np.zeros(cells.shape[1])], cells, np.zeros(cells.shape[1])]]

    for i in range(1, cells.shape[0]-1):     #vertical
        for j in range(1, cells.shape[1]-1):     #horizontal
            neighbours=0
            neighbours+=sum(cells[i-1][j-1:j+2])
            print neighbors, cells[i-1][j-1], cells[i-1][j], cells[i-1][j+1]
            print i, j
            neighbours+=sum(cells[i+1][j-1:j+2])
            neighbours+=cells[i][j-1]
            neighbours+=cells[i][j+1]
    return cells

start = [[1,0,0],
         [0,1,1],
         [1,1,0]]

get_generation(start, 1)

Tags: inforgetnpzerosrangestartgeneration
1条回答
网友
1楼 · 发布于 2024-04-28 14:26:01

您可能应该在helper函数中提取邻域的总和,在该函数中可以使用try except块来避免测试数组的边界:

有人这样想,也许:

import numpy as np


MOORE_OFFSETS = [(1, 1), (1, -1), (1, 0), (-1, 0), (-1, 1), (-1, -1), (0, 1), (0, -1)]


def get_moore_neighbors_sum(array_of_arrays, row, col):
    sum_neighbors = 0
    for neighbor in MOORE_OFFSETS:
        dr, dc = neighbor
        try:
            if row + dr >= 0 and col + dc >= 0:
                sum_neighbors += array_of_arrays[row+dr][col+dc]
        except IndexError:
            continue
    return sum_neighbors


array_of_arrays = # a sequence of sequence of your data
rows = len(array_of_arrays)
cols = len(array_of_arrays[0])

for row in range(rows):
    for col in range(cols):

        sum_neighbors = get_moore_neighbors_sum(array_of_arrays, row, col)

相关问题 更多 >