YohanRoth
YohanRoth

Reputation: 3263

Shift matrix such that given location in centered

You are given an nxn ndarray M and location (x, y) and the goal is to shift the values such that c = (x, y) is centered. Values that "fall outside" are removed and empty space is filled with zeros.

Example:

Input: 

M =

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

c = (0, 0)

Output:

0 0 0 0 0
0 0 0 0 0
0 0 1 1 1
0 0 2 2 2
0 0 3 3 3

c = (3, 4)
 
Output:

2 2 2 0 0 
3 3 3 0 0
4 4 4 0 0 
5 5 5 0 0 
0 0 0 0 0 

Is there any function for it in numpy/scipy or any other packages in python?

Thank you

Upvotes: 0

Views: 76

Answers (1)

Alain T.
Alain T.

Reputation: 42129

I don't know of a numpy function that does that directly, but you can easily write one:

def shift(M,c,r):
    w,h = M.shape
    return np.pad(M,((w,w),(h,h)),'constant')[w//2+1+c:,h//2+1+r:][:w,:h]

output:

m = np.arange(1,6)[:,None]*np.ones(5).astype(np.int)
print(m)

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]
 [5 5 5 5 5]]


print(shift(m,0,0))

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 1 1 1]
 [0 0 2 2 2]
 [0 0 3 3 3]]

print(shift(m,3,4))

[[2 2 2 0 0]
 [3 3 3 0 0]
 [4 4 4 0 0]
 [5 5 5 0 0]
 [0 0 0 0 0]]

Upvotes: 1

Related Questions