【问题标题】:Python PIL(Pillow): Convert a list of images into np.array efficiently?Python PIL(Pillow):有效地将图像列表转换为 np.array?
【发布时间】:2018-06-13 22:08:00
【问题描述】:

我想有效地将​​图像列表转换为 np.array。

我必须处理一些用PIL.Image.open(img_path)读取的jpg图像,我必须处理每一个,然后我想把它们全部放入一个列表中,然后将它完全转换为我的形状的np.array想要,(N,H,W,C),分别表示number of imgheightwidthchannel

我的尝试:

all_img = []

for filename in all_filename_of_img[:100]:
    // process each img

    // then append each into the list
    all_img.append(img)

all_np_img = np.arrray(all_img, dtype=np.array)

有错误:

Traceback (most recent call last):
  File ".../playground.py", line 39, in <module>
    all_np_img = np.array(all_img, dtype=np.array)
TypeError: data type not understood

如果我首先通过img = np.asarray(img) 转换for 循环内的每个img,然后再做all_img.append(img),这是正确的方法吗?

【问题讨论】:

    标签: python numpy python-imaging-library


    【解决方案1】:

    在这种情况下,您可以使用一个名为 stack 的 numpy 函数:

    all_np_img = np.stack(all_img)
    

    【讨论】:

    • 哇,这非常非常高效!我用旧方法尝试了 1000 次,可能不得不等待一分钟,但这只是眨眼……
    【解决方案2】:

    使用np.vstack:

    pics = list()
    for filename in all_filename_of_img[:100]:
        img = Image.open(filename)
        pics.append(img)
    
    np.vstack(pics)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-21
      • 2014-09-15
      • 2016-12-04
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多