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?
arr[0][-1]willraiseanIndexError, when it will actuallyreturn 1(the last value of the first row). This indexing operation will return something for any negative number up to -5, which I think is not the intended behavior, given your code.