Skip to content Skip to sidebar Skip to footer

Slicing A 20×20 Area Around Known Indices (x, Y) In A Numpy Array

I have a large 2D numpy array for which I know a pair of indices which represent one element of the array. I want to set this element and the surrounding 20×20 area equal to zero;

Solution 1:

my_array[x - 10:x + 10, y - 10:y + 10] = 0

or

s = my_array[x - 10:x + 10, y - 10:y + 10]
s[:] = 0

Solution 2:

I believe you mean array[x:x+10,y:y+10]

Solution 3:

You select multiple elements of an array A with A[start:stop] where start and stop are zero-based indices. For a 2D Array this applies as well: A[start1:stop1, start2:stop2].

With the following script

import numpy as npA= np.ones((5,5))

A looks like this

[[ 1.  1.  1.  1.  1.][ 1.  1.  1.  1.  1.][ 1.  1.  1.  1.  1.][ 1.  1.  1.  1.  1.][ 1.  1.  1.  1.  1.]]

with

A[1:4,1:4] = 0

you get

[[ 1.  1.  1.  1.  1.][ 1.  0.  0.  0.  1.][ 1.  0.  0.  0.  1.][ 1.  0.  0.  0.  1.][ 1.  1.  1.  1.  1.]]

Solution 4:

Note that for the block of zeros to be centered on your x,y coordinates, it must be of odd size. For instance, the block of zeros in the following is not centered the coordinates x,y = 4,6 but on the center coordinates of that cell, that is x, y = 4.5, 5.5:

import numpy

a = numpy.ones((10,10))
x,y = 4,6
s = 2
a[x - s: x + s, y-s: y + s] = 0

array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])

whereas this one is:

a = numpy.ones((10,10))
x,y = 4,6
s = 2
a[x - s: x + s + 1, y-s: y + s + 1] = 0print a

array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])

If the script is for pixel based image processing, this could be an important distinction.

Post a Comment for "Slicing A 20×20 Area Around Known Indices (x, Y) In A Numpy Array"