如何从可以传递到 OpenCV 中的 ZipFile 对象获取路径?

How to obtain path from ZipFile objects that could be passed into OpenCV?

我想将图像文件传递到 OpenCV 中以创建 NumPy 数组而不解压缩它。

我的代码如下所示:

zip_file = r'D:\Folder\small_img.zip'

with zipfile.ZipFile(zip_file) as zip:
    for info in zip.infolist():
        path_to_image = os.path.abspath(info.filename)
        zip_img = zip.open(info.filename)
        pil_img = Image.open(zip_img).convert('RGB')
        # cv_img = cv.imread(*)

我放一个*的地方是我不知道要传入什么。我创建了几个class枕头Image的变量(pil_img) 和 ZipFileExt (zip_img)。我知道 cv2.imread 只接受一条路径。所以,我试图传入一个路径名,但是我没有解压缩 zip 文件,因此我也尝试创建一个绝对路径 (path_to_image),看起来像 ('D:\Folder\File1.jpg'),和一个看起来像 (File1.jpg).

的文件名 (info.filename)

但是,其中大多数会呈现错误消息:

TypeError: Can't convert object of type 'Image' to 'str' for 'filename'

TypeError: Can't convert object of type 'ZipExtFile' to 'str' for 'filename'

或者,在我传入 path_to_imageinfo.filename 的情况下,它 returns None.

有人知道我可以将什么传递给 cv2.imread 以获得 NumPy 数组吗?

cv2.imdecode 用于此目的:

import cv2
import numpy as np
import zipfile

with zipfile.ZipFile('images.zip') as zf:
    for info in zf.infolist():
        zip_img = zf.open(info.filename)
        cv_img = cv2.imdecode(np.frombuffer(zip_img.read(), dtype=np.uint8),
                              cv2.IMREAD_UNCHANGED)

在从 zipfile.ZipFile.open, you can call read to get the raw bytes. You then need np.frombuffer 获得的 ZipExtFile 对象上为 cv2.imdecode 获得正确的输入。

如果您(也)需要 Pillow Image 对象,您也可以简单地将其转换为某个 NumPy 数组,但必须记住将 RGB (Pillow) 的顺序更正为 BGR ( OpenCV):

import cv2
import numpy as np
from PIL import Image
import zipfile

with zipfile.ZipFile('images.zip') as zf:
    for info in zf.infolist():
        zip_img = zf.open(info.filename)
        pil_img = Image.open(zip_img)
        cv_img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
NumPy:         1.20.2
OpenCV:        4.5.1
Pillow:        8.2.0
----------------------------------------