我试图从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打开:
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。拜托,有人可以帮助我吗?
答案 0 :(得分:7)
Henrique的 试试这个:
import numpy as np
import cv2 as cv
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)
答案 1 :(得分:-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()