Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

python - How can I create a slice object for Numpy array?

I've tried to find a neat solution to this, but I'm slicing several 2D arrays of the same shape in the same manner. I've tidied it up as much as I can by defining a list containing the 'x,y' center e.g. cpix = [161, 134] What I'd like to do is instead of having to write out the slice three times like so:

a1 = array1[cpix[1]-50:cpix[1]+50, cpix[0]-50:cpix[0]+50] 
a2 = array2[cpix[1]-50:cpix[1]+50, cpix[0]-50:cpix[0]+50] 
a3 = array3[cpix[1]-50:cpix[1]+50, cpix[0]-50:cpix[0]+50]

is just have something predefined (like maybe a mask?) so I can just do a

a1 = array1[predefined_2dslice] 
a2 = array2[predefined_2dslice] 
a3 = array3[predefined_2dslice] 

Is this something that numpy supports?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can use numpy.s_:

Example:

>>> a = np.arange(10).reshape(2, 5)
>>> 
>>> m = np.s_[0:2, 3:4]
>>> 
>>> a[m]
array([[3],
       [8]])

And in this case:

my_slice = np.s_[cpix[1]-50:cpix[1]+50, cpix[0]-50:cpix[0]+50]

a1 = array1[my_slice] 
a2 = array2[my_slice] 
a3 = array3[my_slice]

You can also use numpy.r_ in order to translates slice objects to concatenation along the first axis.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...