Add Offset to Indices of Numpy Array

3k views Asked by At

Following up to this question (and jorgeca's answer): Fast Way to slice image into overlapping patches and merge patches to image I want to add an offset to the indices of the patchified array, i.e:

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

Assuming X,Y are odd numbers, the size of P will be equal to W-X+1,H-Y+1, hence the pixel centered in P[0,0] will actually correspond to A[(Y-1)/2,(X-1)/2].

Is there any way I can offset (without copying any data) the indices of P to have perfect correspondence?

For reference, here is the existing patchify function:

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

There are 1 answers

0
alko On

Is following expression

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

what you need?

Demo:

>>> 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