-1

I have an numpy array image which contain circles. I extracted the whole x,y centroids (in pixels) of these circles (a numpy array as well). Now, I want to crop a square around each x,y centroid. Can someone instruct me how to solve it? Note that I didn't find any question in Stack that deals with crop around a specific coordinate.

Thank you!

1 Answer 1

2

If your centroid has indices i,j and you want to crop a square of size 2*w+1 around it on a numpy array a, you can do

a[i-w:i+w+1,j-w:j+w+1]

This is provided your indices are always more than w from the boundary.

If they're not, you can do

imin = max(0,i-w)
imax = min(a.shape[0],i+w+1)
jmin = max(0,j-w)
jmax = min(a.shape[1],j+w+1) 
a[imin:imax,jmin:jmax]
1
  • there is a more efficient way to clip your indices at the border using np.where. You could read around on stack to find it somewhere. If you'd like to read about this generally the terminology is 'numpy slicing' Dec 13, 2018 at 22:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.