【问题标题】:is there a way to create numpy array from a list of images?有没有办法从图像列表中创建 numpy 数组?
【发布时间】:2021-08-30 01:54:28
【问题描述】:

我正在尝试从包含 1768 张图像的列表中创建 numpy 数组。这是我的代码:

w = []
directory = os.listdir(PATH)
directory = sorted(directory, key=len)
for item in directory:
    img = Image.open(os.path.join(PATH, item))
    w.append(img)
    count+=1
print('w_shape: ', np.array(w, dtype='float32').shape)

当运行它时,我遇到了这个错误:

TypeError: float() argument must be a string or a number, not 'JpegImageFile'

谁能帮我解决?

【问题讨论】:

  • 你希望得到的数组是什么样子的?它的shape 应该是什么?你希望通过创建数组来解决什么问题?
  • 问题与artificial-intelligence 无关 - 请不要向无关标签发送垃圾邮件(已删除)。

标签: python numpy


【解决方案1】:

您收到此错误是因为您列出的每个元素都是一个与float() 不兼容的“JpegImageFile”。为避免这种情况,请将图像作为数组直接添加到您的列表中。
您可以使用 np.asarray() 将图像读取为 numpy 数组。查看下面的代码 sn-p:

w = []
directory = os.listdir(PATH)
directory = sorted(directory, key=len)
for item in directory:
    img = Image.open(os.path.join(PATH, item))
    w.append(np.asarray(img)) # convert it to an array of floats
    count+=1 
print('w_shape: ', np.array(w, dtype='float32').shape)

注意:您也可以改用np.array(img)。看看有什么区别here

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2015-05-08
    • 2018-10-13
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    相关资源
    最近更新 更多