使用OpenCV加载BytesIO图像

14
我正在尝试从io.BytesIO()结构中使用OPENCV加载图像。 原始代码使用PIL加载图像,如下所示:
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打开:

我尝试像这样使用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。请问有人可以帮助我吗?

2个回答

30

Henrique 试试这个:

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)

4
虽然这段代码“还行”,但我刚刚发布了一个答案,其中包含更短的代码,不需要使用writeimage_lenseekbytearray - Ulrich Stern

-1

arrybn提供的答案对我有用。只需要在cv2.imshow后添加cv2.waitkey(1)即可。以下是代码:

服务器端:

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()

基于示例 捕获到网络流

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接