python numpy切片_如何将Numpy数组切片到边界?

这里有一个小类Box,使使用更方便盒 -

from __future__ import division

import numpy as np

class Box:

""" B = Box(2d numpy array A, radius=2)

B.box(j, k) is a box A[ jk - 2 : jk + 2 ] clipped to the edges of A

@askewchan, use np.pad (new in numpy 1.7):

padA = np.pad(A, pad_width, mode="constant", edge=-1)

B = Box(padA, radius)

"""

def __init__(self, A, radius):

self.A = np.asanyarray(A)

self.radius = radius

def box(self, j, k):

""" b.box(j, k): square around j, k clipped to the edges of A """

return self.A[ self.box_slice(j, k)]

def box_slice(self, j, k):

""" square, jk-r : jk+r clipped to A.shape """

# or np.clip ?

r = self.radius

return np.s_[ max(j - r, 0) : min(j + r + 1, self.A.shape[0]),

max(k - r, 0) : min(k + r + 1, self.A.shape[1])]

#...............................................................................

if __name__ == "__main__":

A = np.arange(5*7).reshape((5,7))

print "A:\n", A

B = Box(A, radius=2)

print "B.box(0, 0):\n", B.box(0, 0)

print "B.box(0, 1):\n", B.box(0, 1)

print "B.box(1, 2):\n", B.box(1, 2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值