简体   繁体   中英

How to cv2.imread an image within a zipfile?

I'm trying to use OpenCV2 to read images withing a zipfile with cv2.imread and then resize them and save them but I can't figure out how to read those images within the zipfile. This is my code so far:-

import cv2
from zipfile import ZipFile

with ZipFile("sample_images.zip", "r") as zipFile:
    imgs = zipFile.namelist()
    img = zipFile.open(imgs[0])
    processedImg = cv2.imread(img)

This is the error I get:-

Traceback (most recent call last):
  File "C:/Users/Yash/Desktop/Programming/opencv test/test.py", line 8, in <module>
    processedImg = cv2.imread(img)
SystemError: <built-in function imread> returned NULL without setting an error

Please suggest a solution to this problem. Thanks in advance!

Try this

from io import BytesIO
from zipfile import ZipFile
from PIL import Image

with ZipFile("sample_images.zip", "r") as zipFile:
    imgs = zipFile.namelist()
    print(imgs[0])
    img = zipFile.read(imgs[0])
    processedImg = Image.open(BytesIO(img))
    processedImg.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM