2

I've a square numpy array and I would like to extract the values from an annulus region around the central point of the array. I would like to set the radii of the annulus based on the distance of the points from the center. I retrieved the array indices by using numpy.indices but could not mange to find an efficient way to construct the filter. I'll appreciate if you share your comments/suggestions.

indices = numpy.indices((5, 5))
print indices
[[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]

[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]]

Now I want to extract the values of those points whose indices are at a distance of say, 1 from the central point i.e. (2,2).

rana
  • 1,041
  • 2
  • 11
  • 16
  • So what would the result look like? – NPE Oct 30 '13 at 17:27
  • @Ophion i searched this site before posting this question. but did not find this question you are pointing to. thanks for the link. however, the answer provided below gives a simple and straightforward answer to my question and thats really helpful for a non-programmer like me. thanks again for referring to a similar question – rana Oct 30 '13 at 19:45

1 Answers1

2
pt = (2, 2)
distance = 1
mask = (indices[0] - pt[0]) ** 2 + (indices[1] - pt[1]) ** 2 <= distance ** 2
result = my_array[mask]
YXD
  • 31,741
  • 15
  • 75
  • 115
  • 1
    Another way, `mask = np.hypot(*(indices - pt[:,None,None])) <= distance`, which isn't quite as simple as I thought it would be :P – askewchan Oct 30 '13 at 17:46
  • Sweet, didn't know about `hypot` :) – YXD Oct 30 '13 at 17:49
  • 1
    Check out the other thread- This can be improved by using `ogrid` over `np.indices`, this can save large amounts of time. While this does not return indices at the very least it should give you a starting point that you can add the center to. – Daniel Oct 30 '13 at 18:00