Skip to content
Advertisement

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

I would like to pass the image file into OpenCV to create a NumPy array without unzipping it.

My code looks like this:

JavaScript

The place where I put a * is what I’m not sure what to pass in. I have created a few variables of class Pillow Image (pil_img), and ZipFileExt (zip_img). I understand that cv2.imread only accepts a path. So, I have tried to pass in a path name, however I have not de-zipped the zip file, hence I also tried to create a absolute path (path_to_image) that looks like ('D:FolderFile1.jpg'), and a file name (info.filename) that looks like (File1.jpg).

However, most of them render an error message:

JavaScript

or

JavaScript

Or, in the case where I pass in path_to_image or info.filename, it returns None.

Anyone knows what I could pass into cv2.imread to get the NumPy array?

Advertisement

Answer

There’s cv2.imdecode for that purpose:

JavaScript

On the ZipExtFile object obtained from zipfile.ZipFile.open, you can call read to get the raw bytes. You then need np.frombuffer to get a proper input for cv2.imdecode.

If you (also) need the Pillow Image object, you could also simply cast that one to some NumPy array, but have to keep in mind to correct the ordering from RGB (Pillow) to BGR (OpenCV):

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement