将压缩文件(例如 zip 文件)中的图像转换为 python 中的 numpy 数组

Convert images in a compressed file such as a zip file to numpy array in python

我们可以组合模块 zipfile.ZipFilePIL.Image.open 从压缩文件中读取图像。但是,我们可能会在调用 PIL.Image.open 后收到错误 io.UnsupportedOperation: seek。它指的是我将 ZipExtFile 对象传递给 PIL.Image.open 函数的条件如下:

 from zipfile import ZipFile
 from PIL import Image

 zipf = ZipFile(path, "r")

 f = zipf.open("test.jpg")

 img = Image.open(f)

那么,如何解决这个问题?

其实我们可以通过读取图像的内容,然后将其转换为cStringIO缓冲区来解决这个问题。代码如下:

from zipfile import ZipFile
from PIL import Image

zipf = ZipFile(path, "r")

# read instead of open
content = zipf.read("test.jpg")

img = Image.open(cStringIO.StringIO(content))

在 python 3.7 ZipExtFile 中,对象现在支持查找操作。如果您升级到 python 3.7.2 或更高版本,那么您的代码应该可以工作。