附加NumPy数组时,列表丢失形状

时间:2019-09-30 23:36:59

标签: python arrays numpy

我正在使用PIL加载图像,然后将其转换为NumPy数组。然后,我必须基于图像列表创建一个新图像,因此我将所有theearray附加到列表中,然后将列表转换回数组,因此图像列表的形状具有4个维度(n_images,height,宽度,rgb_channels)。我正在使用以下代码:

def gallery(array, ncols=4):

    nindex, height, width, intensity = array.shape
    nrows = nindex // ncols
    # want result.shape = (height*nrows, width*ncols, intensity)

    result = (array.reshape(nrows, ncols, height, width, intensity)
              .swapaxes(1,2)
              .reshape(height*nrows, width*ncols, intensity))
    return result

def make_array(dim_x):
        for i in range(dim_x):
           print('series',i) 
           series = []
           for j in range(TIME_STEP-1):
              print('photo',j)
              aux = np.asarray(Image.open(dirpath+'/images/pre_images /series_{0}_Xquakemap_{1}.jpg'.format(i,j)).convert('RGB'))
              print(np.shape(aux))
              series.append(aux)
              print(np.shape(series))

        im = Image.fromarray(gallery(np.array(series)))
        im.save(dirpath+'/images/gallery/series_{0}_Xquakemap.jpg'.format(i))
        im_shape = (im.size)

make_array(n_photos)
# n_photos is the total of photos in the dirpath

问题是当series列表上的追加发生时,图像的形状(添加了NumPy数组)丢失了。因此,当尝试重整函数gallery中的数组时,会引起问题。上面代码的输出摘要如下:

...

series 2
photo 0
(585, 619, 3)
(1, 585, 619, 3)
photo 1
(587, 621, 3)
(2,)
photo 2
(587, 621, 3)
(3,)
photo 3
(587, 621, 3)
(4,)
...

如您所见,添加第二张照片时,列表失去了尺寸。这很奇怪,因为代码在前两次迭代中使用了相同的图像。我尝试使用np.stack(),但错误普遍存在。

我也在Github上找到了这个issue,但我认为即使行为相似,它也不适用于这种情况。

在Ubuntu 18,Python 3.7.3和Numpy 1.16.2上工作。

编辑:添加了@kwinkunks的要求

1 个答案:

答案 0 :(得分:0)

在第二个功能中,我认为您需要将series = []移动到外循环之前。

这是我对问题的再现:

import numpy as np
from PIL import Image

TIME_STEP = 3

def gallery(array, ncols=4):
    """Stitch images together."""
    nindex, height, width, intensity = array.shape
    nrows = nindex // ncols
    result = array.reshape(nrows, ncols, height, width, intensity)
    result = result.swapaxes(1,2)
    result = result.reshape(height*nrows, width*ncols, intensity)
    return result

def make_array(dim_x):
    """Make an image from a list of arrays."""
    series = []  # <<<<<<<<<<< This is the line you need to check.
    for i in range(dim_x):
        for j in range(TIME_STEP - 1):
            aux = np.ones((100, 100, 3)) * np.random.randint(0, 256, 3)
            series.append(aux.astype(np.uint8))

    im = Image.fromarray(gallery(np.array(series)))

    return im

make_array(4)

结果是:

The output: lots of squares