【问题标题】:Fail to convert List of ndarrays to numpy array无法将 ndarray 列表转换为 numpy 数组
【发布时间】:2017-10-05 09:03:30
【问题描述】:

我正在以 numpy ndarray 的形式一张一张地读取数千张图像(所有三个通道),并将它们附加到一个列表中。最后,我想将此列表转换为 numpy 数组:

import numpy as np
from PIL import Image

def read_image_path(path, img_size=227):
    img = Image.open(path)
    img = np.array(img.resize([img_size, img_size]))
    return img

我从字典中读取每个图像路径,如下所示:

{1:{'img_path': 'path-to-image', 'someOtherKeys':'...'}, 2:{...}}

images = []
for key in key:
    img = read_image_path(dataset_dictionary[key]['img_path'])
    images.append(img)

到这里一切都很好。我有一个大小为 (227,227,3) 的 ndarray 图像矩阵列表。但是当我尝试将“图像”转换为 numpy 数组并从函数中返回时,会出现以下错误:

return np.array(images)

返回 np.array(图像)

ValueError: 无法将输入数组从形状 (227,227,3) 广播到形状 (227,227)

如果有人对此有任何想法,我将不胜感激。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您很可能有一个形状为 (227,227) 而不是 (227,227,3) 的 img(或图像)。

    下面的代码应该告诉你哪个图像是违规者。

    for key in key:
        img = read_image_path(dataset_dictionary[key]['img_path'])
        if img.shape != (227,227,3):
                print(key)
    

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 2017-03-08
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多