【问题标题】:How to load images from memory to numpy using file system如何使用文件系统将图像从内存加载到 numpy
【发布时间】:2022-02-14 07:52:01
【问题描述】:

我想将我的图像目录存储在内存中,然后将图像加载到一个 numpy 数组中。

加载不在内存中的图片的规范方式如下:

import PIL.Image
import numpy as np

image = PIL.Image.open("./image_dir/my_image_1.jpg")
image = np.array(image)

但是,当图像在内存中时,我不确定如何执行此操作。到目前为止,我已经能够设置以下启动代码:

import fs
import fs.memoryfs
import fs.osfs

image_dir = "./image_dir"

mem_fs = fs.memoryfs.MemoryFS()
drv_fs = fs.osfs.OSFS(image_path)

fs.copy.copy_fs(drv_fs, mem_fs)

print(mem_fs.listdir('.'))

返回:

['my_image_1.jpg', 'my_image_2.jpg']

如何将内存中的图像加载到 numpy 中?

我也对 fs 包的替代品持开放态度。

【问题讨论】:

    标签: python numpy memory python-imaging-library


    【解决方案1】:

    作为per the documentation,Pillow 的Image.open 接受文件对象而不是文件名,因此只要您的内存文件包提供Python 文件对象(它很可能提供),您就可以使用它们。如果没有,您甚至可以将它们包装在提供所需方法的类中。假设您使用的是PyFilesystem,根据its documentation,您应该没问题。

    所以,你想要这样的东西:

    import numpy as np
    import PIL.Image
    import fs.memoryfs
    import fs.osfs
    import fs.copy
    
    mem_fs = fs.memoryfs.MemoryFS()
    drv_fs = fs.osfs.OSFS("./image_dir")
    
    fs.copy.copy_file(drv_fs, './my_image_1.jpg', mem_fs, 'test.jpg')
    
    with mem_fs.openbin('test.jpg') as f:
        image = PIL.Image.open(f)
        image = np.array(image)
    

    (注意我只是用copy_file,因为我用单个文件测试,如果你需要复制整个树,你可以使用copy_fs——原理是一样的)

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多