2017-10-07 1282 views
2

我试图从io.BytesIO()结构中加载OPENCV的图像。 原来,代码加载图像与PIL,如下图所示:使用opencv加载BytesIO图像

image_stream = io.BytesIO() 
image_stream.write(connection.read(image_len)) 
image_stream.seek(0) 
image = Image.open(image_stream) 
print('Image is %dx%d' % image.size) 

我试着用OPENCV像打开:

image_stream = io.BytesIO() 
image_stream.write(connection.read(image_len)) 
image_stream.seek(0) 
img = cv2.imread(image_stream,0) 
cv2.imshow('image',img) 

但似乎imread不BytesIO处理() 。我收到一个错误。

我使用OPENCV 3.3和Python 2.7。请,有人可以帮我吗?

回答

1

恩里克 试试这个:

import numpy as np 

image_stream = io.BytesIO() 
image_stream.write(connection.read(image_len)) 
image_stream.seek(0) 
file_bytes = np.asarray(bytearray(img_stream.read()), dtype=np.uint8) 
img = cv.imdecode(file_bytes, cv.IMREAD_COLOR)