我正在尝试从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。有人能帮帮我吗?
发布于 2017-11-20 18:17:03
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)
发布于 2018-11-06 01:27:34
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()
https://stackoverflow.com/questions/46624449
复制相似问题