简体   繁体   English

将str转换为numpy.ndarray

[英]Convert str to numpy.ndarray

I'm creating a system to share video with opencv but I've got a problem. 我正在创建一个与opencv共享视频的系统,但是我遇到了问题。 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 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: ret是一个booland框架,是数据视频,一个numpy.ndarray ret没问题,但是是框架:我先将其转换为字符串,然后转换为字节:

frame = str(frame).encode()
connexion_avec_serveur.send(frame)

I'd like now to convert again frame in a numpy.ndarray. 我现在想再次转换一个numpy.ndarray中的帧。

Your str(frame).encode() is wrong. 您的str(frame).encode()错误。 If you print it to terminal, then you will find it is not the data of the frame. 如果将其打印到终端,则会发现它不是框架的数据。

An alternative method is to use tobytes() and frombuffer() . 另一种方法是使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM