1

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)
Community
  • 1
  • 1
memecs
  • 7,196
  • 7
  • 34
  • 49
  • 1
    For example, say `W, H, X, Y = (10, 14, 4, 7)`, `P.shape` will be `(11, 4, 4, 7)`, how do you wan't to offset and what? – alko Dec 17 '13 at 12:24
  • Just corrected, the size of X,Y has to be odd. Let consider W,H,X,Y = (10,14,5,7), P.shape will be (6,8,5,7), I want to access P[0,0] as P[2,3] – memecs Dec 17 '13 at 12:42
  • then P.shape is (10, 4, 5, 7), hence P[0,0].shape is (5, 7), it's left upper A's subarray of 5x7 size. Still unclear what you want – alko Dec 17 '13 at 12:46
  • I don't understand why you say P.shape is (10,4,5,7)? P.shape should be (6,8,5,7). I want to be able to change the memory layout or anything else it would allow me to type P[2,3] and get what is now P[0,0] i.e. the 5.7 subarray centered in A[2,3] – memecs Dec 17 '13 at 12:51
  • You mix W and H if you want 6,8. And what would be P[0,0] value in that case? – alko Dec 17 '13 at 13:17
  • It doesn't matter, might be an out-of-bound error or wrap around as it would with P[-1,-1] – memecs Dec 17 '13 at 14:24

1 Answers1

0

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    
alko
  • 46,136
  • 12
  • 94
  • 102