Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load BytesIO image with opencv

I'm trying to load an image with OPENCV from an io.BytesIO() structure. Originally, the code loads the image with PIL, like below:

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)

I tried to open with OPENCV like that:

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)

But it seems that imread doesn't deal with BytesIO(). I'm getting an error.

I'm using OPENCV 3.3 and Python 2.7. Please, could someone help me?

like image 794
Henrique Avatar asked Oct 07 '17 19:10

Henrique


1 Answers

Henrique Try this:

import numpy as np
import cv2 as cv
import io

image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8)
img = cv.imdecode(file_bytes, cv.IMREAD_COLOR)
like image 195
arrybn Avatar answered Oct 23 '22 09:10

arrybn