Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python opencv to load image from zip

Tags:

python

opencv

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 imdecode?

The question is: how can I open this using imread or imdecode for further processing in opencv without saving the image first?

Update:

Here the expected errors I get. I need to convert 'data' into a type that can be consumed by opencv.

data = zfile.read('test.jpg')
buf = StringIO.StringIO(data)
im = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
# results in error: TypeError: buf is not a numpy array, neither a scalar

a = np.asarray(buf)
cv2.imdecode(a, cv2.IMREAD_GRAYSCALE)
# results in error: TypeError: buf data type = 17 is not supported
like image 974
IUnknown Avatar asked Jan 25 '14 22:01

IUnknown


1 Answers

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)    
like image 78
HYRY Avatar answered Oct 13 '22 16:10

HYRY