如何使用文件系统将图像从内存加载到 numpy
How to load images from memory to numpy using file system
我想将我的图像目录存储在内存中,然后将图像加载到一个 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('.'))
Returns:
['my_image_1.jpg', 'my_image_2.jpg']
如何将 内存中 的图像加载到 numpy 中?
我也愿意接受 fs 包的替代品。
作为 per the documentation, Pillow's Image.open
accepts a file object instead of a file name, so as long as your in-memory file package provides Python file objects (which it most likely does), you can just use them. If it doesn't, you could even just wrap them in a class that provides the required methods. Assuming you are using PyFilesystem
, according to 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
——原理是一样的)
我想将我的图像目录存储在内存中,然后将图像加载到一个 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('.'))
Returns:
['my_image_1.jpg', 'my_image_2.jpg']
如何将 内存中 的图像加载到 numpy 中?
我也愿意接受 fs 包的替代品。
作为 per the documentation, Pillow's Image.open
accepts a file object instead of a file name, so as long as your in-memory file package provides Python file objects (which it most likely does), you can just use them. If it doesn't, you could even just wrap them in a class that provides the required methods. Assuming you are using PyFilesystem
, according to 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
——原理是一样的)