填充多个数组以获得与最大数组相同的形状



我有多个2D数组保存在一个名为image_concat的列表中。这个列表将由一百多个这样的数组组成,但现在我只是想让我的代码为一个只有两个数组的列表运行。这些数组都有不同的形状,我想在所有数组中找到最大的x维度和最大的y维度,然后在所有其他数组的边缘加上足够的零,这样最后它们都有相同的形状。请注意,最大的x维度和最大的y维度可能属于单独的数组,也可能属于同一个数组。到目前为止,由于某种原因,我尝试写的并没有成功地改变较小阵列的形状。但我也认为,即使在改变形状后,也会出现一些问题,因为由于形状中的元素是偶数或奇数,一些阵列最终可能会偏离一个。

import astropy
import numpy as np
import math
import matplotlib.pyplot as plt
from astropy.utils.data import download_file
from astropy.io import fits
images = ['http://irsa.ipac.caltech.edu/ibe/data/wise/allsky/4band_p1bm_frm/9a/02729a/148/02729a148-w2-int-1b.fits?center=89.353536,37.643864deg&size=0.6deg', 'http://irsa.ipac.caltech.edu/ibe/data/wise/allsky/4band_p1bm_frm/2a/03652a/123/03652a123-w4-int-1b.fits?center=294.772333,-19.747157deg&size=0.6deg']
image_list = []
for url in images:
image_list.append(download_file(url, cache=True))
image_concat = [fits.getdata(image) for image in image_list]
# See shapes in the beginning
print(np.shape(image_concat[0]))
print(np.shape(image_concat[1]))
def pad(image_concat):
# Identify largest x and y dimensions
xdims, ydims = np.zeros(len(image_concat)), np.zeros(len(image_concat))
for i in range(len(xdims)):
x, y = np.shape(image_concat[i])
xdims[i] = x
ydims[i] = y
x_max = int(np.max(xdims))
y_max = int(np.max(ydims))
# Pad all arrays except the largest dimensions
for A in image_concat:
x_len, y_len = np.shape(A)
print(math.ceil((y_max-y_len)/2))
print(math.ceil((x_max-x_len)/2))
np.pad(A, ((math.ceil((y_max-y_len)/2), math.ceil((y_max-y_len)/2)), (math.ceil((x_max-x_len)/2), math.ceil((x_max-x_len)/2))), 'constant', constant_values=0)
return image_concat
image_concat = pad(image_concat)
# See shapes afterwards (they haven't changed for some reason)
print(np.shape(image_concat[0]))
print(np.shape(image_concat[1]))

我不明白为什么这个案子的形状没有改变。还有,有没有一种方法可以很容易地推广这一点,使其适用于许多数组,无论它们是偶数维还是奇数维?

np.pad不会在适当的位置修改数组,而是返回一个填充数组。所以你需要做image_concat[i] = np.pad(...),其中iA的索引。

最新更新