Load BytesIO image with opencv
Asked Answered
I

2

14

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?

Incept answered 7/10, 2017 at 19:48 Comment(0)
S
33

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)
Schild answered 20/11, 2017 at 10:17 Comment(1)
While this is "ok" code, I just posted an answer with shorter code without the need for write, image_len, seek, and bytearray.Arduous
S
-1

The answer delivered by arrybn, worked for me. It was only necessary to add a cv2.waitkey(1) after cv2.imshow. Here is the code:

Server Side:

import io
import socket
import struct
import cv2
import numpy as np

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)

connection = server_socket.accept()[0].makefile('rb')
cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
try:
    while True:
        image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
        if not image_len:
            break
        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 = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
        cv2.imshow("Image", img)
        cv2.waitKey(1)
finally:
    connection.close()
    server_socket.close()

Based on the example Capturing to a network stream

Smite answered 5/11, 2018 at 17:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.