将str转换为numpy.ndarray [英] Convert str to numpy.ndarray
问题描述
我正在创建一个与opencv共享视频的系统,但是我遇到了问题. 我有一个服务器和一个客户端,但是当我向服务器发送信息时,必须为字节. 我发送了2件事:
I'm creating a system to share video with opencv but I've got a problem. I've a server and a client but when I send informations to the server, the must be bytes. I send 2 things:
ret, frame = cap.read()
ret是一个booland框架,是数据视频,一个numpy.ndarray ret不是问题,而是框架: 我先将其转换为字符串,然后转换为字节:
ret is a booland frame is the data video, a numpy.ndarray ret is not a problem but frame: I convert it in string and then in bytes:
frame = str(frame).encode()
connexion_avec_serveur.send(frame)
我现在想再次将一个帧转换为numpy.ndarray.
I'd like now to convert again frame in a numpy.ndarray.
推荐答案
您的str(frame).encode()
错误.如果将其打印到终端,则会发现它不是框架的数据.
Your str(frame).encode()
is wrong. If you print it to terminal, then you will find it is not the data of the frame.
另一种方法是使用tobytes()
和frombuffer()
.
## read
ret, frame = cap.read()
sz = frame.shape
## tobytes
frame_bytes = frame.tobytes()
print(type(frame_bytes))
# <class 'bytes'>
## frombuffer and reshape
frame_frombytes = np.frombuffer(frame_bytes, dtype=np.uint8).reshape(sz)
print(type(frame_frombytes))
## <class 'numpy.ndarray'>
## test whether they equal or not
print(np.array_equal(frame, frame_frombytes))
这篇关于将str转换为numpy.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!