首页 > 解决方案 > 填充多个数组以获得与最大数组相同的形状

问题描述

我有多个二维数组保存在一个名为的列表中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]))

我不明白为什么这种情况下形状没有改变。而且,有没有一种方法可以轻松地概括这一点,以便它可以在许多数组上工作,无论它们是偶数还是奇数维度?

标签: pythonarrayspython-3.xnumpypad

解决方案


np.pad不会就地修改数组,它会返回一个填充数组。所以你需要做image_concat[i] = np.pad(...)i的索引在哪里A


推荐阅读