在 numpy 数组上重复一个函数

Repeating a function on a numpy array

我正在尝试使两个 .tif 图像的图像形状匹配。

我的方法是在较小图像的底部添加空白切片,直到它们的 Z 轴堆栈数匹配(假设两个图像的 X 和 Y 都具有形状)。我首先将图像转换为 numpy 数组,然后使用 np.concatenate 在数组末尾添加一个带零的数组。

我的代码如下所示:

    x = 0
    difference = model.shape[1] - image.shape[1]

    # This line takes the difference between the larger image's Z stack 
    # slice number with the smaller image and get the difference between
    # their z stack slice number.

    while x <= difference: 
        new_np_array = np.concatenate((the_image_np_array, zeros_np_array), axis=0)
        x += 1

但是,这是行不通的,因为该程序基本上定义了同一个变量三次。我的问题是,如何在同一个数组上重复函数 (np.concatenate) X 次?

如果我理解正确的话,你必须将串联结果赋给数组本身。

  while x <= difference: 
        the_image_np_array = np.concatenate((the_image_np_array, zeros_np_array), axis=0)
        x += 1

我不确定我是否完全理解你想要完成的事情,但你是否考虑过将图像转换为 PIL 图像并使用 Image.resize 函数?

PIL Image docs

附加到列表并在末尾进行连接会更有效。而且更容易正确

alist = []
while x <= difference: 
    alist.append(zeros_np_array)
    x += 1
arr = np.array(alist)
# arr = np.vstack(alist) # alternative