Skip to content Skip to sidebar Skip to footer

Using Python Opencv To Load Image From Zip

I am able to successfully load an image from a zip: with zipfile.ZipFile('test.zip', 'r') as zfile: data = zfile.read('test.jpg') # how to open this using imread or imdecod

Solution 1:

use numpy.frombuffer() to create a uint8 array from the string:

import zipfile
import cv2
import numpy as np

with zipfile.ZipFile('test.zip', 'r') as zfile:
    data = zfile.read('test.jpg')

img = cv2.imdecode(np.frombuffer(data, np.uint8), 1)    

Solution 2:

HYRY's answer does indeed provide the most elegant solution


Reading images in Python doesn't quite comply with "There should be one-- and preferably only one --obvious way to do it."

It is possible that sometimes you'd rather avoid using numpy in some parts of your application. And use Pillow or imread instead. If one day you find yourself in such situation, then hopefully following code snippet will be of some use:

import zipfile

with zipfile.ZipFile('test.zip', 'r') as zfile:
    data = zfile.read('test.jpg')

# Pillowfrom PIL import Image
from StringIO import StringIO
import numpy as np
filelike_buffer = StringIO(data)
pil_image = Image.open(filelike_buffer)
np_im_array_from_pil = np.asarray(pil_image)
printtype(np_im_array_from_pil), np_im_array_from_pil.shape
# <type 'numpy.ndarray'> (348, 500, 3)# imreadfrom imread import imread_from_blob
np_im_array = imread_from_blob(data, "jpg")
printtype(np_im_array), np_im_array.shape
# <type 'numpy.ndarray'> (348, 500, 3)

Answer to "How to read raw png from an array in python opencv?" provides similar solution.

Post a Comment for "Using Python Opencv To Load Image From Zip"