这里有一个小类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)