为Numpy数组的索引添加偏移量

时间:2013-12-17 12:12:33

标签: python arrays numpy stride

跟进这个问题(和jorgeca的回答): Fast Way to slice image into overlapping patches and merge patches to image我想在补丁数组的索引处添加一个偏移量,即:

A = np.arange(W*H).reshape(H,W)
P = patchify(A,(X,Y)) 

假设X,Y是奇数,P的大小将等于W-X + 1,H-Y + 1,因此以P [0,0]为中心的像素实际上对应于A [(Y -1)/ 2,(X-1)/ 2]。

有什么方法可以抵消(没有复制任何数据)P的指数以完美对应?

供参考,这是现有的补丁功能:

def patchify(img, patch_shape):
    img = np.ascontiguousarray(img)  # won't make a copy if not needed
    X, Y = img.shape
    x, y = patch_shape
    shape = ((X-x+1), (Y-y+1), x, y) # number of patches, patch_shape
    # The right strides can be thought by:
    # 1) Thinking of `img` as a chunk of memory in C order
    # 2) Asking how many items through that chunk of memory are needed when indices
    #    i,j,k,l are incremented by one
    strides = img.itemsize*np.array([Y, 1, Y, 1])
    return np.lib.stride_tricks.as_strided(img, shape=shape, strides=strides)

1 个答案:

答案 0 :(得分:0)

是以下表达式

P = np.roll(np.roll(P, X/2, 0), Y/2, 1)

你需要什么?

演示:

>>> W, H, X, Y =  10, 14, 5, 7
>>> A = np.arange(W*H).reshape(W,H)
>>> P = patchify(A,(X,Y))
>>> P = np.roll(np.roll(P, X/2, 0), Y/2, 1)
>>> all(map(all, P[X/2, Y/2] == A[:X, :Y]))
True