我想将一个数组复制到另一个大小不同的数组。 我想要这样的功能:
blit(destimg,src,dstlocation)
例如 blit(zeros((7,7)),ones((3,3)),(4,4))
会导致
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 1., 1.],
[ 0., 0., 0., 0., 1., 1., 1.],
[ 0., 0., 0., 0., 1., 1., 1.]])
数组 src
的左上中心现在位于数组 destimg
的位置 (4,4)
。
如果我执行 blit(zeros((7,7)),ones((3,3)),(5,5))
我会得到:
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 1.],
[ 0., 0., 0., 0., 0., 1., 1.]])
数组 src
不适合 destimg
但它的左上角仍然在正确的位置。
最佳答案
您可以只计算适当的切片:
import numpy as np
def blit(dest, src, loc):
pos = [i if i >= 0 else None for i in loc]
neg = [-i if i < 0 else None for i in loc]
target = dest[[slice(i,None) for i in pos]]
src = src[[slice(i, j) for i,j in zip(neg, target.shape)]]
target[[slice(None, i) for i in src.shape]] = src
return dest
print(blit(np.zeros((7,7)), np.ones((3,3)), (5, 5)))
产量
[[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 1. 1.]
[ 0. 0. 0. 0. 0. 1. 1.]]
和
print(blit(np.zeros((7,7)), np.ones((3,3)), (-1, -1)))
产量
[[ 1. 1. 0. 0. 0. 0. 0.]
[ 1. 1. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0.]]
关于python - numpy blit(将数组的一部分复制到另一个具有不同大小的数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676187/