使用python opencv从zip加载图像 [英] Using python opencv to load image from zip

查看:156
本文介绍了使用python opencv从zip加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够从 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 imdecode?

问题是:如何在不先保存图像的情况下使用 imread 或 imdecode 打开它以在 opencv 中进一步处理?

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

更新:

这是我得到的预期错误.我需要将数据"转换为opencv可以使用的类型.

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

推荐答案

use numpy.frombuffer() 从字符串创建一个 uint8 数组:

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)    

这篇关于使用python opencv从zip加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆