numpy blit (copy part of an array to another one with a different size)
arrays, numpy, opencv, python
Solution
You could just compute the appropriate slices:
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)))
yields
[[ 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.]]
and
print(blit(np.zeros((7,7)), np.ones((3,3)), (-1, -1)))
yields
[[ 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.]]
Problem
I want to copy one array to another one with a different size. I would like a function like this: ``` blit(destimg,src,dstlocation) ``` for example `blit(zeros((7,7)),ones((3,3)),(4,4))` would result in ``` 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.]]) ``` The top left center of array `src` is now in the location `(4,4)` of the array `destimg`. if I did `blit(zeros((7,7)),ones((3,3)),(5,5))` I would get: ``` 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.]]) ``` The array `src` doesn't fit in the `destimg` but its top left corner is still in the right position.