【问题标题】:Shift matrix such that given location in centered移动矩阵,使给定位置居中
【发布时间】:2021-02-23 12:30:48
【问题描述】:

给您一个nxn ndarray M 和位置(x, y),目标是移动这些值,使c = (x, y) 居中。 “落在外面”的值被删除,空白处用零填充。

例子:

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 

在 numpy/scipy 或 python 中的任何其他包中是否有任何功能?

谢谢

【问题讨论】:

  • 第二个输出,你的意思是c=(3,4)吗?无论如何,我认为不会有专门针对此的功能。当然,很高兴被证明是错误的。
  • @QuangHoang 是的,对不起

标签: python numpy


【解决方案1】:

我不知道直接执行此操作的 numpy 函数,但您可以轻松编写一个:

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]

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多