0

I want to apply a circular mask to all elements in a numpy array with specific values. At the moment my (example) code looks like this:

import numpy as np

n = 14
r = 3 #radius
### example array ###
array = np.zeros((n, n)) 
array[2,:]=1
array[:,5]=1
array[5,:]=1
array[:,9] = 3
a, b = np.where((array == 1) | (array == 3))
print(array)

### applying mask ###
for i in range(a.size-1):
    y,x = np.ogrid[-a[i]:np.size(array, 0)-a[i], -b[i]:np.size(array, 1)-b[i]]
    mask = x*x + y*y <= r*r
    array[(mask) & (array != 1) & (array != 3)] = 255 # setting elements in neighborhood of 1 and 3 to 255
print(array)

The code works as I want it but my real data is much bigger and the algorithm is very slow. At the moment every point/mask gets evaluated one after another (for loop). Is there a way to create a mask for all 1 and 3 (in this example) at one time?

clearseplex
  • 679
  • 1
  • 7
  • 22

0 Answers0