将str转换为numpy.ndarray

时间:2017-12-26 10:50:45

标签: python string numpy opencv byte

我正在创建一个与opencv共享视频的系统,但我遇到了问题。 我有一个服务器和一个客户端但是当我向服务器发送信息时,必须是字节。 我送了两件东西:

 ret, frame = cap.read()
ret是一个booland框架是数据视频,一个numpy.ndarray ret不是问题而是框架: 我将其转换为字符串,然后以字节转换:

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

我现在想在numpy.ndarray中再次转换帧。

1 个答案:

答案 0 :(得分:1)

您的str(frame).encode()错了。如果将其打印到终端,则会发现它不是帧的数据。

另一种方法是使用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))
相关问题