使用ZipFile中的ImageIO处理文件

时间:2017-11-13 16:36:29

标签: python zipfile

尝试使用imageio从zipfile读取图像文件时出错:

import zipfile
import glob
import imageio
from os.path import splitext

    for database in glob.iglob('Datasets/*.zip'):
        print(database)
        zf = zipfile.ZipFile(database, 'r')
        for file in zf.namelist():
            basename,extension = splitext(file)
            if extension == '.png':
                img = imageio.imread(file)
                print(img.shape, end='')

这是追溯:

Datasets/first.zip
Traceback (most recent call last):
  File "testZip.py", line 12, in <module>
    img = imageio.imread(file)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 200, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 117, in get_reader
    request = Request(uri, 'r' + mode, **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 120, in __init__
    self._parse_uri(uri)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 252, in _parse_uri
    raise IOError("No such file: '%s'" % fn)
OSError: No such file: 'first/image_7395.png'
[Finished in 0.2s with exit code 1]

有人有线索吗?

由于

2 个答案:

答案 0 :(得分:0)

file变量包含文件名,而不是实际的文件数据。错误很明显:磁盘上不存在名为first/image_7395.png的文件 - 它位于zip中。您需要从zip中提取文件,并将提取的文件用于imageio。例如:

for database in glob.iglob('Datasets/*.zip'):
    print(database)
    zf = zipfile.ZipFile(database, 'r')
    for file in zf.namelist():
        basename,extension = splitext(file)
        if extension == '.png':
            ofile = zf.extract(file)
            img = imageio.imread(ofile)
            print(img.shape, end='')
            # if you need to:
            os.remove(ofile)

编辑:看起来imageio也可以从类似文件的对象中读取,在这种情况下,您可以使用ZipFile.open()并将其传递给imageio。例如:

# ...
if extension == '.png':
    with zf.open(file) as img_file:
        img = imageio.read(img_file)

答案 1 :(得分:0)

您尝试按名称从ZIP打开图像。 imageio不知道该怎么做。它假设您给它一个真正的文件路径。首先打开zip文件,你需要给它一个文件对象。你也可以像@ randomdude999建议一样提取它。

for file in zf.namelist():
    basename,extension = splitext(file)
    if extension == '.png':
        img = imageio.imread(zf.open(file))
        print(img.shape, end='')