python(摩尔邻里)中的索引数组

时间:2018-08-06 16:56:38

标签: python numpy

主要问题是当我print cells[i-1][j]分别为i = 2j = 1时,它应该返回1,但它表示有0。我想对每个单元的邻域进行计数,但这并没有不能正常工作---但是应该。

我有一个3 x 3的矩阵,添加带有零的多余边以免超出数组,然后在我的原始区域上进行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)

1 个答案:

答案 0 :(得分:0)

您可能应该在辅助函数中提取邻居的总和,在其中可以使用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)