Вот подход, использующий np.pad
, который можно обобщить для произвольной формы цели:
def to_shape(a, shape):
y_, x_ = shape
y, x = a.shape
y_pad = (y_-y)
x_pad = (x_-x)
return np.pad(a,((y_pad//2, y_pad//2 + y_pad%2),
(x_pad//2, x_pad//2 + x_pad%2)),
mode = 'constant')
Для предложенного примера:
a = np.ones((41,13))
shape = [93, 13]
to_shape(a, shape).shape
# (93, 13)
Давайте посмотрим на другой пример:
shape = [100, 121]
to_shape(a, shape).shape
# (100, 121)
Сроки
def florian(array, shape):
#print(array)
testarray = np.zeros(shape)
for index,row in enumerate(array):
for i in range(0,len(row)-1):
testarray[index][i]= row[i]
def to_shape(a, shape):
y_, x_ = shape
y, x = a.shape
y_pad = (y_-y)
x_pad = (x_-x)
return np.pad(a,((y_pad//2, y_pad//2 + y_pad%2),
(x_pad//2, x_pad//2 + x_pad%2)),
mode = 'constant')
a = np.ones((500, 500))
shape = [1000, 1103]
%timeit florian(a, shape)
# 101 ms ± 5.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit to_shape(a, shape)
# 19.8 ms ± 318 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)