简体   繁体   English

Python 2D数组处理

[英]Python 2D array processing

I have an input array of the form 我有形式的输入数组

1 0 0 0 1
1 1 1 0 0
1 0 0 0 0
0 0 0 1 1
0 1 0 0 0

I want to calculate the density map and get output in the form (summing up all the values around a value including the value) 我想计算密度图并以表格形式输出(汇总包含该值的值周围的所有值)

3 4 2 2 1
4 5 2 2 1
3 4 3 3 2
2 2 2 2 2
1 1 2 2 2

import numpy as np

def get_value(arr,i,j):
    """
    This function will return the value at the index if present. If list index out of range, it will return 0
    """
    try:
        return arr[i][j]
    except:
        return 0

#input array
arr = [[1, 0, 0, 0, 1],
 [1, 1, 1, 0, 0],
 [1, 0, 0, 0, 0],
 [0, 0, 0, 1, 1],
 [0, 1, 0, 0, 0]]

np_arr = np.array(arr) # converting to numpy array

r =1 # initializing the radius r as 1
n =5 # initializing the size of the input matrix as 5
np_arr_result = np.zeros(shape=(5,5)) # initializing the output array

for i in range(0,5):
    for j in range(0,5):
        np_arr_result[i][j] = get_value(np_arr,i,j) + get_value(np_arr,i-r,j-r) + get_value(np_arr,i-r,j)  + get_value(np_arr,i-r,j+r) + get_value(np_arr,i,j-r)  + get_value(np_arr, i, j+r) + get_value(np_arr, i+r, j-r) + get_value(np_arr, i+r, j) + get_value(np_arr, i+r, j+r)

print("output")
print(np_arr_result)

However, I am not getting the right output and getting the result as: 但是,我没有得到正确的输出并将结果显示为:

output
[[ 5.  5.  3.  2.  1.]
 [ 5.  5.  2.  2.  1.]
 [ 4.  4.  3.  3.  2.]
 [ 3.  2.  2.  2.  2.]
 [ 2.  1.  2.  2.  2.]]

What could have gone wrong? 可能出了什么问题?

This is a perfect task for a 2D convolution: 对于2D卷积来说,这是一项完美的任务:

data = numpy.array([
    [1, 0, 0, 0, 1],
    [1, 1, 1, 0, 0],
    [1, 0, 0, 0, 0],
    [0, 0, 0, 1, 1],
    [0, 1, 0, 0, 0],
])

kernel = numpy.ones((3, 3), dtype=data.dtype)
# array([[1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1]])

scipy.signal.convolve2d(data, kernel, mode='same')
# array([[3, 4, 2, 2, 1],
#        [4, 5, 2, 2, 1],
#        [3, 4, 3, 3, 2],
#        [2, 2, 2, 2, 2],
#        [1, 1, 2, 2, 2]])

That is because for numpy, the index -1 is for the last element, so it will not assert IndexError. 这是因为对于numpy,索引-1用于最后一个元素,因此它不会断言IndexError。

just modify the get_value() function as : 只需将get_value()函数修改为:

def get_value(arr,i,j):
    """
    This function will return the value at the index if present. If list index out of range, it will return 0
    """
    if (i>-1 and j >-1 and i < arr.shape[0] and j < arr.shape[1]):
        return arr[i][j]
    else:
        return 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM