我能够从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中进行进一步处理?
更新
这是我得到的预期错误。我需要将'data'转换为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
答案 0 :(得分:15)
使用numpy.frombuffer()
从字符串创建uint8数组:
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)
答案 1 :(得分:-1)
HYRY's answer确实提供了最优雅的解决方案
使用Python阅读图像并不完全符合"There should be one-- and preferably only one --obvious way to do it."
有时您可能宁愿避免在应用程序的某些部分使用numpy
。并改用Pillow
或imread
。如果有一天你发现自己处于这种状况,那么希望下面的代码片段会有用:
import zipfile
with zipfile.ZipFile('test.zip', 'r') as zfile:
data = zfile.read('test.jpg')
# Pillow
from 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)
print type(np_im_array_from_pil), np_im_array_from_pil.shape
# <type 'numpy.ndarray'> (348, 500, 3)
# imread
from imread import imread_from_blob
np_im_array = imread_from_blob(data, "jpg")
print type(np_im_array), np_im_array.shape
# <type 'numpy.ndarray'> (348, 500, 3)
对"How to read raw png from an array in python opencv?"的回答提供了类似的解决方案。