ELD
ELD

Reputation: 177

Store indices of neighbouring cells which fall within a certain radius

I have a very large numpy array of 1s and 0s. I want to go row by row and look for all the 1s. Once I encounter a 1, I want to store the indices of entries which fall inside a radius of five rows. This is better illustrated in the picture:

enter image description here

(in the picture I only show half a circle, in the real case I need the indices of the values that fall inside the entire circle) Once I collect the indices, I go to the next 1 in the array and do the same. Once I finish looping through the array I want to set all the values of the collected indices which are not 1 to 1. In a sense, I am creating a buffer around all 1s with a radius of 5 columns.

for row in myarray: 
    for column in myarray:
        dist = math.sqrt(row**2+column**2) 
        if dist <= 5  
        .........store the indices of the neighbouring cells 

Can you please give me a suggestion how to accomplish this? enter image description here

Upvotes: 2

Views: 132

Answers (1)

unutbu
unutbu

Reputation: 879849

The operation you are describing is called dilation. I you have scipy, you could use ndimage.binary_dilation to obtain the result:

import numpy as np
import scipy.ndimage as ndimage
import matplotlib.pyplot as plt

arr = np.zeros((21, 21))
arr[5, 5] = arr[15, 15] = 1

i, j = np.ogrid[:11, :11]
# struct = ((i-5)**2 + (j-5)**2 <= 40)
struct = np.abs(i-5)+ np.abs(j-5) <= 8

result = ndimage.binary_dilation(arr, structure=struct)
plt.imshow(result, interpolation='nearest')
plt.show()

enter image description here

Upvotes: 2

Related Questions