在 Python 中检查矩阵中的邻居时禁用负索引

Disable negative indexing when checking neighbours in a matrix in Python

所以我有以下给定输入的代码:

import numpy as np

x = np.matrix([[1,1,1,1,0],
               [1,1,1,0,0],
               [1,1,0,0,0],
               [1,0,0,0,0]])
print(x)

def MIZ(mat,check):
    for j in range(0,mat.shape[0]):
        for i in range(0,mat.shape[1]):
            try:
                if mat[i,j] == 1:
                    if mat[i+check,j] == 0 or \
                       mat[i-check,j] == 0 or \
                       mat[i,j+check] == 0 or \
                       mat[i,j-check] == 0:
                           mat[i,j] = 2
            except:
                pass
    return mat
            
print(MIZ(x,1))

这个想法很简单;因为所有位于 0 旁边的 1 都被转换为 2。这里的“check”参数理想情况下应该是可调的,这样如果“check=2”1s 有一个 0 a space 也被转换为 2,等等。现在问题出现在矩阵中的第一个元素(索引 = 0,0),因为那时 i-1 和 j-1 都是 -1 并且为了我的目的我想避免这种情况并将它限制为仅周围元素。

当前代码结果为:

[[2 2 2 2 0]
 [2 1 2 0 0]
 [2 2 0 0 0]
 [1 0 0 0 0]]

还有最下面的 1 没有转换为 2 的问题,但这是次要问题。

您可以在索引之前检查您是否在范围内。 就像那样(顺便说一下,我在循环中更改了 ij):

def in_range(index, range_length):
    return -range_length <= index <= range_length -1


def MIZ(mat, check):
    for i in range(0, mat.shape[0]):
        for j in range(0, mat.shape[1]):
            if mat[i, j] == 1:
                if (in_range(i+check, mat.shape[0]) and mat[i + check, j] == 0) or \
                   (in_range(i-check, mat.shape[0]) and mat[i - check, j] == 0) or \
                    (in_range(j + check, mat.shape[1]) and mat[i, j + check] == 0) or \
                    (in_range(j - check, mat.shape[1]) and mat[i, j - check] == 0):
                    mat[i, j] = 2
    return mat

print(MIZ(x, 1))

输入:

x = np.array([[1,1,1,1,0],
               [1,1,1,0,0],
               [1,1,0,0,0],
               [1,0,0,0,0]])

输出:

[[2 2 2 2 0]
 [2 1 2 0 0]
 [2 2 0 0 0]
 [2 0 0 0 0]]

编辑,更改“in_range”函数应该使您只按需要访问非负索引:

def in_range(index, range_length):
    return 0 <= index <= range_length -1

输入:

x = np.array([[1,1,1,1,0],
               [1,1,1,0,0],
               [1,1,0,0,0],
               [1,0,0,0,0]])

输出:

[[1 1 1 2 0]
 [1 1 2 0 0]
 [1 2 0 0 0]
 [2 0 0 0 0]]

我一直没能找到任何干净的解决方案,但这确实有效。 Max(0, value) 也是可能的,但是如果你有一个负值,它会选择 0,它本身就是一个索引。

# Function
def no_neg(value):
    if value >= 0:
        return value
    else:
        raise IndexError
        

在您的代码中,它看起来像这样。 将 numpy 导入为 np

x = np.matrix([[1,1,1,1,0],
               [1,1,1,0,0],
               [1,1,0,0,0],
               [1,0,0,0,0]])
print(x)

def MIZ(mat,check):
    for j in range(0,mat.shape[0]):
        for i in range(0,mat.shape[1]):
            try:
                if mat[i,j] == 1:
                    if mat[no_neg(i+check),no_neg(j)] == 0 or \
                       mat[no_neg(i-check),no_neg(j)] == 0 or \
                       mat[no_neg(i),no_neg(j+check)] == 0 or \
                       mat[no_neg(i),no_neg(j-check)] == 0:
                           mat[i,j] = 2
            except:
                pass
    return mat
            
print(MIZ(x,1))